+ Correction and a minor optimisation
[melted] / src / modules / avformat / consumer_avformat.c
1 /*
2 * consumer_avformat.c -- an encoder based on avformat
3 * Copyright (C) 2003-2004 Ushodaya Enterprises Limited
4 * Author: Charles Yates <charles.yates@pandora.be>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 */
20
21 // Local header files
22 #include "consumer_avformat.h"
23
24 // mlt Header files
25 #include <framework/mlt_frame.h>
26
27 // System header files
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <limits.h>
32 #include <pthread.h>
33 #include <sys/time.h>
34 #include <math.h>
35
36 // avformat header files
37 #include <avformat.h>
38
39 //
40 // This structure should be extended and made globally available in mlt
41 //
42
43 typedef struct
44 {
45 int16_t *buffer;
46 int size;
47 int used;
48 double time;
49 int frequency;
50 int channels;
51 }
52 *sample_fifo, sample_fifo_s;
53
54 sample_fifo sample_fifo_init( int frequency, int channels )
55 {
56 sample_fifo this = calloc( 1, sizeof( sample_fifo_s ) );
57 this->frequency = frequency;
58 this->channels = channels;
59 return this;
60 }
61
62 // sample_fifo_clear and check are temporarily aborted (not working as intended)
63
64 void sample_fifo_clear( sample_fifo this, double time )
65 {
66 int words = ( float )( time - this->time ) * this->frequency * this->channels;
67 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) && this->used > words && words > 0 )
68 {
69 memmove( this->buffer, &this->buffer[ words ], ( this->used - words ) * sizeof( int16_t ) );
70 this->used -= words;
71 this->time = time;
72 }
73 else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )this->time * 100 ) )
74 {
75 this->used = 0;
76 this->time = time;
77 }
78 }
79
80 void sample_fifo_check( sample_fifo this, double time )
81 {
82 if ( this->used == 0 )
83 {
84 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) )
85 this->time = time;
86 }
87 }
88
89 void sample_fifo_append( sample_fifo this, int16_t *samples, int count )
90 {
91 if ( ( this->size - this->used ) < count )
92 {
93 this->size += count * 5;
94 this->buffer = realloc( this->buffer, this->size * sizeof( int16_t ) );
95 }
96
97 memcpy( &this->buffer[ this->used ], samples, count * sizeof( int16_t ) );
98 this->used += count;
99 }
100
101 int sample_fifo_used( sample_fifo this )
102 {
103 return this->used;
104 }
105
106 int sample_fifo_fetch( sample_fifo this, int16_t *samples, int count )
107 {
108 if ( count > this->used )
109 count = this->used;
110
111 memcpy( samples, this->buffer, count * sizeof( int16_t ) );
112 this->used -= count;
113 memmove( this->buffer, &this->buffer[ count ], this->used * sizeof( int16_t ) );
114
115 this->time += ( double )count / this->channels / this->frequency;
116
117 return count;
118 }
119
120 void sample_fifo_close( sample_fifo this )
121 {
122 free( this->buffer );
123 free( this );
124 }
125
126 // Forward references.
127 static int consumer_start( mlt_consumer this );
128 static int consumer_stop( mlt_consumer this );
129 static int consumer_is_stopped( mlt_consumer this );
130 static void *consumer_thread( void *arg );
131 static void consumer_close( mlt_consumer this );
132
133 /** Initialise the dv consumer.
134 */
135
136 mlt_consumer consumer_avformat_init( char *arg )
137 {
138 // Allocate the consumer
139 mlt_consumer this = mlt_consumer_new( );
140
141 // If memory allocated and initialises without error
142 if ( this != NULL )
143 {
144 // Get properties from the consumer
145 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
146
147 // Assign close callback
148 this->close = consumer_close;
149
150 // Interpret the argument
151 if ( arg != NULL )
152 mlt_properties_set( properties, "target", arg );
153
154 // sample and frame queue
155 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
156
157 // Set avformat defaults (all lifted from ffmpeg.c)
158 mlt_properties_set_int( properties, "audio_bit_rate", 128000 );
159 mlt_properties_set_int( properties, "video_bit_rate", 200 * 1000 );
160 mlt_properties_set_int( properties, "video_bit_rate_tolerance", 4000 * 1000 );
161 mlt_properties_set_int( properties, "gop_size", 12 );
162 mlt_properties_set_int( properties, "b_frames", 0 );
163 mlt_properties_set_int( properties, "mb_decision", FF_MB_DECISION_SIMPLE );
164 mlt_properties_set_double( properties, "qscale", 0 );
165 mlt_properties_set_int( properties, "me_method", ME_EPZS );
166 mlt_properties_set_int( properties, "mb_cmp", FF_CMP_SAD );
167 mlt_properties_set_int( properties, "ildct_cmp", FF_CMP_VSAD );
168 mlt_properties_set_int( properties, "sub_cmp", FF_CMP_SAD );
169 mlt_properties_set_int( properties, "cmp", FF_CMP_SAD );
170 mlt_properties_set_int( properties, "pre_cmp", FF_CMP_SAD );
171 mlt_properties_set_int( properties, "pre_me", 0 );
172 mlt_properties_set_double( properties, "lumi_mask", 0 );
173 mlt_properties_set_double( properties, "dark_mask", 0 );
174 mlt_properties_set_double( properties, "scplx_mask", 0 );
175 mlt_properties_set_double( properties, "tcplx_mask", 0 );
176 mlt_properties_set_double( properties, "p_mask", 0 );
177 mlt_properties_set_int( properties, "qns", 0 );
178 mlt_properties_set_int( properties, "video_qmin", 2 );
179 mlt_properties_set_int( properties, "video_qmax", 31 );
180 mlt_properties_set_int( properties, "video_lmin", 2*FF_QP2LAMBDA );
181 mlt_properties_set_int( properties, "video_lmax", 31*FF_QP2LAMBDA );
182 mlt_properties_set_int( properties, "video_mb_qmin", 2 );
183 mlt_properties_set_int( properties, "video_mb_qmax", 31 );
184 mlt_properties_set_int( properties, "video_qdiff", 3 );
185 mlt_properties_set_double( properties, "video_qblur", 0.5 );
186 mlt_properties_set_double( properties, "video_qcomp", 0.5 );
187 mlt_properties_set_int( properties, "video_rc_max_rate", 0 );
188 mlt_properties_set_int( properties, "video_rc_min_rate", 0 );
189 mlt_properties_set_int( properties, "video_rc_buffer_size", 0 );
190 mlt_properties_set_double( properties, "video_rc_buffer_aggressivity", 1.0 );
191 mlt_properties_set_double( properties, "video_rc_initial_cplx", 0 );
192 mlt_properties_set_double( properties, "video_i_qfactor", 1.25 );
193 mlt_properties_set_double( properties, "video_b_qfactor", 1.25 );
194 mlt_properties_set_double( properties, "video_i_qoffset", -0.8 );
195 mlt_properties_set_double( properties, "video_b_qoffset", 0 );
196 mlt_properties_set_int( properties, "video_intra_quant_bias", FF_DEFAULT_QUANT_BIAS );
197 mlt_properties_set_int( properties, "video_inter_quant_bias", FF_DEFAULT_QUANT_BIAS );
198 mlt_properties_set_int( properties, "dct_algo", 0 );
199 mlt_properties_set_int( properties, "idct_algo", 0 );
200 mlt_properties_set_int( properties, "me_threshold", 0 );
201 mlt_properties_set_int( properties, "mb_threshold", 0 );
202 mlt_properties_set_int( properties, "intra_dc_precision", 0 );
203 mlt_properties_set_int( properties, "strict", 0 );
204 mlt_properties_set_int( properties, "error_rate", 0 );
205 mlt_properties_set_int( properties, "noise_reduction", 0 );
206 mlt_properties_set_int( properties, "sc_threshold", 0 );
207 mlt_properties_set_int( properties, "me_range", 0 );
208 mlt_properties_set_int( properties, "coder", 0 );
209 mlt_properties_set_int( properties, "context", 0 );
210 mlt_properties_set_int( properties, "predictor", 0 );
211
212 // Ensure termination at end of the stream
213 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
214
215 // Set up start/stop/terminated callbacks
216 this->start = consumer_start;
217 this->stop = consumer_stop;
218 this->is_stopped = consumer_is_stopped;
219 }
220
221 // Return this
222 return this;
223 }
224
225 /** Start the consumer.
226 */
227
228 static int consumer_start( mlt_consumer this )
229 {
230 // Get the properties
231 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
232
233 // Check that we're not already running
234 if ( !mlt_properties_get_int( properties, "running" ) )
235 {
236 // Allocate a thread
237 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
238
239 // Get the width and height
240 int width = mlt_properties_get_int( properties, "width" );
241 int height = mlt_properties_get_int( properties, "height" );
242
243 // Obtain the size property
244 char *size = mlt_properties_get( properties, "size" );
245
246 // Interpret it
247 if ( size != NULL )
248 {
249 int tw, th;
250 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
251 {
252 width = tw;
253 height = th;
254 }
255 else
256 {
257 fprintf( stderr, "consumer_avformat: Invalid size property %s - ignoring.\n", size );
258 }
259 }
260
261 // Now ensure we honour the multiple of two requested by libavformat
262 mlt_properties_set_int( properties, "width", ( width / 2 ) * 2 );
263 mlt_properties_set_int( properties, "height", ( height / 2 ) * 2 );
264
265 // Assign the thread to properties
266 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
267
268 // Set the running state
269 mlt_properties_set_int( properties, "running", 1 );
270
271 // Create the thread
272 pthread_create( thread, NULL, consumer_thread, this );
273 }
274 return 0;
275 }
276
277 /** Stop the consumer.
278 */
279
280 static int consumer_stop( mlt_consumer this )
281 {
282 // Get the properties
283 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
284
285 // Check that we're running
286 if ( mlt_properties_get_int( properties, "running" ) )
287 {
288 // Get the thread
289 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
290
291 // Stop the thread
292 mlt_properties_set_int( properties, "running", 0 );
293
294 // Wait for termination
295 pthread_join( *thread, NULL );
296 }
297
298 return 0;
299 }
300
301 /** Determine if the consumer is stopped.
302 */
303
304 static int consumer_is_stopped( mlt_consumer this )
305 {
306 // Get the properties
307 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
308 return !mlt_properties_get_int( properties, "running" );
309 }
310
311 /** Add an audio output stream
312 */
313
314 static AVStream *add_audio_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
315 {
316 // Get the properties
317 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
318
319 // Create a new stream
320 AVStream *st = av_new_stream( oc, 1 );
321
322 // If created, then initialise from properties
323 if ( st != NULL )
324 {
325 AVCodecContext *c = st->codec;
326 c->codec_id = codec_id;
327 c->codec_type = CODEC_TYPE_AUDIO;
328
329 // Put sample parameters
330 c->bit_rate = mlt_properties_get_int( properties, "audio_bit_rate" );
331 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
332 c->channels = mlt_properties_get_int( properties, "channels" );
333
334 // Allow the user to override the audio fourcc
335 if ( mlt_properties_get( properties, "afourcc" ) )
336 {
337 char *tail = NULL;
338 char *arg = mlt_properties_get( properties, "afourcc" );
339 int tag = strtol( arg, &tail, 0);
340 if( !tail || *tail )
341 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
342 c->codec_tag = tag;
343 }
344 }
345 else
346 {
347 fprintf( stderr, "Could not allocate a stream for audio\n" );
348 }
349
350 return st;
351 }
352
353 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
354 {
355 // We will return the audio input size from here
356 int audio_input_frame_size = 0;
357
358 // Get the context
359 AVCodecContext *c = st->codec;
360
361 // Find the encoder
362 AVCodec *codec = avcodec_find_encoder( c->codec_id );
363
364 // Continue if codec found and we can open it
365 if ( codec != NULL && avcodec_open(c, codec) >= 0 )
366 {
367 // ugly hack for PCM codecs (will be removed ASAP with new PCM
368 // support to compute the input frame size in samples
369 if ( c->frame_size <= 1 )
370 {
371 audio_input_frame_size = audio_outbuf_size / c->channels;
372 switch(st->codec->codec_id)
373 {
374 case CODEC_ID_PCM_S16LE:
375 case CODEC_ID_PCM_S16BE:
376 case CODEC_ID_PCM_U16LE:
377 case CODEC_ID_PCM_U16BE:
378 audio_input_frame_size >>= 1;
379 break;
380 default:
381 break;
382 }
383 }
384 else
385 {
386 audio_input_frame_size = c->frame_size;
387 }
388
389 // Some formats want stream headers to be seperate (hmm)
390 if( !strcmp( oc->oformat->name, "mp4" ) ||
391 !strcmp( oc->oformat->name, "mov" ) ||
392 !strcmp( oc->oformat->name, "3gp" ) )
393 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
394 }
395 else
396 {
397 fprintf( stderr, "Unable to encode audio - disabling audio output.\n" );
398 }
399
400 return audio_input_frame_size;
401 }
402
403 static void close_audio( AVFormatContext *oc, AVStream *st )
404 {
405 avcodec_close( st->codec );
406 }
407
408 /** Add a video output stream
409 */
410
411 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
412 {
413 // Get the properties
414 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
415
416 // Create a new stream
417 AVStream *st = av_new_stream( oc, 0 );
418
419 if ( st != NULL )
420 {
421 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
422 double ar = mlt_properties_get_double( properties, "display_ratio" );
423 AVCodecContext *c = st->codec;
424 c->codec_id = codec_id;
425 c->codec_type = CODEC_TYPE_VIDEO;
426
427 // put sample parameters
428 c->bit_rate = mlt_properties_get_int( properties, "video_bit_rate" );
429 c->bit_rate_tolerance = mlt_properties_get_int( properties, "video_bit_rate_tolerance" );
430 c->width = mlt_properties_get_int( properties, "width" );
431 c->height = mlt_properties_get_int( properties, "height" );
432 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
433 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
434 c->gop_size = mlt_properties_get_int( properties, "gop_size" );
435 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
436
437 if ( mlt_properties_get_int( properties, "b_frames" ) )
438 {
439 c->max_b_frames = mlt_properties_get_int( properties, "b_frames" );
440 c->b_frame_strategy = 0;
441 c->b_quant_factor = 2.0;
442 }
443
444 c->mb_decision = mlt_properties_get_int( properties, "mb_decision" );
445 c->sample_aspect_ratio = av_d2q( ar * c->height / c->width , 255);
446 c->mb_cmp = mlt_properties_get_int( properties, "mb_cmp" );
447 c->ildct_cmp = mlt_properties_get_int( properties, "ildct_cmp" );
448 c->me_sub_cmp = mlt_properties_get_int( properties, "sub_cmp" );
449 c->me_cmp = mlt_properties_get_int( properties, "cmp" );
450 c->me_pre_cmp = mlt_properties_get_int( properties, "pre_cmp" );
451 c->pre_me = mlt_properties_get_int( properties, "pre_me" );
452 c->lumi_masking = mlt_properties_get_double( properties, "lumi_mask" );
453 c->dark_masking = mlt_properties_get_double( properties, "dark_mask" );
454 c->spatial_cplx_masking = mlt_properties_get_double( properties, "scplx_mask" );
455 c->temporal_cplx_masking = mlt_properties_get_double( properties, "tcplx_mask" );
456 c->p_masking = mlt_properties_get_double( properties, "p_mask" );
457 c->quantizer_noise_shaping= mlt_properties_get_int( properties, "qns" );
458 c->qmin = mlt_properties_get_int( properties, "video_qmin" );
459 c->qmax = mlt_properties_get_int( properties, "video_qmax" );
460 c->lmin = mlt_properties_get_int( properties, "video_lmin" );
461 c->lmax = mlt_properties_get_int( properties, "video_lmax" );
462 c->mb_qmin = mlt_properties_get_int( properties, "video_mb_qmin" );
463 c->mb_qmax = mlt_properties_get_int( properties, "video_mb_qmax" );
464 c->max_qdiff = mlt_properties_get_int( properties, "video_qdiff" );
465 c->qblur = mlt_properties_get_double( properties, "video_qblur" );
466 c->qcompress = mlt_properties_get_double( properties, "video_qcomp" );
467
468 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
469 {
470 c->flags |= CODEC_FLAG_QSCALE;
471 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
472 }
473
474 // Allow the user to override the video fourcc
475 if ( mlt_properties_get( properties, "vfourcc" ) )
476 {
477 char *tail = NULL;
478 const char *arg = mlt_properties_get( properties, "vfourcc" );
479 int tag = strtol( arg, &tail, 0);
480 if( !tail || *tail )
481 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
482 c->codec_tag = tag;
483 }
484
485 // Some formats want stream headers to be seperate
486 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
487 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
488
489 c->rc_max_rate = mlt_properties_get_int( properties, "video_rc_max_rate" );
490 c->rc_min_rate = mlt_properties_get_int( properties, "video_rc_min_rate" );
491 c->rc_buffer_size = mlt_properties_get_int( properties, "video_rc_buffer_size" );
492 c->rc_buffer_aggressivity= mlt_properties_get_double( properties, "video_rc_buffer_aggressivity" );
493 c->rc_initial_cplx= mlt_properties_get_double( properties, "video_rc_initial_cplx" );
494 c->i_quant_factor = mlt_properties_get_double( properties, "video_i_qfactor" );
495 c->b_quant_factor = mlt_properties_get_double( properties, "video_b_qfactor" );
496 c->i_quant_offset = mlt_properties_get_double( properties, "video_i_qoffset" );
497 c->b_quant_offset = mlt_properties_get_double( properties, "video_b_qoffset" );
498 c->intra_quant_bias = mlt_properties_get_int( properties, "video_intra_quant_bias" );
499 c->inter_quant_bias = mlt_properties_get_int( properties, "video_inter_quant_bias" );
500 c->dct_algo = mlt_properties_get_int( properties, "dct_algo" );
501 c->idct_algo = mlt_properties_get_int( properties, "idct_algo" );
502 c->me_threshold= mlt_properties_get_int( properties, "me_threshold" );
503 c->mb_threshold= mlt_properties_get_int( properties, "mb_threshold" );
504 c->intra_dc_precision= mlt_properties_get_int( properties, "intra_dc_precision" );
505 c->strict_std_compliance = mlt_properties_get_int( properties, "strict" );
506 c->error_rate = mlt_properties_get_int( properties, "error_rate" );
507 c->noise_reduction= mlt_properties_get_int( properties, "noise_reduction" );
508 c->scenechange_threshold= mlt_properties_get_int( properties, "sc_threshold" );
509 c->me_range = mlt_properties_get_int( properties, "me_range" );
510 c->coder_type= mlt_properties_get_int( properties, "coder" );
511 c->context_model= mlt_properties_get_int( properties, "context" );
512 c->prediction_method= mlt_properties_get_int( properties, "predictor" );
513 c->me_method = mlt_properties_get_int( properties, "me_method" );
514 }
515 else
516 {
517 fprintf( stderr, "Could not allocate a stream for video\n" );
518 }
519
520 return st;
521 }
522
523 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
524 {
525 // Allocate a frame
526 AVFrame *picture = avcodec_alloc_frame();
527
528 // Determine size of the
529 int size = avpicture_get_size(pix_fmt, width, height);
530
531 // Allocate the picture buf
532 uint8_t *picture_buf = av_malloc(size);
533
534 // If we have both, then fill the image
535 if ( picture != NULL && picture_buf != NULL )
536 {
537 // Fill the frame with the allocated buffer
538 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
539 }
540 else
541 {
542 // Something failed - clean up what we can
543 av_free( picture );
544 av_free( picture_buf );
545 picture = NULL;
546 }
547
548 return picture;
549 }
550
551 static int open_video(AVFormatContext *oc, AVStream *st)
552 {
553 // Get the codec
554 AVCodecContext *video_enc = st->codec;
555
556 // find the video encoder
557 AVCodec *codec = avcodec_find_encoder( video_enc->codec_id );
558
559 if( codec && codec->pix_fmts )
560 {
561 const enum PixelFormat *p = codec->pix_fmts;
562 for( ; *p!=-1; p++ )
563 {
564 if( *p == video_enc->pix_fmt )
565 break;
566 }
567 if( *p == -1 )
568 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
569 }
570
571 // Open the codec safely
572 return codec != NULL && avcodec_open( video_enc, codec ) >= 0;
573 }
574
575 void close_video(AVFormatContext *oc, AVStream *st)
576 {
577 avcodec_close(st->codec);
578 }
579
580 static inline long time_difference( struct timeval *time1 )
581 {
582 struct timeval time2;
583 gettimeofday( &time2, NULL );
584 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
585 }
586
587 /** The main thread - the argument is simply the consumer.
588 */
589
590 static void *consumer_thread( void *arg )
591 {
592 // Map the argument to the object
593 mlt_consumer this = arg;
594
595 // Get the properties
596 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
597
598 // Get the terminate on pause property
599 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
600 int terminated = 0;
601
602 // Determine if feed is slow (for realtime stuff)
603 int real_time_output = mlt_properties_get_int( properties, "real_time" );
604
605 // Time structures
606 struct timeval ante;
607
608 // Get the frame rate
609 int fps = mlt_properties_get_double( properties, "fps" );
610
611 // Get width and height
612 int width = mlt_properties_get_int( properties, "width" );
613 int height = mlt_properties_get_int( properties, "height" );
614 int img_width = width;
615 int img_height = height;
616
617 // Get default audio properties
618 mlt_audio_format aud_fmt = mlt_audio_pcm;
619 int channels = mlt_properties_get_int( properties, "channels" );
620 int frequency = mlt_properties_get_int( properties, "frequency" );
621 int16_t *pcm = NULL;
622 int samples = 0;
623
624 // AVFormat audio buffer and frame size
625 int audio_outbuf_size = 10000;
626 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
627 int audio_input_frame_size = 0;
628
629 // AVFormat video buffer and frame count
630 int frame_count = 0;
631 int video_outbuf_size = ( 1024 * 1024 );
632 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
633
634 // Used for the frame properties
635 mlt_frame frame = NULL;
636 mlt_properties frame_properties = NULL;
637
638 // Get the queues
639 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
640 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
641
642 // Need two av pictures for converting
643 AVFrame *output = NULL;
644 AVFrame *input = alloc_picture( PIX_FMT_YUV422, width, height );
645
646 // For receiving images from an mlt_frame
647 uint8_t *image;
648 mlt_image_format img_fmt = mlt_image_yuv422;
649
650 // For receiving audio samples back from the fifo
651 int16_t *buffer = av_malloc( 48000 * 2 );
652 int count = 0;
653
654 // Allocate the context
655 AVFormatContext *oc = av_alloc_format_context( );
656
657 // Streams
658 AVStream *audio_st = NULL;
659 AVStream *video_st = NULL;
660
661 // Time stamps
662 double audio_pts = 0;
663 double video_pts = 0;
664
665 // Loop variable
666 int i;
667
668 // Frames despatched
669 long int frames = 0;
670 long int total_time = 0;
671
672 // Determine the format
673 AVOutputFormat *fmt = NULL;
674 char *filename = mlt_properties_get( properties, "target" );
675 char *format = mlt_properties_get( properties, "format" );
676 char *vcodec = mlt_properties_get( properties, "vcodec" );
677 char *acodec = mlt_properties_get( properties, "acodec" );
678
679 // Used to store and override codec ids
680 int audio_codec_id;
681 int video_codec_id;
682
683 // Check for user selected format first
684 if ( format != NULL )
685 fmt = guess_format( format, NULL, NULL );
686
687 // Otherwise check on the filename
688 if ( fmt == NULL && filename != NULL )
689 fmt = guess_format( NULL, filename, NULL );
690
691 // Otherwise default to mpeg
692 if ( fmt == NULL )
693 fmt = guess_format( "mpeg", NULL, NULL );
694
695 // We need a filename - default to stdout?
696 if ( filename == NULL || !strcmp( filename, "" ) )
697 filename = "pipe:";
698
699 // Get the codec ids selected
700 audio_codec_id = fmt->audio_codec;
701 video_codec_id = fmt->video_codec;
702
703 // Check for audio codec overides
704 if ( acodec != NULL )
705 {
706 AVCodec *p = first_avcodec;
707 while( p != NULL )
708 {
709 if ( !strcmp( p->name, acodec ) && p->type == CODEC_TYPE_AUDIO )
710 break;
711 p = p->next;
712 }
713 if ( p != NULL )
714 audio_codec_id = p->id;
715 else
716 fprintf( stderr, "consumer_avcodec: audio codec %s unrecognised - ignoring\n", acodec );
717 }
718
719 // Check for video codec overides
720 if ( vcodec != NULL )
721 {
722 AVCodec *p = first_avcodec;
723 while( p != NULL )
724 {
725 if ( !strcmp( p->name, vcodec ) && p->type == CODEC_TYPE_VIDEO )
726 break;
727 p = p->next;
728 }
729 if ( p != NULL )
730 video_codec_id = p->id;
731 else
732 fprintf( stderr, "consumer_avcodec: video codec %s unrecognised - ignoring\n", vcodec );
733 }
734
735 // Update the output context
736 oc->oformat = fmt;
737 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
738
739 // Add audio and video streams
740 if ( fmt->video_codec != CODEC_ID_NONE )
741 video_st = add_video_stream( this, oc, video_codec_id );
742 if ( fmt->audio_codec != CODEC_ID_NONE )
743 audio_st = add_audio_stream( this, oc, audio_codec_id );
744
745 // Set the parameters (even though we have none...)
746 if ( av_set_parameters(oc, NULL) >= 0 )
747 {
748 if ( video_st && !open_video( oc, video_st ) )
749 video_st = NULL;
750 if ( audio_st )
751 audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
752
753 // Open the output file, if needed
754 if ( !( fmt->flags & AVFMT_NOFILE ) )
755 {
756 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0)
757 {
758 fprintf(stderr, "Could not open '%s'\n", filename);
759 mlt_properties_set_int( properties, "running", 0 );
760 }
761 }
762
763 // Write the stream header, if any
764 if ( mlt_properties_get_int( properties, "running" ) )
765 av_write_header( oc );
766 }
767 else
768 {
769 fprintf(stderr, "Invalid output format parameters\n");
770 mlt_properties_set_int( properties, "running", 0 );
771 }
772
773 // Allocate picture
774 if ( video_st )
775 output = alloc_picture( video_st->codec->pix_fmt, width, height );
776
777 // Last check - need at least one stream
778 if ( audio_st == NULL && video_st == NULL )
779 mlt_properties_set_int( properties, "running", 0 );
780
781 // Get the starting time (can ignore the times above)
782 gettimeofday( &ante, NULL );
783
784 // Loop while running
785 while( mlt_properties_get_int( properties, "running" ) && !terminated )
786 {
787 // Get the frame
788 frame = mlt_consumer_rt_frame( this );
789
790 // Check that we have a frame to work with
791 if ( frame != NULL )
792 {
793 // Increment frames despatched
794 frames ++;
795
796 // Default audio args
797 frame_properties = MLT_FRAME_PROPERTIES( frame );
798
799 // Check for the terminated condition
800 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
801
802 // Get audio and append to the fifo
803 if ( !terminated && audio_st )
804 {
805 samples = mlt_sample_calculator( fps, frequency, count );
806 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
807
808 // Create the fifo if we don't have one
809 if ( fifo == NULL )
810 {
811 fifo = sample_fifo_init( frequency, channels );
812 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
813 }
814
815 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
816 memset( pcm, 0, samples * channels * 2 );
817
818 // Append the samples
819 sample_fifo_append( fifo, pcm, samples * channels );
820 total_time += ( samples * 1000000 ) / frequency;
821 }
822
823 // Encode the image
824 if ( !terminated && video_st )
825 mlt_deque_push_back( queue, frame );
826 else
827 mlt_frame_close( frame );
828 }
829
830 // While we have stuff to process, process...
831 while ( 1 )
832 {
833 if (audio_st)
834 audio_pts = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;
835 else
836 audio_pts = 0.0;
837
838 if (video_st)
839 video_pts = (double)video_st->pts.val * video_st->time_base.num / video_st->time_base.den;
840 else
841 video_pts = 0.0;
842
843 // Write interleaved audio and video frames
844 if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
845 {
846 if ( channels * audio_input_frame_size < sample_fifo_used( fifo ) )
847 {
848 AVCodecContext *c;
849 AVPacket pkt;
850 av_init_packet( &pkt );
851
852 c = audio_st->codec;
853
854 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
855
856 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
857 // Write the compressed frame in the media file
858 if ( c->coded_frame )
859 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
860 pkt.flags |= PKT_FLAG_KEY;
861 pkt.stream_index= audio_st->index;
862 pkt.data= audio_outbuf;
863
864 if ( av_interleaved_write_frame( oc, &pkt ) != 0)
865 fprintf(stderr, "Error while writing audio frame\n");
866
867 audio_pts += c->frame_size;
868 }
869 else
870 {
871 break;
872 }
873 }
874 else if ( video_st )
875 {
876 if ( mlt_deque_count( queue ) )
877 {
878 int out_size, ret;
879 AVCodecContext *c;
880
881 frame = mlt_deque_pop_front( queue );
882 frame_properties = MLT_FRAME_PROPERTIES( frame );
883
884 c = video_st->codec;
885
886 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
887 {
888 int i = 0;
889 int j = 0;
890 uint8_t *p;
891 uint8_t *q;
892
893 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
894
895 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
896
897 q = image;
898
899 // Convert the mlt frame to an AVPicture
900 for ( i = 0; i < height; i ++ )
901 {
902 p = input->data[ 0 ] + i * input->linesize[ 0 ];
903 j = width;
904 while( j -- )
905 {
906 *p ++ = *q ++;
907 *p ++ = *q ++;
908 }
909 }
910
911 // Do the colour space conversion
912 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUV422, width, height );
913
914 // Apply the alpha if applicable
915 if ( video_st->codec->pix_fmt == PIX_FMT_RGBA32 )
916 {
917 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
918 register int n;
919
920 for ( i = 0; i < height; i ++ )
921 {
922 n = ( width + 7 ) / 8;
923 p = output->data[ 0 ] + i * output->linesize[ 0 ];
924
925 #ifndef __DARWIN__
926 p += 3;
927 #endif
928
929 switch( width % 8 )
930 {
931 case 0: do { *p = *alpha++; p += 4;
932 case 7: *p = *alpha++; p += 4;
933 case 6: *p = *alpha++; p += 4;
934 case 5: *p = *alpha++; p += 4;
935 case 4: *p = *alpha++; p += 4;
936 case 3: *p = *alpha++; p += 4;
937 case 2: *p = *alpha++; p += 4;
938 case 1: *p = *alpha++; p += 4;
939 }
940 while( --n );
941 }
942 }
943 }
944 }
945
946 if (oc->oformat->flags & AVFMT_RAWPICTURE)
947 {
948 // raw video case. The API will change slightly in the near future for that
949 AVPacket pkt;
950 av_init_packet(&pkt);
951
952 pkt.flags |= PKT_FLAG_KEY;
953 pkt.stream_index= video_st->index;
954 pkt.data= (uint8_t *)output;
955 pkt.size= sizeof(AVPicture);
956
957 ret = av_write_frame(oc, &pkt);
958 video_pts += c->frame_size;
959 }
960 else
961 {
962 // Set the quality
963 output->quality = video_st->quality;
964
965 // Encode the image
966 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
967
968 // If zero size, it means the image was buffered
969 if (out_size != 0)
970 {
971 AVPacket pkt;
972 av_init_packet( &pkt );
973
974 if ( c->coded_frame )
975 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
976 if( c->coded_frame && c->coded_frame->key_frame )
977 pkt.flags |= PKT_FLAG_KEY;
978 pkt.stream_index= video_st->index;
979 pkt.data= video_outbuf;
980 pkt.size= out_size;
981
982 // write the compressed frame in the media file
983 ret = av_interleaved_write_frame(oc, &pkt);
984 video_pts += c->frame_size;
985 }
986 }
987 frame_count++;
988 mlt_frame_close( frame );
989 }
990 else
991 {
992 break;
993 }
994 }
995 }
996
997 if ( real_time_output && frames % 12 == 0 )
998 {
999 long passed = time_difference( &ante );
1000 if ( fifo != NULL )
1001 {
1002 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1003 passed -= pending;
1004 }
1005 if ( passed < total_time )
1006 {
1007 long total = ( total_time - passed );
1008 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1009 nanosleep( &t, NULL );
1010 }
1011 }
1012 }
1013
1014 // close each codec
1015 if (video_st)
1016 close_video(oc, video_st);
1017 if (audio_st)
1018 close_audio(oc, audio_st);
1019
1020 // Write the trailer, if any
1021 av_write_trailer(oc);
1022
1023 // Free the streams
1024 for(i = 0; i < oc->nb_streams; i++)
1025 av_freep(&oc->streams[i]);
1026
1027 // Close the output file
1028 if (!(fmt->flags & AVFMT_NOFILE))
1029 url_fclose(&oc->pb);
1030
1031 // Clean up input and output frames
1032 if ( output )
1033 av_free( output->data[0] );
1034 av_free( output );
1035 av_free( input->data[0] );
1036 av_free( input );
1037 av_free( video_outbuf );
1038 av_free( buffer );
1039
1040 // Free the stream
1041 av_free(oc);
1042
1043 // Just in case we terminated on pause
1044 mlt_properties_set_int( properties, "running", 0 );
1045
1046 mlt_consumer_stopped( this );
1047
1048 return NULL;
1049 }
1050
1051 /** Close the consumer.
1052 */
1053
1054 static void consumer_close( mlt_consumer this )
1055 {
1056 // Stop the consumer
1057 mlt_consumer_stop( this );
1058
1059 // Close the parent
1060 mlt_consumer_close( this );
1061
1062 // Free the memory
1063 free( this );
1064 }