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