]> git.sesse.net Git - mlt/blob - src/modules/avformat/consumer_avformat.c
Fix crash in x264 on second pass of multi-threaded encoding.
[mlt] / 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  * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 // mlt Header files
23 #include <framework/mlt_consumer.h>
24 #include <framework/mlt_frame.h>
25 #include <framework/mlt_profile.h>
26 #include <framework/mlt_log.h>
27
28 // System header files
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <limits.h>
33 #include <pthread.h>
34 #include <sys/time.h>
35 #include <unistd.h>
36
37 // avformat header files
38 #include <avformat.h>
39 #ifdef SWSCALE
40 #include <swscale.h>
41 #endif
42 #include <opt.h>
43
44 #if LIBAVUTIL_VERSION_INT < (50<<16)
45 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
46 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
47 #endif
48
49 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2)
50
51 //
52 // This structure should be extended and made globally available in mlt
53 //
54
55 typedef struct
56 {
57         int16_t *buffer;
58         int size;
59         int used;
60         double time;
61         int frequency;
62         int channels;
63 }
64 *sample_fifo, sample_fifo_s;
65
66 sample_fifo sample_fifo_init( int frequency, int channels )
67 {
68         sample_fifo this = calloc( 1, sizeof( sample_fifo_s ) );
69         this->frequency = frequency;
70         this->channels = channels;
71         return this;
72 }
73
74 // sample_fifo_clear and check are temporarily aborted (not working as intended)
75
76 void sample_fifo_clear( sample_fifo this, double time )
77 {
78         int words = ( float )( time - this->time ) * this->frequency * this->channels;
79         if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) && this->used > words && words > 0 )
80         {
81                 memmove( this->buffer, &this->buffer[ words ], ( this->used - words ) * sizeof( int16_t ) );
82                 this->used -= words;
83                 this->time = time;
84         }
85         else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )this->time * 100 ) )
86         {
87                 this->used = 0;
88                 this->time = time;
89         }
90 }
91
92 void sample_fifo_check( sample_fifo this, double time )
93 {
94         if ( this->used == 0 )
95         {
96                 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) )
97                         this->time = time;
98         }
99 }
100
101 void sample_fifo_append( sample_fifo this, int16_t *samples, int count )
102 {
103         if ( ( this->size - this->used ) < count )
104         {
105                 this->size += count * 5;
106                 this->buffer = realloc( this->buffer, this->size * sizeof( int16_t ) );
107         }
108
109         memcpy( &this->buffer[ this->used ], samples, count * sizeof( int16_t ) );
110         this->used += count;
111 }
112
113 int sample_fifo_used( sample_fifo this )
114 {
115         return this->used;
116 }
117
118 int sample_fifo_fetch( sample_fifo this, int16_t *samples, int count )
119 {
120         if ( count > this->used )
121                 count = this->used;
122
123         memcpy( samples, this->buffer, count * sizeof( int16_t ) );
124         this->used -= count;
125         memmove( this->buffer, &this->buffer[ count ], this->used * sizeof( int16_t ) );
126
127         this->time += ( double )count / this->channels / this->frequency;
128
129         return count;
130 }
131
132 void sample_fifo_close( sample_fifo this )
133 {
134         free( this->buffer );
135         free( this );
136 }
137
138 // Forward references.
139 static int consumer_start( mlt_consumer this );
140 static int consumer_stop( mlt_consumer this );
141 static int consumer_is_stopped( mlt_consumer this );
142 static void *consumer_thread( void *arg );
143 static void consumer_close( mlt_consumer this );
144
145 /** Initialise the dv consumer.
146 */
147
148 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
149 {
150         // Allocate the consumer
151         mlt_consumer this = mlt_consumer_new( profile );
152
153         // If memory allocated and initialises without error
154         if ( this != NULL )
155         {
156                 // Get properties from the consumer
157                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
158
159                 // Assign close callback
160                 this->close = consumer_close;
161
162                 // Interpret the argument
163                 if ( arg != NULL )
164                         mlt_properties_set( properties, "target", arg );
165
166                 // sample and frame queue
167                 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
168
169                 // Audio options not fully handled by AVOptions
170 #define QSCALE_NONE (-99999)
171                 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
172                 
173                 // Video options not fully handled by AVOptions
174                 mlt_properties_set_int( properties, "dc", 8 );
175                 
176                 // Muxer options not fully handled by AVOptions
177                 mlt_properties_set_double( properties, "muxdelay", 0.7 );
178                 mlt_properties_set_double( properties, "muxpreload", 0.5 );
179
180                 // Ensure termination at end of the stream
181                 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
182                 
183                 // Default to separate processing threads for producer and consumer with no frame dropping!
184                 mlt_properties_set_int( properties, "real_time", -1 );
185                 mlt_properties_set_int( properties, "prefill", 1 );
186
187                 // Set up start/stop/terminated callbacks
188                 this->start = consumer_start;
189                 this->stop = consumer_stop;
190                 this->is_stopped = consumer_is_stopped;
191         }
192
193         // Return this
194         return this;
195 }
196
197 /** Start the consumer.
198 */
199
200 static int consumer_start( mlt_consumer this )
201 {
202         // Get the properties
203         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
204         int error = 0;
205
206         // Report information about available muxers and codecs as YAML Tiny
207         char *s = mlt_properties_get( properties, "f" );
208         if ( s && strcmp( s, "list" ) == 0 )
209         {
210                 fprintf( stderr, "---\nformats:\n" );
211                 AVOutputFormat *format = NULL;
212                 while ( ( format = av_oformat_next( format ) ) )
213                         fprintf( stderr, "  - %s\n", format->name );
214                 fprintf( stderr, "...\n" );
215                 error = 1;
216         }
217         s = mlt_properties_get( properties, "acodec" );
218         if ( s && strcmp( s, "list" ) == 0 )
219         {
220                 fprintf( stderr, "---\naudio_codecs:\n" );
221                 AVCodec *codec = NULL;
222                 while ( ( codec = av_codec_next( codec ) ) )
223                         if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
224                                 fprintf( stderr, "  - %s\n", codec->name );
225                 fprintf( stderr, "...\n" );
226                 error = 1;
227         }
228         s = mlt_properties_get( properties, "vcodec" );
229         if ( s && strcmp( s, "list" ) == 0 )
230         {
231                 fprintf( stderr, "---\nvideo_codecs:\n" );
232                 AVCodec *codec = NULL;
233                 while ( ( codec = av_codec_next( codec ) ) )
234                         if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
235                                 fprintf( stderr, "  - %s\n", codec->name );
236                 fprintf( stderr, "...\n" );
237                 error = 1;
238         }
239
240         // Check that we're not already running
241         if ( !error && !mlt_properties_get_int( properties, "running" ) )
242         {
243                 // Allocate a thread
244                 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
245
246                 // Get the width and height
247                 int width = mlt_properties_get_int( properties, "width" );
248                 int height = mlt_properties_get_int( properties, "height" );
249
250                 // Obtain the size property
251                 char *size = mlt_properties_get( properties, "s" );
252
253                 // Interpret it
254                 if ( size != NULL )
255                 {
256                         int tw, th;
257                         if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
258                         {
259                                 width = tw;
260                                 height = th;
261                         }
262                         else
263                         {
264                                 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "Invalid size property %s - ignoring.\n", size );
265                         }
266                 }
267                 
268                 // Now ensure we honour the multiple of two requested by libavformat
269                 width = ( width / 2 ) * 2;
270                 height = ( height / 2 ) * 2;
271                 mlt_properties_set_int( properties, "width", width );
272                 mlt_properties_set_int( properties, "height", height );
273
274                 // We need to set these on the profile as well because the s property is
275                 // an alias to mlt properties that correspond to profile settings.
276                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
277                 if ( profile )
278                 {
279                         profile->width = width;
280                         profile->height = height;
281                 }
282
283                 // Handle the ffmpeg command line "-r" property for frame rate
284                 if ( mlt_properties_get( properties, "r" ) )
285                 {
286                         double frame_rate = mlt_properties_get_double( properties, "r" );
287                         AVRational rational = av_d2q( frame_rate, 255 );
288                         mlt_properties_set_int( properties, "frame_rate_num", rational.num );
289                         mlt_properties_set_int( properties, "frame_rate_den", rational.den );
290                         if ( profile )
291                         {
292                                 profile->frame_rate_num = rational.num;
293                                 profile->frame_rate_den = rational.den;
294                                 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
295                         }
296                 }
297                 
298                 // Apply AVOptions that are synonyms for standard mlt_consumer options
299                 if ( mlt_properties_get( properties, "ac" ) )
300                         mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
301                 if ( mlt_properties_get( properties, "ar" ) )
302                         mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
303
304                 // Assign the thread to properties
305                 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
306
307                 // Set the running state
308                 mlt_properties_set_int( properties, "running", 1 );
309
310                 // Create the thread
311                 pthread_create( thread, NULL, consumer_thread, this );
312         }
313         return error;
314 }
315
316 /** Stop the consumer.
317 */
318
319 static int consumer_stop( mlt_consumer this )
320 {
321         // Get the properties
322         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
323
324         // Check that we're running
325         if ( mlt_properties_get_int( properties, "running" ) )
326         {
327                 // Get the thread
328                 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
329
330                 // Stop the thread
331                 mlt_properties_set_int( properties, "running", 0 );
332
333                 // Wait for termination
334                 pthread_join( *thread, NULL );
335         }
336
337         return 0;
338 }
339
340 /** Determine if the consumer is stopped.
341 */
342
343 static int consumer_is_stopped( mlt_consumer this )
344 {
345         // Get the properties
346         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
347         return !mlt_properties_get_int( properties, "running" );
348 }
349
350 /** Process properties as AVOptions and apply to AV context obj
351 */
352
353 static void apply_properties( void *obj, mlt_properties properties, int flags )
354 {
355         int i;
356         int count = mlt_properties_count( properties ); 
357         for ( i = 0; i < count; i++ )
358         {
359                 const char *opt_name = mlt_properties_get_name( properties, i );
360                 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
361                 if ( opt != NULL )
362 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
363                         av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
364 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
365                         av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
366 #else
367                         av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
368 #endif
369         }
370 }
371
372 /** Add an audio output stream
373 */
374
375 static AVStream *add_audio_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
376 {
377         // Get the properties
378         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
379
380         // Create a new stream
381         AVStream *st = av_new_stream( oc, 1 );
382
383         // If created, then initialise from properties
384         if ( st != NULL ) 
385         {
386                 AVCodecContext *c = st->codec;
387
388                 // Establish defaults from AVOptions
389                 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
390
391                 c->codec_id = codec_id;
392                 c->codec_type = CODEC_TYPE_AUDIO;
393                 c->sample_fmt = SAMPLE_FMT_S16;
394
395 #if 0 // disabled until some audio codecs are multi-threaded
396                 // Setup multi-threading
397                 int thread_count = mlt_properties_get_int( properties, "threads" );
398                 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
399                         thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
400                 if ( thread_count > 1 )
401                         avcodec_thread_init( c, thread_count );         
402 #endif
403         
404                 if (oc->oformat->flags & AVFMT_GLOBALHEADER) 
405                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
406                 
407                 // Allow the user to override the audio fourcc
408                 if ( mlt_properties_get( properties, "atag" ) )
409                 {
410                         char *tail = NULL;
411                         char *arg = mlt_properties_get( properties, "atag" );
412                         int tag = strtol( arg, &tail, 0);
413                         if( !tail || *tail )
414                                 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
415                         c->codec_tag = tag;
416                 }
417
418                 // Process properties as AVOptions
419                 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
420
421                 int audio_qscale = mlt_properties_get_int( properties, "aq" );
422         if ( audio_qscale > QSCALE_NONE )
423                 {
424                         c->flags |= CODEC_FLAG_QSCALE;
425                         c->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
426                 }
427
428                 // Set parameters controlled by MLT
429                 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
430                 c->time_base = ( AVRational ){ 1, c->sample_rate };
431                 c->channels = mlt_properties_get_int( properties, "channels" );
432
433                 if ( mlt_properties_get( properties, "alang" ) != NULL )
434                         strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
435         }
436         else
437         {
438                 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not allocate a stream for audio\n" );
439         }
440
441         return st;
442 }
443
444 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
445 {
446         // We will return the audio input size from here
447         int audio_input_frame_size = 0;
448
449         // Get the context
450         AVCodecContext *c = st->codec;
451
452         // Find the encoder
453         AVCodec *codec = avcodec_find_encoder( c->codec_id );
454
455         // Continue if codec found and we can open it
456         if ( codec != NULL && avcodec_open( c, codec ) >= 0 )
457         {
458                 // ugly hack for PCM codecs (will be removed ASAP with new PCM
459                 // support to compute the input frame size in samples
460                 if ( c->frame_size <= 1 ) 
461                 {
462                         audio_input_frame_size = audio_outbuf_size / c->channels;
463                         switch(st->codec->codec_id) 
464                         {
465                                 case CODEC_ID_PCM_S16LE:
466                                 case CODEC_ID_PCM_S16BE:
467                                 case CODEC_ID_PCM_U16LE:
468                                 case CODEC_ID_PCM_U16BE:
469                                         audio_input_frame_size >>= 1;
470                                         break;
471                                 default:
472                                         break;
473                         }
474                 } 
475                 else 
476                 {
477                         audio_input_frame_size = c->frame_size;
478                 }
479
480                 // Some formats want stream headers to be seperate (hmm)
481                 if ( !strcmp( oc->oformat->name, "mp4" ) ||
482                          !strcmp( oc->oformat->name, "mov" ) ||
483                          !strcmp( oc->oformat->name, "3gp" ) )
484                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
485         }
486         else
487         {
488                 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
489         }
490
491         return audio_input_frame_size;
492 }
493
494 static void close_audio( AVFormatContext *oc, AVStream *st )
495 {
496         if ( st && st->codec )
497                 avcodec_close( st->codec );
498 }
499
500 /** Add a video output stream 
501 */
502
503 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
504 {
505         // Get the properties
506         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
507
508         // Create a new stream
509         AVStream *st = av_new_stream( oc, 0 );
510
511         if ( st != NULL ) 
512         {
513                 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
514                 AVCodecContext *c = st->codec;
515
516                 // Establish defaults from AVOptions
517                 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
518
519                 c->codec_id = codec_id;
520                 c->codec_type = CODEC_TYPE_VIDEO;
521                 
522                 // Setup multi-threading
523                 int thread_count = mlt_properties_get_int( properties, "threads" );
524                 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
525                         thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
526                 if ( thread_count > 1 )
527                         avcodec_thread_init( c, thread_count );         
528         
529                 // Process properties as AVOptions
530                 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
531
532                 // Set options controlled by MLT
533                 c->width = mlt_properties_get_int( properties, "width" );
534                 c->height = mlt_properties_get_int( properties, "height" );
535                 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
536                 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
537                 if ( st->time_base.den == 0 )
538                         st->time_base = c->time_base;
539                 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
540
541                 if ( mlt_properties_get( properties, "aspect" ) )
542                 {
543                         // "-aspect" on ffmpeg command line is display aspect ratio
544                         double ar = mlt_properties_get_double( properties, "aspect" );
545                         AVRational rational = av_d2q( ar, 255 );
546
547                         // Update the profile and properties as well since this is an alias 
548                         // for mlt properties that correspond to profile settings
549                         mlt_properties_set_int( properties, "display_aspect_num", rational.num );
550                         mlt_properties_set_int( properties, "display_aspect_den", rational.den );
551                         mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
552                         if ( profile )
553                         {
554                                 profile->display_aspect_num = rational.num;
555                                 profile->display_aspect_den = rational.den;
556                                 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
557                         }
558
559                         // Now compute the sample aspect ratio
560                         rational = av_d2q( ar * c->height / c->width, 255 );
561                         c->sample_aspect_ratio = rational;
562                         // Update the profile and properties as well since this is an alias 
563                         // for mlt properties that correspond to profile settings
564                         mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
565                         mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
566                         if ( profile )
567                         {
568                                 profile->sample_aspect_num = rational.num;
569                                 profile->sample_aspect_den = rational.den;
570                                 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
571                         }
572                 }
573                 else
574                 {
575                         c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
576                         c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
577                 }
578 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
579                 st->sample_aspect_ratio = c->sample_aspect_ratio;
580 #endif
581
582                 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
583                 {
584                         c->flags |= CODEC_FLAG_QSCALE;
585                         st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
586                 }
587
588                 // Allow the user to override the video fourcc
589                 if ( mlt_properties_get( properties, "vtag" ) )
590                 {
591                         char *tail = NULL;
592                         const char *arg = mlt_properties_get( properties, "vtag" );
593                         int tag = strtol( arg, &tail, 0);
594                         if( !tail || *tail )
595                                 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
596                         c->codec_tag = tag;
597                 }
598
599                 // Some formats want stream headers to be seperate
600                 if ( oc->oformat->flags & AVFMT_GLOBALHEADER ) 
601                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
602
603                 // Translate these standard mlt consumer properties to ffmpeg
604                 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
605                      mlt_properties_get_int( properties, "deinterlace" ) == 0 )
606                 {
607                         if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
608                                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
609                         if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
610                                 c->flags |= CODEC_FLAG_INTERLACED_ME;
611                 }
612                 
613                 // parse the ratecontrol override string
614                 int i;
615                 char *rc_override = mlt_properties_get( properties, "rc_override" );
616                 for ( i = 0; rc_override; i++ )
617                 {
618                         int start, end, q;
619                         int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
620                         if ( e != 3 )
621                                 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "Error parsing rc_override\n" );
622                         c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
623                         c->rc_override[i].start_frame = start;
624                         c->rc_override[i].end_frame = end;
625                         if ( q > 0 )
626                         {
627                                 c->rc_override[i].qscale = q;
628                                 c->rc_override[i].quality_factor = 1.0;
629                         }
630                         else
631                         {
632                                 c->rc_override[i].qscale = 0;
633                                 c->rc_override[i].quality_factor = -q / 100.0;
634                         }
635                         rc_override = strchr( rc_override, '/' );
636                         if ( rc_override )
637                                 rc_override++;
638                 }
639                 c->rc_override_count = i;
640                 if ( !c->rc_initial_buffer_occupancy )
641                         c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
642                 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
643
644                 // Setup dual-pass
645                 i = mlt_properties_get_int( properties, "pass" );
646                 if ( i == 1 )
647                         c->flags |= CODEC_FLAG_PASS1;
648                 else if ( i == 2 )
649                         c->flags |= CODEC_FLAG_PASS2;
650                 if ( codec_id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
651                 {
652                         char logfilename[1024];
653                         FILE *f;
654                         int size;
655                         char *logbuffer;
656
657                         snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
658                                 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
659                         if ( c->flags & CODEC_FLAG_PASS1 )
660                         {
661                                 f = fopen( logfilename, "w" );
662                                 if ( !f )
663                                         perror( logfilename );
664                                 else
665                                         mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
666                         }
667                         else
668                         {
669                                 /* read the log file */
670                                 f = fopen( logfilename, "r" );
671                                 if ( !f )
672                                 {
673                                         perror(logfilename);
674                                 }
675                                 else
676                                 {
677                                         mlt_properties_set( properties, "_logfilename", logfilename );
678                                         fseek( f, 0, SEEK_END );
679                                         size = ftell( f );
680                                         fseek( f, 0, SEEK_SET );
681                                         logbuffer = av_malloc( size + 1 );
682                                         if ( !logbuffer )
683                                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( this ), "Could not allocate log buffer\n" );
684                                         else
685                                         {
686                                                 size = fread( logbuffer, 1, size, f );
687                                                 fclose( f );
688                                                 logbuffer[size] = '\0';
689                                                 c->stats_in = logbuffer;
690                                                 mlt_properties_set_data( properties, "_logbuffer", logbuffer, 0, ( mlt_destructor )av_free, NULL );
691                                         }
692                                 }
693                         }
694                 }
695         }
696         else
697         {
698                 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not allocate a stream for video\n" );
699         }
700  
701         return st;
702 }
703
704 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
705 {
706         // Allocate a frame
707         AVFrame *picture = avcodec_alloc_frame();
708
709         // Determine size of the 
710         int size = avpicture_get_size(pix_fmt, width, height);
711
712         // Allocate the picture buf
713         uint8_t *picture_buf = av_malloc(size);
714
715         // If we have both, then fill the image
716         if ( picture != NULL && picture_buf != NULL )
717         {
718                 // Fill the frame with the allocated buffer
719                 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
720         }
721         else
722         {
723                 // Something failed - clean up what we can
724                 av_free( picture );
725                 av_free( picture_buf );
726                 picture = NULL;
727         }
728
729         return picture;
730 }
731         
732 static int open_video(AVFormatContext *oc, AVStream *st)
733 {
734         // Get the codec
735         AVCodecContext *video_enc = st->codec;
736
737         // find the video encoder
738         AVCodec *codec = avcodec_find_encoder( video_enc->codec_id );
739
740         if( codec && codec->pix_fmts )
741         {
742                 const enum PixelFormat *p = codec->pix_fmts;
743                 for( ; *p!=-1; p++ )
744                 {
745                         if( *p == video_enc->pix_fmt )
746                                 break;
747                 }
748                 if( *p == -1 )
749                         video_enc->pix_fmt = codec->pix_fmts[ 0 ];
750         }
751
752         // Open the codec safely
753         return codec != NULL && avcodec_open( video_enc, codec ) >= 0;
754 }
755
756 void close_video(AVFormatContext *oc, AVStream *st)
757 {
758         if ( st && st->codec )
759                 avcodec_close(st->codec);
760 }
761
762 static inline long time_difference( struct timeval *time1 )
763 {
764         struct timeval time2;
765         gettimeofday( &time2, NULL );
766         return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
767 }
768
769 /** The main thread - the argument is simply the consumer.
770 */
771
772 static void *consumer_thread( void *arg )
773 {
774         // Map the argument to the object
775         mlt_consumer this = arg;
776
777         // Get the properties
778         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
779
780         // Get the terminate on pause property
781         int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
782         int terminated = 0;
783
784         // Determine if feed is slow (for realtime stuff)
785         int real_time_output = mlt_properties_get_int( properties, "real_time" );
786
787         // Time structures
788         struct timeval ante;
789
790         // Get the frame rate
791         double fps = mlt_properties_get_double( properties, "fps" );
792
793         // Get width and height
794         int width = mlt_properties_get_int( properties, "width" );
795         int height = mlt_properties_get_int( properties, "height" );
796         int img_width = width;
797         int img_height = height;
798
799         // Get default audio properties
800         mlt_audio_format aud_fmt = mlt_audio_s16;
801         int channels = mlt_properties_get_int( properties, "channels" );
802         int frequency = mlt_properties_get_int( properties, "frequency" );
803         int16_t *pcm = NULL;
804         int samples = 0;
805
806         // AVFormat audio buffer and frame size
807         int audio_outbuf_size = ( 1024 * 42 );
808         uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
809         int audio_input_frame_size = 0;
810
811         // AVFormat video buffer and frame count
812         int frame_count = 0;
813         int video_outbuf_size = ( 1024 * 1024 );
814         uint8_t *video_outbuf = av_malloc( video_outbuf_size );
815
816         // Used for the frame properties
817         mlt_frame frame = NULL;
818         mlt_properties frame_properties = NULL;
819
820         // Get the queues
821         mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
822         sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
823
824         // Need two av pictures for converting
825         AVFrame *output = NULL;
826         AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
827
828         // For receiving images from an mlt_frame
829         uint8_t *image;
830         mlt_image_format img_fmt = mlt_image_yuv422;
831
832         // For receiving audio samples back from the fifo
833         int16_t *buffer = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
834         int count = 0;
835
836         // Allocate the context
837 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
838         AVFormatContext *oc = avformat_alloc_context( );
839 #else
840         AVFormatContext *oc = av_alloc_format_context( );
841 #endif
842
843         // Streams
844         AVStream *audio_st = NULL;
845         AVStream *video_st = NULL;
846
847         // Time stamps
848         double audio_pts = 0;
849         double video_pts = 0;
850
851         // Loop variable
852         int i;
853
854         // Frames despatched
855         long int frames = 0;
856         long int total_time = 0;
857
858         // Determine the format
859         AVOutputFormat *fmt = NULL;
860         const char *filename = mlt_properties_get( properties, "target" );
861         char *format = mlt_properties_get( properties, "f" );
862         char *vcodec = mlt_properties_get( properties, "vcodec" );
863         char *acodec = mlt_properties_get( properties, "acodec" );
864         
865         // Used to store and override codec ids
866         int audio_codec_id;
867         int video_codec_id;
868
869         // Check for user selected format first
870         if ( format != NULL )
871                 fmt = guess_format( format, NULL, NULL );
872
873         // Otherwise check on the filename
874         if ( fmt == NULL && filename != NULL )
875                 fmt = guess_format( NULL, filename, NULL );
876
877         // Otherwise default to mpeg
878         if ( fmt == NULL )
879                 fmt = guess_format( "mpeg", NULL, NULL );
880
881         // We need a filename - default to stdout?
882         if ( filename == NULL || !strcmp( filename, "" ) )
883                 filename = "pipe:";
884
885         // Get the codec ids selected
886         audio_codec_id = fmt->audio_codec;
887         video_codec_id = fmt->video_codec;
888
889         // Check for audio codec overides
890         if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
891                 audio_codec_id = CODEC_ID_NONE;
892         else if ( acodec )
893         {
894                 AVCodec *p = avcodec_find_encoder_by_name( acodec );
895                 if ( p != NULL )
896                         audio_codec_id = p->id;
897                 else
898                         mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "audio codec %s unrecognised - ignoring\n", acodec );
899         }
900
901         // Check for video codec overides
902         if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
903                 video_codec_id = CODEC_ID_NONE;
904         else if ( vcodec )
905         {
906                 AVCodec *p = avcodec_find_encoder_by_name( vcodec );
907                 if ( p != NULL )
908                         video_codec_id = p->id;
909                 else
910                         mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "video codec %s unrecognised - ignoring\n", vcodec );
911         }
912
913         // Write metadata
914         char *tmp = NULL;
915         int metavalue;
916
917         tmp = mlt_properties_get( properties, "meta.attr.title.markup");
918         if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
919
920         tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
921         if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
922
923         tmp = mlt_properties_get( properties, "meta.attr.author.markup");
924         if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
925
926         tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
927         if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
928
929         tmp = mlt_properties_get( properties, "meta.attr.album.markup");
930         if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
931
932         metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
933         if (metavalue != 0) oc->year = metavalue;
934
935         metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
936         if (metavalue != 0) oc->track = metavalue;
937
938         oc->oformat = fmt;
939         snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
940
941         // Add audio and video streams 
942         if ( video_codec_id != CODEC_ID_NONE )
943                 video_st = add_video_stream( this, oc, video_codec_id );
944         if ( audio_codec_id != CODEC_ID_NONE )
945                 audio_st = add_audio_stream( this, oc, audio_codec_id );
946
947         // Set the parameters (even though we have none...)
948         if ( av_set_parameters(oc, NULL) >= 0 ) 
949         {
950                 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
951                 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
952
953                 // Process properties as AVOptions
954                 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
955
956                 if ( video_st && !open_video( oc, video_st ) )
957                         video_st = NULL;
958                 if ( audio_st )
959                 {
960                         audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
961                         if ( !audio_input_frame_size )
962                                 audio_st = NULL;
963                 }
964
965                 // Open the output file, if needed
966                 if ( !( fmt->flags & AVFMT_NOFILE ) ) 
967                 {
968                         if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 ) 
969                         {
970                                 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not open '%s'\n", filename );
971                                 mlt_properties_set_int( properties, "running", 0 );
972                         }
973                 }
974         
975                 // Write the stream header, if any
976                 if ( mlt_properties_get_int( properties, "running" ) )
977                         av_write_header( oc );
978         }
979         else
980         {
981                 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Invalid output format parameters\n" );
982                 mlt_properties_set_int( properties, "running", 0 );
983         }
984
985         // Allocate picture
986         if ( video_st )
987                 output = alloc_picture( video_st->codec->pix_fmt, width, height );
988
989         // Last check - need at least one stream
990         if ( audio_st == NULL && video_st == NULL )
991                 mlt_properties_set_int( properties, "running", 0 );
992
993         // Get the starting time (can ignore the times above)
994         gettimeofday( &ante, NULL );
995
996         // Loop while running
997         while( mlt_properties_get_int( properties, "running" ) &&
998                ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
999         {
1000                 // Get the frame
1001                 frame = mlt_consumer_rt_frame( this );
1002
1003                 // Check that we have a frame to work with
1004                 if ( frame != NULL )
1005                 {
1006                         // Increment frames despatched
1007                         frames ++;
1008
1009                         // Default audio args
1010                         frame_properties = MLT_FRAME_PROPERTIES( frame );
1011
1012                         // Check for the terminated condition
1013                         terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1014
1015                         // Get audio and append to the fifo
1016                         if ( !terminated && audio_st )
1017                         {
1018                                 samples = mlt_sample_calculator( fps, frequency, count ++ );
1019                                 mlt_frame_get_audio( frame, (void**) &pcm, &aud_fmt, &frequency, &channels, &samples );
1020
1021                                 // Create the fifo if we don't have one
1022                                 if ( fifo == NULL )
1023                                 {
1024                                         fifo = sample_fifo_init( frequency, channels );
1025                                         mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1026                                 }
1027
1028                                 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1029                                         memset( pcm, 0, samples * channels * 2 );
1030
1031                                 // Append the samples
1032                                 sample_fifo_append( fifo, pcm, samples * channels );
1033                                 total_time += ( samples * 1000000 ) / frequency;
1034                         }
1035
1036                         // Encode the image
1037                         if ( !terminated && video_st )
1038                                 mlt_deque_push_back( queue, frame );
1039                         else
1040                                 mlt_frame_close( frame );
1041                 }
1042
1043                 // While we have stuff to process, process...
1044                 while ( 1 )
1045                 {
1046                         // Write interleaved audio and video frames
1047                         if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
1048                         {
1049                                 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1050                                 {
1051                                         AVCodecContext *c = audio_st->codec;
1052                                         AVPacket pkt;
1053                                         int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) ), AUDIO_ENCODE_BUFFER_SIZE );
1054
1055                                         if ( n > 0 )
1056                                                 sample_fifo_fetch( fifo, buffer, n );
1057                                         else
1058                                                 memset( buffer, 0, AUDIO_ENCODE_BUFFER_SIZE );
1059                                         
1060                                         av_init_packet( &pkt );
1061                                         pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
1062                                         
1063                                         // Write the compressed frame in the media file
1064                                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1065                                         {
1066                                                 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
1067                                                 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "audio pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1068                                         }
1069                                         pkt.flags |= PKT_FLAG_KEY;
1070                                         pkt.stream_index= audio_st->index;
1071                                         pkt.data= audio_outbuf;
1072
1073                                         if ( pkt.size > 0 )
1074                                                 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1075                                                         mlt_log_error( MLT_CONSUMER_SERVICE( this ), "error writing audio frame\n" );
1076
1077                                         mlt_log_debug( MLT_CONSUMER_SERVICE( this ), " frame_size %d\n", c->frame_size );
1078                                         if ( audio_codec_id == CODEC_ID_VORBIS )
1079                                                 audio_pts = (double)c->coded_frame->pts * av_q2d( audio_st->time_base );
1080                                         else
1081                                                 audio_pts = (double)audio_st->pts.val * av_q2d( audio_st->time_base );
1082                                 }
1083                                 else
1084                                 {
1085                                         break;
1086                                 }
1087                         }
1088                         else if ( video_st )
1089                         {
1090                                 if ( mlt_deque_count( queue ) )
1091                                 {
1092                                         int out_size, ret;
1093                                         AVCodecContext *c;
1094
1095                                         frame = mlt_deque_pop_front( queue );
1096                                         frame_properties = MLT_FRAME_PROPERTIES( frame );
1097
1098                                         c = video_st->codec;
1099                                         
1100                                         if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1101                                         {
1102                                                 int i = 0;
1103                                                 int j = 0;
1104                                                 uint8_t *p;
1105                                                 uint8_t *q;
1106
1107                                                 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1108
1109                                                 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1110
1111                                                 q = image;
1112
1113                                                 // Convert the mlt frame to an AVPicture
1114                                                 for ( i = 0; i < height; i ++ )
1115                                                 {
1116                                                         p = input->data[ 0 ] + i * input->linesize[ 0 ];
1117                                                         j = width;
1118                                                         while( j -- )
1119                                                         {
1120                                                                 *p ++ = *q ++;
1121                                                                 *p ++ = *q ++;
1122                                                         }
1123                                                 }
1124
1125                                                 // Do the colour space conversion
1126 #ifdef SWSCALE
1127                                                 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1128                                                         width, height, video_st->codec->pix_fmt, SWS_FAST_BILINEAR, NULL, NULL, NULL);
1129                                                 sws_scale( context, input->data, input->linesize, 0, height,
1130                                                         output->data, output->linesize);
1131                                                 sws_freeContext( context );
1132 #else
1133                                                 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1134 #endif
1135
1136                                                 // Apply the alpha if applicable
1137                                                 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1138                                                 {
1139                                                         uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1140                                                         register int n;
1141
1142                                                         for ( i = 0; i < height; i ++ )
1143                                                         {
1144                                                                 n = ( width + 7 ) / 8;
1145                                                                 p = output->data[ 0 ] + i * output->linesize[ 0 ];
1146
1147                                                                 #ifndef __DARWIN__
1148                                                                 p += 3;
1149                                                                 #endif
1150
1151                                                                 switch( width % 8 )
1152                                                                 {
1153                                                                         case 0: do { *p = *alpha++; p += 4;
1154                                                                         case 7:          *p = *alpha++; p += 4;
1155                                                                         case 6:          *p = *alpha++; p += 4;
1156                                                                         case 5:          *p = *alpha++; p += 4;
1157                                                                         case 4:          *p = *alpha++; p += 4;
1158                                                                         case 3:          *p = *alpha++; p += 4;
1159                                                                         case 2:          *p = *alpha++; p += 4;
1160                                                                         case 1:          *p = *alpha++; p += 4;
1161                                                                                         }
1162                                                                                         while( --n );
1163                                                                 }
1164                                                         }
1165                                                 }
1166                                         }
1167
1168                                         if (oc->oformat->flags & AVFMT_RAWPICTURE) 
1169                                         {
1170                                                 // raw video case. The API will change slightly in the near future for that
1171                                                 AVPacket pkt;
1172                                                 av_init_packet(&pkt);
1173
1174                                                 pkt.flags |= PKT_FLAG_KEY;
1175                                                 pkt.stream_index= video_st->index;
1176                                                 pkt.data= (uint8_t *)output;
1177                                                 pkt.size= sizeof(AVPicture);
1178
1179                                                 ret = av_write_frame(oc, &pkt);
1180                                                 video_pts += c->frame_size;
1181                                         } 
1182                                         else 
1183                                         {
1184                                                 // Set the quality
1185                                                 output->quality = video_st->quality;
1186
1187                                                 // Set frame interlace hints
1188                                                 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1189                                                 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1190
1191                                                 // Encode the image
1192                                                 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1193
1194                                                 // If zero size, it means the image was buffered
1195                                                 if ( out_size > 0 )
1196                                                 {
1197                                                         AVPacket pkt;
1198                                                         av_init_packet( &pkt );
1199
1200                                                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1201                                                                 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1202                                                         mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "video pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1203                                                         if( c->coded_frame && c->coded_frame->key_frame )
1204                                                                 pkt.flags |= PKT_FLAG_KEY;
1205                                                         pkt.stream_index= video_st->index;
1206                                                         pkt.data= video_outbuf;
1207                                                         pkt.size= out_size;
1208
1209                                                         // write the compressed frame in the media file
1210                                                         ret = av_interleaved_write_frame(oc, &pkt);
1211                                                         mlt_log_debug( MLT_CONSUMER_SERVICE( this ), " frame_size %d\n", c->frame_size );
1212                                                         video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1213                                                         
1214                                                         // Dual pass logging
1215                                                         if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1216                                                                 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1217                                                 } 
1218                                                 else
1219                                                 {
1220                                                         mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "error with video encode\n" );
1221                                                 }
1222                                         }
1223                                         frame_count++;
1224                                         mlt_frame_close( frame );
1225                                 }
1226                                 else
1227                                 {
1228                                         break;
1229                                 }
1230                         }
1231                         if ( audio_st )
1232                                 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "audio pts %lld (%f) ", audio_st->pts.val, audio_pts );
1233                         if ( video_st )
1234                                 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "video pts %lld (%f) ", video_st->pts.val, video_pts );
1235                         mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "\n" );
1236                 }
1237
1238                 if ( real_time_output == 1 && frames % 12 == 0 )
1239                 {
1240                         long passed = time_difference( &ante );
1241                         if ( fifo != NULL )
1242                         {
1243                                 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1244                                 passed -= pending;
1245                         }
1246                         if ( passed < total_time )
1247                         {
1248                                 long total = ( total_time - passed );
1249                                 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1250                                 nanosleep( &t, NULL );
1251                         }
1252                 }
1253         }
1254
1255 #ifdef FLUSH
1256         if ( ! real_time_output )
1257         {
1258                 // Flush audio fifo
1259                 if ( audio_st && audio_st->codec->frame_size > 1 ) for (;;)
1260                 {
1261                         AVCodecContext *c = audio_st->codec;
1262                         AVPacket pkt;
1263                         av_init_packet( &pkt );
1264                         pkt.size = 0;
1265
1266                         if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1267                                 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1268                         {
1269                                 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
1270                                 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
1271                         }
1272                         if ( pkt.size <= 0 )
1273                                 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1274                         if ( pkt.size <= 0 )
1275                                 break;
1276
1277                         // Write the compressed frame in the media file
1278                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1279                                 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
1280                         pkt.flags |= PKT_FLAG_KEY;
1281                         pkt.stream_index = audio_st->index;
1282                         pkt.data = audio_outbuf;
1283                         if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1284                         {
1285                                 fprintf( stderr, "%s: Error while writing flushed audio frame\n", __FILE__ );
1286                                 break;
1287                         }
1288                 }
1289
1290                 // Flush video
1291                 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1292                 {
1293                         AVCodecContext *c = video_st->codec;
1294                         AVPacket pkt;
1295                         av_init_packet( &pkt );
1296
1297                         // Encode the image
1298                         pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1299                         if ( pkt.size <= 0 )
1300                                 break;
1301
1302                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1303                                 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1304                         if( c->coded_frame && c->coded_frame->key_frame )
1305                                 pkt.flags |= PKT_FLAG_KEY;
1306                         pkt.stream_index = video_st->index;
1307                         pkt.data = video_outbuf;
1308
1309                         // write the compressed frame in the media file
1310                         if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1311                         {
1312                                 mlt_log_error( MLT_CONSUMER_SERVICE(this), "error while writing flushing video frame\n" );
1313                                 break;
1314                         }
1315                 }
1316         }
1317 #endif
1318
1319         // XXX ugly hack to prevent x264 from crashing on second pass of multi-threaded encoding
1320         int pass = mlt_properties_get_int( properties, "pass" );
1321         int thread_count = mlt_properties_get_int( properties, "threads" );
1322         if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1323                 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1324         int multithreaded_x264 = ( video_codec_id == CODEC_ID_H264 && pass == 2 && thread_count > 1 );
1325         
1326         // close each codec
1327         if ( video_st && !multithreaded_x264 )
1328                 close_video(oc, video_st);
1329         if (audio_st)
1330                 close_audio(oc, audio_st);
1331
1332         // Write the trailer, if any
1333         av_write_trailer(oc);
1334
1335         // Free the streams
1336         for(i = 0; i < oc->nb_streams; i++)
1337                 av_freep(&oc->streams[i]);
1338
1339         // Close the output file
1340         if (!(fmt->flags & AVFMT_NOFILE))
1341 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1342                 url_fclose(oc->pb);
1343 #else
1344                 url_fclose(&oc->pb);
1345 #endif
1346
1347         // Clean up input and output frames
1348         if ( output )
1349                 av_free( output->data[0] );
1350         av_free( output );
1351         av_free( input->data[0] );
1352         av_free( input );
1353         av_free( video_outbuf );
1354         av_free( buffer );
1355
1356         // Free the stream
1357         av_free(oc);
1358
1359         // Just in case we terminated on pause
1360         mlt_properties_set_int( properties, "running", 0 );
1361
1362         mlt_consumer_stopped( this );
1363
1364         if ( pass == 2 )
1365         {
1366                 // Remove the dual pass log file
1367                 if ( mlt_properties_get( properties, "_logfilename" ) )
1368                         remove( mlt_properties_get( properties, "_logfilename" ) );
1369
1370                 // Remove the x264 dual pass logs
1371                 char *cwd = getcwd( NULL, 0 );
1372                 const char *file = "x264_2pass.log";
1373                 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1374                 sprintf( full, "%s/%s", cwd, file );
1375                 remove( full );
1376                 free( full );
1377                 file = "x264_2pass.log.temp";
1378                 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1379                 sprintf( full, "%s/%s", cwd, file );
1380                 remove( full );
1381                 free( full );
1382                 file = "x264_2pass.log.mbtree";
1383                 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1384                 sprintf( full, "%s/%s", cwd, file );
1385                 remove( full );
1386                 free( full );
1387                 free( cwd );
1388                 remove( "x264_2pass.log.temp" );
1389         }
1390
1391         return NULL;
1392 }
1393
1394 /** Close the consumer.
1395 */
1396
1397 static void consumer_close( mlt_consumer this )
1398 {
1399         // Stop the consumer
1400         mlt_consumer_stop( this );
1401
1402         // Close the parent
1403         mlt_consumer_close( this );
1404
1405         // Free the memory
1406         free( this );
1407 }