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