]> git.sesse.net Git - mlt/blob - src/modules/avformat/consumer_avformat.c
default to strict=experimental for painless aac encoding
[mlt] / src / modules / avformat / consumer_avformat.c
1 /*
2  * consumer_avformat.c -- an encoder based on avformat
3  * Copyright (C) 2003-2012 Ushodaya Enterprises Limited
4  * Author: Charles Yates <charles.yates@pandora.be>
5  * Author: Dan Dennedy <dan@dennedy.org>
6  * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 // mlt Header files
24 #include <framework/mlt_consumer.h>
25 #include <framework/mlt_frame.h>
26 #include <framework/mlt_profile.h>
27 #include <framework/mlt_log.h>
28 #include <framework/mlt_events.h>
29
30 // System header files
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <limits.h>
35 #include <pthread.h>
36 #include <sys/time.h>
37 #include <unistd.h>
38
39 // avformat header files
40 #include <libavformat/avformat.h>
41 #include <libavformat/avio.h>
42 #ifdef SWSCALE
43 #include <libswscale/swscale.h>
44 #endif
45 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
46 #include <libavutil/pixdesc.h>
47 #endif
48 #include <libavutil/mathematics.h>
49
50 #if LIBAVUTIL_VERSION_INT < (50<<16)
51 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
52 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
53 #endif
54
55 #if LIBAVCODEC_VERSION_MAJOR >= 53
56 #include <libavutil/opt.h>
57 #define CODEC_TYPE_VIDEO      AVMEDIA_TYPE_VIDEO
58 #define CODEC_TYPE_AUDIO      AVMEDIA_TYPE_AUDIO
59 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
60 #else
61 #include <libavcodec/opt.h>
62 #endif
63
64 #define MAX_AUDIO_STREAMS (8)
65 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
66 #define AUDIO_BUFFER_SIZE (1024 * 42)
67 #define VIDEO_BUFFER_SIZE (2048 * 1024)
68
69 //
70 // This structure should be extended and made globally available in mlt
71 //
72
73 typedef struct
74 {
75         int16_t *buffer;
76         int size;
77         int used;
78         double time;
79         int frequency;
80         int channels;
81 }
82 *sample_fifo, sample_fifo_s;
83
84 sample_fifo sample_fifo_init( int frequency, int channels )
85 {
86         sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
87         fifo->frequency = frequency;
88         fifo->channels = channels;
89         return fifo;
90 }
91
92 // sample_fifo_clear and check are temporarily aborted (not working as intended)
93
94 void sample_fifo_clear( sample_fifo fifo, double time )
95 {
96         int words = ( float )( time - fifo->time ) * fifo->frequency * fifo->channels;
97         if ( ( int )( ( float )time * 100 ) < ( int )( ( float )fifo->time * 100 ) && fifo->used > words && words > 0 )
98         {
99                 memmove( fifo->buffer, &fifo->buffer[ words ], ( fifo->used - words ) * sizeof( int16_t ) );
100                 fifo->used -= words;
101                 fifo->time = time;
102         }
103         else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )fifo->time * 100 ) )
104         {
105                 fifo->used = 0;
106                 fifo->time = time;
107         }
108 }
109
110 void sample_fifo_check( sample_fifo fifo, double time )
111 {
112         if ( fifo->used == 0 )
113         {
114                 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )fifo->time * 100 ) )
115                         fifo->time = time;
116         }
117 }
118
119 void sample_fifo_append( sample_fifo fifo, int16_t *samples, int count )
120 {
121         if ( ( fifo->size - fifo->used ) < count )
122         {
123                 fifo->size += count * 5;
124                 fifo->buffer = realloc( fifo->buffer, fifo->size * sizeof( int16_t ) );
125         }
126
127         memcpy( &fifo->buffer[ fifo->used ], samples, count * sizeof( int16_t ) );
128         fifo->used += count;
129 }
130
131 int sample_fifo_used( sample_fifo fifo )
132 {
133         return fifo->used;
134 }
135
136 int sample_fifo_fetch( sample_fifo fifo, int16_t *samples, int count )
137 {
138         if ( count > fifo->used )
139                 count = fifo->used;
140
141         memcpy( samples, fifo->buffer, count * sizeof( int16_t ) );
142         fifo->used -= count;
143         memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used * sizeof( int16_t ) );
144
145         fifo->time += ( double )count / fifo->channels / fifo->frequency;
146
147         return count;
148 }
149
150 void sample_fifo_close( sample_fifo fifo )
151 {
152         free( fifo->buffer );
153         free( fifo );
154 }
155
156 // Forward references.
157 static int consumer_start( mlt_consumer consumer );
158 static int consumer_stop( mlt_consumer consumer );
159 static int consumer_is_stopped( mlt_consumer consumer );
160 static void *consumer_thread( void *arg );
161 static void consumer_close( mlt_consumer consumer );
162
163 /** Initialise the consumer.
164 */
165
166 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
167 {
168         // Allocate the consumer
169         mlt_consumer consumer = mlt_consumer_new( profile );
170
171         // If memory allocated and initialises without error
172         if ( consumer != NULL )
173         {
174                 // Get properties from the consumer
175                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
176
177                 // Assign close callback
178                 consumer->close = consumer_close;
179
180                 // Interpret the argument
181                 if ( arg != NULL )
182                         mlt_properties_set( properties, "target", arg );
183
184                 // sample and frame queue
185                 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
186
187                 // Audio options not fully handled by AVOptions
188 #define QSCALE_NONE (-99999)
189                 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
190                 
191                 // Video options not fully handled by AVOptions
192                 mlt_properties_set_int( properties, "dc", 8 );
193                 
194                 // Muxer options not fully handled by AVOptions
195                 mlt_properties_set_double( properties, "muxdelay", 0.7 );
196                 mlt_properties_set_double( properties, "muxpreload", 0.5 );
197
198                 // Some AVOption defaults we like
199                 mlt_properties_set( properties, "strict", "experimental" );
200
201                 // Ensure termination at end of the stream
202                 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
203                 
204                 // Default to separate processing threads for producer and consumer with no frame dropping!
205                 mlt_properties_set_int( properties, "real_time", -1 );
206                 mlt_properties_set_int( properties, "prefill", 1 );
207
208                 // Set up start/stop/terminated callbacks
209                 consumer->start = consumer_start;
210                 consumer->stop = consumer_stop;
211                 consumer->is_stopped = consumer_is_stopped;
212                 
213                 mlt_events_register( properties, "consumer-fatal-error", NULL );
214         }
215
216         // Return consumer
217         return consumer;
218 }
219
220 /** Start the consumer.
221 */
222
223 static int consumer_start( mlt_consumer consumer )
224 {
225         // Get the properties
226         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
227         int error = 0;
228
229         // Report information about available muxers and codecs as YAML Tiny
230         char *s = mlt_properties_get( properties, "f" );
231         if ( s && strcmp( s, "list" ) == 0 )
232         {
233                 mlt_properties doc = mlt_properties_new();
234                 mlt_properties formats = mlt_properties_new();
235                 char key[20];
236                 AVOutputFormat *format = NULL;
237                 
238                 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
239                 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
240                 while ( ( format = av_oformat_next( format ) ) )
241                 {
242                         snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
243                         mlt_properties_set( formats, key, format->name );
244                 }
245                 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
246                 mlt_properties_close( doc );
247                 error = 1;
248         }
249         s = mlt_properties_get( properties, "acodec" );
250         if ( s && strcmp( s, "list" ) == 0 )
251         {
252                 mlt_properties doc = mlt_properties_new();
253                 mlt_properties codecs = mlt_properties_new();
254                 char key[20];
255                 AVCodec *codec = NULL;
256
257                 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
258                 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
259                 while ( ( codec = av_codec_next( codec ) ) )
260                         if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
261                         {
262                                 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
263                                 mlt_properties_set( codecs, key, codec->name );
264                         }
265                 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
266                 mlt_properties_close( doc );
267                 error = 1;
268         }
269         s = mlt_properties_get( properties, "vcodec" );
270         if ( s && strcmp( s, "list" ) == 0 )
271         {
272                 mlt_properties doc = mlt_properties_new();
273                 mlt_properties codecs = mlt_properties_new();
274                 char key[20];
275                 AVCodec *codec = NULL;
276
277                 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
278                 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
279                 while ( ( codec = av_codec_next( codec ) ) )
280                         if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
281                         {
282                                 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
283                                 mlt_properties_set( codecs, key, codec->name );
284                         }
285                 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
286                 mlt_properties_close( doc );
287                 error = 1;
288         }
289
290         // Check that we're not already running
291         if ( !error && !mlt_properties_get_int( properties, "running" ) )
292         {
293                 // Allocate a thread
294                 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
295
296                 // Get the width and height
297                 int width = mlt_properties_get_int( properties, "width" );
298                 int height = mlt_properties_get_int( properties, "height" );
299
300                 // Obtain the size property
301                 char *size = mlt_properties_get( properties, "s" );
302
303                 // Interpret it
304                 if ( size != NULL )
305                 {
306                         int tw, th;
307                         if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
308                         {
309                                 width = tw;
310                                 height = th;
311                         }
312                         else
313                         {
314                                 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Invalid size property %s - ignoring.\n", size );
315                         }
316                 }
317                 
318                 // Now ensure we honour the multiple of two requested by libavformat
319                 width = ( width / 2 ) * 2;
320                 height = ( height / 2 ) * 2;
321                 mlt_properties_set_int( properties, "width", width );
322                 mlt_properties_set_int( properties, "height", height );
323
324                 // We need to set these on the profile as well because the s property is
325                 // an alias to mlt properties that correspond to profile settings.
326                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
327                 if ( profile )
328                 {
329                         profile->width = width;
330                         profile->height = height;
331                 }
332
333                 // Handle the ffmpeg command line "-r" property for frame rate
334                 if ( mlt_properties_get( properties, "r" ) )
335                 {
336                         double frame_rate = mlt_properties_get_double( properties, "r" );
337                         AVRational rational = av_d2q( frame_rate, 255 );
338                         mlt_properties_set_int( properties, "frame_rate_num", rational.num );
339                         mlt_properties_set_int( properties, "frame_rate_den", rational.den );
340                         if ( profile )
341                         {
342                                 profile->frame_rate_num = rational.num;
343                                 profile->frame_rate_den = rational.den;
344                                 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
345                         }
346                 }
347                 
348                 // Apply AVOptions that are synonyms for standard mlt_consumer options
349                 if ( mlt_properties_get( properties, "ac" ) )
350                         mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
351                 if ( mlt_properties_get( properties, "ar" ) )
352                         mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
353
354                 // Assign the thread to properties
355                 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
356
357                 // Set the running state
358                 mlt_properties_set_int( properties, "running", 1 );
359
360                 // Create the thread
361                 pthread_create( thread, NULL, consumer_thread, consumer );
362         }
363         return error;
364 }
365
366 /** Stop the consumer.
367 */
368
369 static int consumer_stop( mlt_consumer consumer )
370 {
371         // Get the properties
372         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
373
374         // Check that we're running
375         if ( mlt_properties_get_int( properties, "running" ) )
376         {
377                 // Get the thread
378                 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
379
380                 // Stop the thread
381                 mlt_properties_set_int( properties, "running", 0 );
382
383                 // Wait for termination
384                 pthread_join( *thread, NULL );
385         }
386
387         return 0;
388 }
389
390 /** Determine if the consumer is stopped.
391 */
392
393 static int consumer_is_stopped( mlt_consumer consumer )
394 {
395         // Get the properties
396         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
397         return !mlt_properties_get_int( properties, "running" );
398 }
399
400 /** Process properties as AVOptions and apply to AV context obj
401 */
402
403 static void apply_properties( void *obj, mlt_properties properties, int flags )
404 {
405         int i;
406         int count = mlt_properties_count( properties );
407 #if LIBAVUTIL_VERSION_INT < ((51<<16)+(12<<8)+0)
408         int alloc = 1;
409 #endif
410
411         for ( i = 0; i < count; i++ )
412         {
413                 const char *opt_name = mlt_properties_get_name( properties, i );
414 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(7<<8)+0)
415                 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
416 #else
417                 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
418 #endif
419
420                 // If option not found, see if it was prefixed with a or v (-vb)
421                 if ( !opt && (
422                         ( opt_name[0] == 'v' && ( flags & AV_OPT_FLAG_VIDEO_PARAM ) ) ||
423                         ( opt_name[0] == 'a' && ( flags & AV_OPT_FLAG_AUDIO_PARAM ) ) ) )
424 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(7<<8)+0)
425                         opt = av_opt_find( obj, ++opt_name, NULL, flags, flags );
426 #else
427                         opt = av_find_opt( obj, ++opt_name, NULL, flags, flags );
428 #endif
429                 // Apply option if found
430                 if ( opt )
431 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
432                         av_opt_set( obj, opt_name, mlt_properties_get_value( properties, i), 0 );
433 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
434                         av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
435 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
436                         av_set_string2( obj, opt_name, mlt_properties_get_value( properties, i), alloc );
437 #else
438                         av_set_string( obj, opt_name, mlt_properties_get_value( properties, i) );
439 #endif
440         }
441 }
442
443 /** Add an audio output stream
444 */
445
446 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec, int channels )
447 {
448         // Get the properties
449         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
450
451         // Create a new stream
452 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
453         AVStream *st = avformat_new_stream( oc, codec );
454 #else
455         AVStream *st = av_new_stream( oc, oc->nb_streams );
456 #endif
457
458         // If created, then initialise from properties
459         if ( st != NULL ) 
460         {
461                 AVCodecContext *c = st->codec;
462
463                 // Establish defaults from AVOptions
464 #if LIBAVCODEC_VERSION_MAJOR >= 53
465                 avcodec_get_context_defaults3( c, codec );
466 #else
467                 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
468 #endif
469
470                 c->codec_id = codec->id;
471                 c->codec_type = CODEC_TYPE_AUDIO;
472                 c->sample_fmt = SAMPLE_FMT_S16;
473
474 #if 0 // disabled until some audio codecs are multi-threaded
475                 // Setup multi-threading
476                 int thread_count = mlt_properties_get_int( properties, "threads" );
477                 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
478                         thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
479                 if ( thread_count > 1 )
480                         c->thread_count = thread_count;
481 #endif
482         
483                 if (oc->oformat->flags & AVFMT_GLOBALHEADER) 
484                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
485                 
486                 // Allow the user to override the audio fourcc
487                 if ( mlt_properties_get( properties, "atag" ) )
488                 {
489                         char *tail = NULL;
490                         char *arg = mlt_properties_get( properties, "atag" );
491                         int tag = strtol( arg, &tail, 0);
492                         if( !tail || *tail )
493                                 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
494                         c->codec_tag = tag;
495                 }
496
497                 // Process properties as AVOptions
498                 char *apre = mlt_properties_get( properties, "apre" );
499                 if ( apre )
500                 {
501                         mlt_properties p = mlt_properties_load( apre );
502                         apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
503                         mlt_properties_close( p );
504                 }
505                 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
506
507                 int audio_qscale = mlt_properties_get_int( properties, "aq" );
508         if ( audio_qscale > QSCALE_NONE )
509                 {
510                         c->flags |= CODEC_FLAG_QSCALE;
511                         c->global_quality = FF_QP2LAMBDA * audio_qscale;
512 #if LIBAVFORMAT_VERSION_MAJOR < 53
513                         st->quality = c->global_quality;
514 #endif
515                 }
516
517                 // Set parameters controlled by MLT
518                 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
519                 c->time_base = ( AVRational ){ 1, c->sample_rate };
520                 c->channels = channels;
521
522                 if ( mlt_properties_get( properties, "alang" ) != NULL )
523 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
524 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
525                         av_dict_set( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
526 #else
527                         av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
528 #endif
529 #else
530
531                         strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
532 #endif
533         }
534         else
535         {
536                 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
537         }
538
539         return st;
540 }
541
542 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
543 {
544         // We will return the audio input size from here
545         int audio_input_frame_size = 0;
546
547         // Get the context
548         AVCodecContext *c = st->codec;
549
550         // Find the encoder
551         AVCodec *codec;
552         if ( codec_name )
553                 codec = avcodec_find_encoder_by_name( codec_name );
554         else
555                 codec = avcodec_find_encoder( c->codec_id );
556
557 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
558         // Process properties as AVOptions on the AVCodec
559         if ( codec && codec->priv_class )
560         {
561                 char *apre = mlt_properties_get( properties, "apre" );
562                 if ( !c->priv_data && codec->priv_data_size )
563                 {
564                         c->priv_data = av_mallocz( codec->priv_data_size );
565                         *(const AVClass **) c->priv_data = codec->priv_class;
566 //                      av_opt_set_defaults( c );
567                 }
568                 if ( apre )
569                 {
570                         mlt_properties p = mlt_properties_load( apre );
571                         apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
572                         mlt_properties_close( p );
573                 }
574                 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
575         }
576 #endif
577
578         // Continue if codec found and we can open it
579 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
580         if ( codec && avcodec_open2( c, codec, NULL ) >= 0 )
581 #else
582         if ( codec && avcodec_open( c, codec ) >= 0 )
583 #endif
584         {
585                 // ugly hack for PCM codecs (will be removed ASAP with new PCM
586                 // support to compute the input frame size in samples
587                 if ( c->frame_size <= 1 ) 
588                 {
589                         audio_input_frame_size = audio_outbuf_size / c->channels;
590                         switch(st->codec->codec_id) 
591                         {
592                                 case CODEC_ID_PCM_S16LE:
593                                 case CODEC_ID_PCM_S16BE:
594                                 case CODEC_ID_PCM_U16LE:
595                                 case CODEC_ID_PCM_U16BE:
596                                         audio_input_frame_size >>= 1;
597                                         break;
598                                 default:
599                                         break;
600                         }
601                 } 
602                 else 
603                 {
604                         audio_input_frame_size = c->frame_size;
605                 }
606
607                 // Some formats want stream headers to be seperate (hmm)
608                 if ( !strcmp( oc->oformat->name, "mp4" ) ||
609                          !strcmp( oc->oformat->name, "mov" ) ||
610                          !strcmp( oc->oformat->name, "3gp" ) )
611                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
612         }
613         else
614         {
615                 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
616         }
617
618         return audio_input_frame_size;
619 }
620
621 static void close_audio( AVFormatContext *oc, AVStream *st )
622 {
623         if ( st && st->codec )
624                 avcodec_close( st->codec );
625 }
626
627 /** Add a video output stream 
628 */
629
630 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
631 {
632         // Get the properties
633         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
634
635         // Create a new stream
636 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
637         AVStream *st = avformat_new_stream( oc, codec );
638 #else
639         AVStream *st = av_new_stream( oc, oc->nb_streams );
640 #endif
641
642         if ( st != NULL ) 
643         {
644                 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
645                 AVCodecContext *c = st->codec;
646
647                 // Establish defaults from AVOptions
648 #if LIBAVCODEC_VERSION_MAJOR >= 53
649                 avcodec_get_context_defaults3( c, codec );
650 #else
651                 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
652 #endif
653
654                 c->codec_id = codec->id;
655                 c->codec_type = CODEC_TYPE_VIDEO;
656                 
657                 // Setup multi-threading
658                 int thread_count = mlt_properties_get_int( properties, "threads" );
659                 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
660                         thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
661                 if ( thread_count > 1 )
662 #if LIBAVCODEC_VERSION_MAJOR >= 53
663                         c->thread_count = thread_count;
664 #else
665                         avcodec_thread_init( c, thread_count );
666 #endif
667
668                 // Process properties as AVOptions
669                 char *vpre = mlt_properties_get( properties, "vpre" );
670                 if ( vpre )
671                 {
672                         mlt_properties p = mlt_properties_load( vpre );
673 #ifdef AVDATADIR
674                         if ( mlt_properties_count( p ) < 1 )
675                         {
676                                 AVCodec *codec = avcodec_find_encoder( c->codec_id );
677                                 if ( codec )
678                                 {
679                                         char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
680                                         strcpy( path, AVDATADIR );
681                                         strcat( path, codec->name );
682                                         strcat( path, "-" );
683                                         strcat( path, vpre );
684                                         strcat( path, ".ffpreset" );
685                                         
686                                         mlt_properties_close( p );
687                                         p = mlt_properties_load( path );
688                                         if ( mlt_properties_count( p ) > 0 )
689                                                 mlt_properties_debug( p, path, stderr );
690                                         free( path );   
691                                 }
692                         }
693                         else
694                         {
695                                 mlt_properties_debug( p, vpre, stderr );                        
696                         }
697 #endif
698                         apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
699                         mlt_properties_close( p );
700                 }
701                 int colorspace = mlt_properties_get_int( properties, "colorspace" );
702                 mlt_properties_set( properties, "colorspace", NULL );
703                 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
704                 mlt_properties_set_int( properties, "colorspace", colorspace );
705
706                 // Set options controlled by MLT
707                 c->width = mlt_properties_get_int( properties, "width" );
708                 c->height = mlt_properties_get_int( properties, "height" );
709                 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
710                 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
711                 if ( st->time_base.den == 0 )
712                         st->time_base = c->time_base;
713 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
714                 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
715 #else
716                 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
717 #endif
718                 
719 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
720                 switch ( colorspace )
721                 {
722                 case 170:
723                         c->colorspace = AVCOL_SPC_SMPTE170M;
724                         break;
725                 case 240:
726                         c->colorspace = AVCOL_SPC_SMPTE240M;
727                         break;
728                 case 470:
729                         c->colorspace = AVCOL_SPC_BT470BG;
730                         break;
731                 case 601:
732                         c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
733                         break;
734                 case 709:
735                         c->colorspace = AVCOL_SPC_BT709;
736                         break;
737                 }
738 #endif
739
740                 if ( mlt_properties_get( properties, "aspect" ) )
741                 {
742                         // "-aspect" on ffmpeg command line is display aspect ratio
743                         double ar = mlt_properties_get_double( properties, "aspect" );
744                         AVRational rational = av_d2q( ar, 255 );
745
746                         // Update the profile and properties as well since this is an alias 
747                         // for mlt properties that correspond to profile settings
748                         mlt_properties_set_int( properties, "display_aspect_num", rational.num );
749                         mlt_properties_set_int( properties, "display_aspect_den", rational.den );
750                         mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
751                         if ( profile )
752                         {
753                                 profile->display_aspect_num = rational.num;
754                                 profile->display_aspect_den = rational.den;
755                                 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
756                         }
757
758                         // Now compute the sample aspect ratio
759                         rational = av_d2q( ar * c->height / c->width, 255 );
760                         c->sample_aspect_ratio = rational;
761                         // Update the profile and properties as well since this is an alias 
762                         // for mlt properties that correspond to profile settings
763                         mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
764                         mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
765                         if ( profile )
766                         {
767                                 profile->sample_aspect_num = rational.num;
768                                 profile->sample_aspect_den = rational.den;
769                                 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
770                         }
771                 }
772                 else
773                 {
774                         c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
775                         c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
776                 }
777 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
778                 st->sample_aspect_ratio = c->sample_aspect_ratio;
779 #endif
780
781                 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
782                 {
783                         c->flags |= CODEC_FLAG_QSCALE;
784                         c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
785 #if LIBAVFORMAT_VERSION_MAJOR < 53
786                         st->quality = c->global_quality;
787 #endif
788                 }
789
790                 // Allow the user to override the video fourcc
791                 if ( mlt_properties_get( properties, "vtag" ) )
792                 {
793                         char *tail = NULL;
794                         const char *arg = mlt_properties_get( properties, "vtag" );
795                         int tag = strtol( arg, &tail, 0);
796                         if( !tail || *tail )
797                                 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
798                         c->codec_tag = tag;
799                 }
800
801                 // Some formats want stream headers to be seperate
802                 if ( oc->oformat->flags & AVFMT_GLOBALHEADER ) 
803                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
804
805                 // Translate these standard mlt consumer properties to ffmpeg
806                 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
807                      mlt_properties_get_int( properties, "deinterlace" ) == 0 )
808                 {
809                         if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
810                                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
811                         if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
812                                 c->flags |= CODEC_FLAG_INTERLACED_ME;
813                 }
814                 
815                 // parse the ratecontrol override string
816                 int i;
817                 char *rc_override = mlt_properties_get( properties, "rc_override" );
818                 for ( i = 0; rc_override; i++ )
819                 {
820                         int start, end, q;
821                         int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
822                         if ( e != 3 )
823                                 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
824                         c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
825                         c->rc_override[i].start_frame = start;
826                         c->rc_override[i].end_frame = end;
827                         if ( q > 0 )
828                         {
829                                 c->rc_override[i].qscale = q;
830                                 c->rc_override[i].quality_factor = 1.0;
831                         }
832                         else
833                         {
834                                 c->rc_override[i].qscale = 0;
835                                 c->rc_override[i].quality_factor = -q / 100.0;
836                         }
837                         rc_override = strchr( rc_override, '/' );
838                         if ( rc_override )
839                                 rc_override++;
840                 }
841                 c->rc_override_count = i;
842                 if ( !c->rc_initial_buffer_occupancy )
843                         c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
844                 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
845
846                 // Setup dual-pass
847                 i = mlt_properties_get_int( properties, "pass" );
848                 if ( i == 1 )
849                         c->flags |= CODEC_FLAG_PASS1;
850                 else if ( i == 2 )
851                         c->flags |= CODEC_FLAG_PASS2;
852                 if ( codec->id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
853                 {
854                         char logfilename[1024];
855                         FILE *f;
856                         int size;
857                         char *logbuffer;
858
859                         snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
860                                 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
861                         if ( c->flags & CODEC_FLAG_PASS1 )
862                         {
863                                 f = fopen( logfilename, "w" );
864                                 if ( !f )
865                                         perror( logfilename );
866                                 else
867                                         mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
868                         }
869                         else
870                         {
871                                 /* read the log file */
872                                 f = fopen( logfilename, "r" );
873                                 if ( !f )
874                                 {
875                                         perror(logfilename);
876                                 }
877                                 else
878                                 {
879                                         mlt_properties_set( properties, "_logfilename", logfilename );
880                                         fseek( f, 0, SEEK_END );
881                                         size = ftell( f );
882                                         fseek( f, 0, SEEK_SET );
883                                         logbuffer = av_malloc( size + 1 );
884                                         if ( !logbuffer )
885                                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
886                                         else
887                                         {
888                                                 size = fread( logbuffer, 1, size, f );
889                                                 fclose( f );
890                                                 logbuffer[size] = '\0';
891                                                 c->stats_in = logbuffer;
892                                         }
893                                 }
894                         }
895                 }
896         }
897         else
898         {
899                 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
900         }
901  
902         return st;
903 }
904
905 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
906 {
907         // Allocate a frame
908         AVFrame *picture = avcodec_alloc_frame();
909
910         // Determine size of the 
911         int size = avpicture_get_size(pix_fmt, width, height);
912
913         // Allocate the picture buf
914         uint8_t *picture_buf = av_malloc(size);
915
916         // If we have both, then fill the image
917         if ( picture != NULL && picture_buf != NULL )
918         {
919                 // Fill the frame with the allocated buffer
920                 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
921         }
922         else
923         {
924                 // Something failed - clean up what we can
925                 av_free( picture );
926                 av_free( picture_buf );
927                 picture = NULL;
928         }
929
930         return picture;
931 }
932
933 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
934 {
935         // Get the codec
936         AVCodecContext *video_enc = st->codec;
937
938         // find the video encoder
939         AVCodec *codec;
940         if ( codec_name )
941                 codec = avcodec_find_encoder_by_name( codec_name );
942         else
943                 codec = avcodec_find_encoder( video_enc->codec_id );
944
945 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
946         // Process properties as AVOptions on the AVCodec
947         if ( codec && codec->priv_class )
948         {
949                 char *vpre = mlt_properties_get( properties, "vpre" );
950                 if ( !video_enc->priv_data && codec->priv_data_size )
951                 {
952                         video_enc->priv_data = av_mallocz( codec->priv_data_size );
953                         *(const AVClass **) video_enc->priv_data = codec->priv_class;
954 //                      av_opt_set_defaults( video_enc );
955                 }
956                 if ( vpre )
957                 {
958                         mlt_properties p = mlt_properties_load( vpre );
959                         apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
960                         mlt_properties_close( p );
961                 }
962                 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
963         }
964 #endif
965
966         if( codec && codec->pix_fmts )
967         {
968                 const enum PixelFormat *p = codec->pix_fmts;
969                 for( ; *p!=-1; p++ )
970                 {
971                         if( *p == video_enc->pix_fmt )
972                                 break;
973                 }
974                 if( *p == -1 )
975                         video_enc->pix_fmt = codec->pix_fmts[ 0 ];
976         }
977
978 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
979         int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
980 #else
981         int result = codec && avcodec_open( video_enc, codec ) >= 0;
982 #endif
983         
984         return result;
985 }
986
987 void close_video(AVFormatContext *oc, AVStream *st)
988 {
989         if ( st && st->codec )
990         {
991                 av_freep( &st->codec->stats_in );
992                 avcodec_close(st->codec);
993         }
994 }
995
996 static inline long time_difference( struct timeval *time1 )
997 {
998         struct timeval time2;
999         gettimeofday( &time2, NULL );
1000         return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1001 }
1002
1003 static int mlt_write(void *h, uint8_t *buf, int size)
1004 {
1005         mlt_properties properties = (mlt_properties) h;
1006         mlt_events_fire( properties, "avformat-write", buf, size, NULL );
1007         return 0;
1008 }
1009
1010 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1011 {
1012         listener( owner, service, (uint8_t*) args[0], (int) args[1] );
1013 }
1014
1015
1016 /** The main thread - the argument is simply the consumer.
1017 */
1018
1019 static void *consumer_thread( void *arg )
1020 {
1021         // Map the argument to the object
1022         mlt_consumer consumer = arg;
1023
1024         // Get the properties
1025         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1026
1027         // Get the terminate on pause property
1028         int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1029         int terminated = 0;
1030
1031         // Determine if feed is slow (for realtime stuff)
1032         int real_time_output = mlt_properties_get_int( properties, "real_time" );
1033
1034         // Time structures
1035         struct timeval ante;
1036
1037         // Get the frame rate
1038         double fps = mlt_properties_get_double( properties, "fps" );
1039
1040         // Get width and height
1041         int width = mlt_properties_get_int( properties, "width" );
1042         int height = mlt_properties_get_int( properties, "height" );
1043         int img_width = width;
1044         int img_height = height;
1045
1046         // Get default audio properties
1047         mlt_audio_format aud_fmt = mlt_audio_s16;
1048         int channels = mlt_properties_get_int( properties, "channels" );
1049         int total_channels = channels;
1050         int frequency = mlt_properties_get_int( properties, "frequency" );
1051         int16_t *pcm = NULL;
1052         int samples = 0;
1053
1054         // AVFormat audio buffer and frame size
1055         int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1056         uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1057         int audio_input_frame_size = 0;
1058
1059         // AVFormat video buffer and frame count
1060         int frame_count = 0;
1061         int video_outbuf_size = VIDEO_BUFFER_SIZE;
1062         uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1063
1064         // Used for the frame properties
1065         mlt_frame frame = NULL;
1066         mlt_properties frame_properties = NULL;
1067
1068         // Get the queues
1069         mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1070         sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1071
1072         // Need two av pictures for converting
1073         AVFrame *output = NULL;
1074         AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
1075
1076         // For receiving images from an mlt_frame
1077         uint8_t *image;
1078         mlt_image_format img_fmt = mlt_image_yuv422;
1079
1080         // For receiving audio samples back from the fifo
1081         int16_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1082         int16_t *audio_buf_2 = NULL;
1083         int count = 0;
1084
1085         // Allocate the context
1086 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
1087         AVFormatContext *oc = avformat_alloc_context( );
1088 #else
1089         AVFormatContext *oc = av_alloc_format_context( );
1090 #endif
1091
1092         // Streams
1093         AVStream *video_st = NULL;
1094         AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1095
1096         // Time stamps
1097         double audio_pts = 0;
1098         double video_pts = 0;
1099
1100         // Frames dispatched
1101         long int frames = 0;
1102         long int total_time = 0;
1103
1104         // Determine the format
1105         AVOutputFormat *fmt = NULL;
1106         const char *filename = mlt_properties_get( properties, "target" );
1107         char *format = mlt_properties_get( properties, "f" );
1108         char *vcodec = mlt_properties_get( properties, "vcodec" );
1109         char *acodec = mlt_properties_get( properties, "acodec" );
1110         AVCodec *audio_codec = NULL;
1111         AVCodec *video_codec = NULL;
1112         
1113         // Used to store and override codec ids
1114         int audio_codec_id;
1115         int video_codec_id;
1116
1117         // Misc
1118         char key[27];
1119         mlt_properties frame_meta_properties = mlt_properties_new();
1120
1121         // Initialize audio_st
1122         int i = MAX_AUDIO_STREAMS;
1123         while ( i-- )
1124                 audio_st[i] = NULL;
1125
1126         // Check for user selected format first
1127         if ( format != NULL )
1128 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1129                 fmt = guess_format( format, NULL, NULL );
1130 #else
1131                 fmt = av_guess_format( format, NULL, NULL );
1132 #endif
1133
1134         // Otherwise check on the filename
1135         if ( fmt == NULL && filename != NULL )
1136 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1137                 fmt = guess_format( NULL, filename, NULL );
1138 #else
1139                 fmt = av_guess_format( NULL, filename, NULL );
1140 #endif
1141
1142         // Otherwise default to mpeg
1143         if ( fmt == NULL )
1144 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1145                 fmt = guess_format( "mpeg", NULL, NULL );
1146 #else
1147                 fmt = av_guess_format( "mpeg", NULL, NULL );
1148 #endif
1149
1150         // We need a filename - default to stdout?
1151         if ( filename == NULL || !strcmp( filename, "" ) )
1152                 filename = "pipe:";
1153
1154         // Get the codec ids selected
1155         audio_codec_id = fmt->audio_codec;
1156         video_codec_id = fmt->video_codec;
1157
1158         // Check for audio codec overides
1159         if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1160                 audio_codec_id = CODEC_ID_NONE;
1161         else if ( acodec )
1162         {
1163                 audio_codec = avcodec_find_encoder_by_name( acodec );
1164                 if ( audio_codec )
1165                 {
1166                         audio_codec_id = audio_codec->id;
1167                         if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1168                         {
1169                                 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1170                                 acodec = mlt_properties_get( properties, "_acodec" );
1171                                 audio_codec = avcodec_find_encoder_by_name( acodec );
1172                         }
1173                 }
1174                 else
1175                 {
1176                         audio_codec_id = CODEC_ID_NONE;
1177                         mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1178                 }
1179         }
1180         else
1181         {
1182                 audio_codec = avcodec_find_encoder( audio_codec_id );
1183         }
1184
1185         // Check for video codec overides
1186         if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1187                 video_codec_id = CODEC_ID_NONE;
1188         else if ( vcodec )
1189         {
1190                 video_codec = avcodec_find_encoder_by_name( vcodec );
1191                 if ( video_codec )
1192                 {
1193                         video_codec_id = video_codec->id;
1194                 }
1195                 else
1196                 {
1197                         video_codec_id = CODEC_ID_NONE;
1198                         mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1199                 }
1200         }
1201         else
1202         {
1203                 video_codec = avcodec_find_encoder( video_codec_id );
1204         }
1205
1206         // Write metadata
1207 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1208         for ( i = 0; i < mlt_properties_count( properties ); i++ )
1209         {
1210                 char *name = mlt_properties_get_name( properties, i );
1211                 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1212                 {
1213                         char *key = strdup( name + 10 );
1214                         char *markup = strrchr( key, '.' );
1215                         if ( markup && !strcmp( markup, ".markup") )
1216                         {
1217                                 markup[0] = '\0';
1218                                 if ( !strstr( key, ".stream." ) )
1219 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1220 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1221                                         av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1222 #else
1223                                         av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1224 #endif
1225 #else
1226                                         av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1227 #endif
1228                         }
1229                         free( key );
1230                 }
1231         }
1232 #else
1233         char *tmp = NULL;
1234         int metavalue;
1235
1236         tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1237         if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1238
1239         tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1240         if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1241
1242         tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1243         if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1244
1245         tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1246         if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1247
1248         tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1249         if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1250
1251         metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1252         if (metavalue != 0) oc->year = metavalue;
1253
1254         metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1255         if (metavalue != 0) oc->track = metavalue;
1256 #endif
1257
1258         oc->oformat = fmt;
1259         snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1260
1261         // Get a frame now, so we can set some AVOptions from properties.
1262         frame = mlt_consumer_rt_frame( consumer );
1263
1264         // Set the timecode from the MLT metadata if available.
1265     if ( frame )
1266     {
1267         const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1268         if ( timecode && strcmp( timecode, "" ) )
1269         {
1270             mlt_properties_set( properties, "timecode", timecode );
1271             if ( strchr( timecode, ';' ) )
1272                 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1273         }
1274     }
1275
1276         // Add audio and video streams
1277         if ( video_codec_id != CODEC_ID_NONE )
1278                 video_st = add_video_stream( consumer, oc, video_codec );
1279         if ( audio_codec_id != CODEC_ID_NONE )
1280         {
1281                 int is_multi = 0;
1282
1283                 total_channels = 0;
1284                 // multitrack audio
1285                 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1286                 {
1287                         sprintf( key, "channels.%d", i );
1288                         int j = mlt_properties_get_int( properties, key );
1289                         if ( j )
1290                         {
1291                                 is_multi = 1;
1292                                 total_channels += j;
1293                                 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1294                         }
1295                 }
1296                 // single track
1297                 if ( !is_multi )
1298                 {
1299                         audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1300                         total_channels = channels;
1301                 }
1302         }
1303         mlt_properties_set_int( properties, "channels", total_channels );
1304
1305         // Set the parameters (even though we have none...)
1306 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1307         if ( av_set_parameters(oc, NULL) >= 0 )
1308 #endif
1309         {
1310 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1311                 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1312                         mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1313 #else
1314                 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1315 #endif
1316                 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1317
1318                 // Process properties as AVOptions
1319                 char *fpre = mlt_properties_get( properties, "fpre" );
1320                 if ( fpre )
1321                 {
1322                         mlt_properties p = mlt_properties_load( fpre );
1323                         apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1324 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1325                         if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1326                                 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1327 #endif
1328                         mlt_properties_close( p );
1329                 }
1330                 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1331 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1332                 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1333                         apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1334 #endif
1335
1336                 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1337                         video_st = NULL;
1338                 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1339                 {
1340                         audio_input_frame_size = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1341                                 acodec? acodec : NULL );
1342                         if ( !audio_input_frame_size )
1343                                 audio_st[i] = NULL;
1344                 }
1345
1346                 // Setup custom I/O if redirecting
1347                 if ( mlt_properties_get_int( properties, "redirect" ) )
1348                 {
1349                         int buffer_size = 32768;
1350                         unsigned char *buffer = av_malloc( buffer_size );
1351 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1352                         AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1353 #else
1354                         ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1355 #endif
1356                         if ( buffer && io )
1357                         {
1358                                 oc->pb = io;
1359 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1360                                 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1361 #endif
1362                                 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1363                                 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1364                                 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1365                         }
1366                         else
1367                         {
1368                                 av_free( buffer );
1369                                 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1370                         }
1371                 }
1372                 // Open the output file, if needed
1373                 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1374                 {
1375 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1376                         if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1377 #else
1378                         if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1379 #endif
1380                         {
1381                                 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1382                                 mlt_properties_set_int( properties, "running", 0 );
1383                         }
1384                 }
1385         
1386                 // Write the stream header.
1387                 if ( mlt_properties_get_int( properties, "running" ) )
1388 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1389                         avformat_write_header( oc, NULL );
1390 #else
1391                         av_write_header( oc );
1392 #endif
1393         }
1394 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1395         else
1396         {
1397                 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1398                 mlt_properties_set_int( properties, "running", 0 );
1399         }
1400 #endif
1401
1402         // Allocate picture
1403         if ( video_st )
1404                 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1405
1406         // Last check - need at least one stream
1407         if ( !audio_st[0] && !video_st )
1408                 mlt_properties_set_int( properties, "running", 0 );
1409
1410         // Get the starting time (can ignore the times above)
1411         gettimeofday( &ante, NULL );
1412
1413         // Loop while running
1414         while( mlt_properties_get_int( properties, "running" ) &&
1415                ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1416         {
1417                 if ( !frame )
1418                         frame = mlt_consumer_rt_frame( consumer );
1419
1420                 // Check that we have a frame to work with
1421                 if ( frame != NULL )
1422                 {
1423                         // Increment frames dispatched
1424                         frames ++;
1425
1426                         // Default audio args
1427                         frame_properties = MLT_FRAME_PROPERTIES( frame );
1428
1429                         // Check for the terminated condition
1430                         terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1431
1432                         // Get audio and append to the fifo
1433                         if ( !terminated && audio_st[0] )
1434                         {
1435                                 samples = mlt_sample_calculator( fps, frequency, count ++ );
1436                                 channels = total_channels;
1437                                 mlt_frame_get_audio( frame, (void**) &pcm, &aud_fmt, &frequency, &channels, &samples );
1438
1439                                 // Save the audio channel remap properties for later
1440                                 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1441
1442                                 // Create the fifo if we don't have one
1443                                 if ( fifo == NULL )
1444                                 {
1445                                         fifo = sample_fifo_init( frequency, channels );
1446                                         mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1447                                 }
1448
1449                                 // Silence if not normal forward speed
1450                                 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1451                                         memset( pcm, 0, samples * channels * 2 );
1452
1453                                 // Append the samples
1454                                 sample_fifo_append( fifo, pcm, samples * channels );
1455                                 total_time += ( samples * 1000000 ) / frequency;
1456
1457                                 if ( !video_st )
1458                                         mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1459                         }
1460
1461                         // Encode the image
1462                         if ( !terminated && video_st )
1463                                 mlt_deque_push_back( queue, frame );
1464                         else
1465                                 mlt_frame_close( frame );
1466                         frame = NULL;
1467                 }
1468
1469                 // While we have stuff to process, process...
1470                 while ( 1 )
1471                 {
1472                         // Write interleaved audio and video frames
1473                         if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1474                         {
1475                                 // Write audio
1476                                 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1477                                 {
1478                                         int j = 0; // channel offset into interleaved source buffer
1479                                         int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) ), AUDIO_ENCODE_BUFFER_SIZE );
1480
1481                                         // Get the audio samples
1482                                         if ( n > 0 )
1483                                         {
1484                                                 sample_fifo_fetch( fifo, audio_buf_1, n );
1485                                         }
1486                                         else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1487                                         {
1488                                                 // This prevents an infinite loop when some versions of vorbis do not
1489                                                 // increment pts when encoding silence.
1490                                                 audio_pts = video_pts;
1491                                                 break;
1492                                         }
1493                                         else
1494                                         {
1495                                                 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1496                                         }
1497                                         samples = n / channels;
1498
1499                                         // For each output stream
1500                                         for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1501                                         {
1502                                                 AVStream *stream = audio_st[i];
1503                                                 AVCodecContext *codec = stream->codec;
1504                                                 AVPacket pkt;
1505
1506                                                 av_init_packet( &pkt );
1507
1508                                                 // Optimized for single track and no channel remap
1509                                                 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1510                                                 {
1511                                                         pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1512                                                 }
1513                                                 else
1514                                                 {
1515                                                         // Extract the audio channels according to channel mapping
1516                                                         int dest_offset = 0; // channel offset into interleaved dest buffer
1517
1518                                                         // Get the number of channels for this stream
1519                                                         sprintf( key, "channels.%d", i );
1520                                                         int current_channels = mlt_properties_get_int( properties, key );
1521
1522                                                         // Clear the destination audio buffer.
1523                                                         if ( !audio_buf_2 )
1524                                                                 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1525                                                         else
1526                                                                 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1527
1528                                                         // For each output channel
1529                                                         while ( dest_offset < current_channels && j < total_channels )
1530                                                         {
1531                                                                 int map_start = -1, map_channels = 0;
1532                                                                 int source_offset = 0;
1533                                                                 int k;
1534
1535                                                                 // Look for a mapping that starts at j
1536                                                                 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1537                                                                 {
1538                                                                         sprintf( key, "%d.channels", k );
1539                                                                         map_channels = mlt_properties_get_int( frame_meta_properties, key );
1540                                                                         sprintf( key, "%d.start", k );
1541                                                                         if ( mlt_properties_get( frame_meta_properties, key ) )
1542                                                                                 map_start = mlt_properties_get_int( frame_meta_properties, key );
1543                                                                         if ( map_start != j )
1544                                                                                 source_offset += map_channels;
1545                                                                 }
1546
1547                                                                 // If no mapping
1548                                                                 if ( map_start != j )
1549                                                                 {
1550                                                                         map_channels = current_channels;
1551                                                                         source_offset = j;
1552                                                                 }
1553
1554                                                                 // Copy samples if source offset valid
1555                                                                 if ( source_offset < channels )
1556                                                                 {
1557                                                                         // Interleave the audio buffer with the # channels for this stream/mapping.
1558                                                                         for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1559                                                                         {
1560                                                                                 int16_t *src = audio_buf_1 + source_offset;
1561                                                                                 int16_t *dest = audio_buf_2 + dest_offset;
1562                                                                                 int s = samples + 1;
1563
1564                                                                                 while ( --s ) {
1565                                                                                         *dest = *src;
1566                                                                                         dest += current_channels;
1567                                                                                         src += channels;
1568                                                                                 }
1569                                                                         }
1570                                                                 }
1571                                                                 // Otherwise silence
1572                                                                 else
1573                                                                 {
1574                                                                         j += current_channels;
1575                                                                         dest_offset += current_channels;
1576                                                                 }
1577                                                         }
1578                                                         pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_2 );
1579                                                 }
1580
1581                                                 // Write the compressed frame in the media file
1582                                                 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1583                                                 {
1584                                                         pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1585                                                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame pts %"PRId64,
1586                                                                 stream->index, pkt.pts, codec->coded_frame->pts );
1587                                                 }
1588                                                 pkt.flags |= PKT_FLAG_KEY;
1589                                                 pkt.stream_index = stream->index;
1590                                                 pkt.data = audio_outbuf;
1591
1592                                                 if ( pkt.size > 0 )
1593                                                 {
1594                                                         if ( av_interleaved_write_frame( oc, &pkt ) )
1595                                                         {
1596                                                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1597                                                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1598                                                                 goto on_fatal_error;
1599                                                         }
1600                                                 }
1601
1602                                                 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1603                                                 if ( i == 0 )
1604                                                 {
1605                                                         audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1606                                                 }
1607                                         }
1608                                 }
1609                                 else
1610                                 {
1611                                         break;
1612                                 }
1613                         }
1614                         else if ( video_st )
1615                         {
1616                                 // Write video
1617                                 if ( mlt_deque_count( queue ) )
1618                                 {
1619                                         int out_size, ret = 0;
1620                                         AVCodecContext *c;
1621
1622                                         frame = mlt_deque_pop_front( queue );
1623                                         frame_properties = MLT_FRAME_PROPERTIES( frame );
1624
1625                                         c = video_st->codec;
1626                                         
1627                                         if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1628                                         {
1629                                                 int i = 0;
1630                                                 uint8_t *p;
1631                                                 uint8_t *q;
1632
1633                                                 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1634
1635                                                 q = image;
1636
1637                                                 // Convert the mlt frame to an AVPicture
1638                                                 for ( i = 0; i < height; i ++ )
1639                                                 {
1640                                                         p = input->data[ 0 ] + i * input->linesize[ 0 ];
1641                                                         memcpy( p, q, width * 2 );
1642                                                         q += width * 2;
1643                                                 }
1644
1645                                                 // Do the colour space conversion
1646 #ifdef SWSCALE
1647                                                 int flags = SWS_BILINEAR;
1648 #ifdef USE_MMX
1649                                                 flags |= SWS_CPU_CAPS_MMX;
1650 #endif
1651 #ifdef USE_SSE
1652                                                 flags |= SWS_CPU_CAPS_MMX2;
1653 #endif
1654                                                 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1655                                                         width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1656                                                 sws_scale( context, (const uint8_t* const*) input->data, input->linesize, 0, height,
1657                                                         output->data, output->linesize);
1658                                                 sws_freeContext( context );
1659 #else
1660                                                 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1661 #endif
1662
1663                                                 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1664
1665                                                 // Apply the alpha if applicable
1666                                                 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1667                                                 {
1668                                                         uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1669                                                         register int n;
1670
1671                                                         for ( i = 0; i < height; i ++ )
1672                                                         {
1673                                                                 n = ( width + 7 ) / 8;
1674                                                                 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1675
1676                                                                 switch( width % 8 )
1677                                                                 {
1678                                                                         case 0: do { *p = *alpha++; p += 4;
1679                                                                         case 7:          *p = *alpha++; p += 4;
1680                                                                         case 6:          *p = *alpha++; p += 4;
1681                                                                         case 5:          *p = *alpha++; p += 4;
1682                                                                         case 4:          *p = *alpha++; p += 4;
1683                                                                         case 3:          *p = *alpha++; p += 4;
1684                                                                         case 2:          *p = *alpha++; p += 4;
1685                                                                         case 1:          *p = *alpha++; p += 4;
1686                                                                                         }
1687                                                                                         while( --n );
1688                                                                 }
1689                                                         }
1690                                                 }
1691                                         }
1692
1693                                         if (oc->oformat->flags & AVFMT_RAWPICTURE) 
1694                                         {
1695                                                 // raw video case. The API will change slightly in the near future for that
1696                                                 AVPacket pkt;
1697                                                 av_init_packet(&pkt);
1698
1699                                                 pkt.flags |= PKT_FLAG_KEY;
1700                                                 pkt.stream_index= video_st->index;
1701                                                 pkt.data= (uint8_t *)output;
1702                                                 pkt.size= sizeof(AVPicture);
1703
1704                                                 ret = av_write_frame(oc, &pkt);
1705                                                 video_pts += c->frame_size;
1706                                         } 
1707                                         else 
1708                                         {
1709                                                 // Set the quality
1710                                                 output->quality = c->global_quality;
1711
1712                                                 // Set frame interlace hints
1713                                                 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1714                                                 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1715                                                 output->pts = frame_count;
1716
1717                                                 // Encode the image
1718                                                 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1719
1720                                                 // If zero size, it means the image was buffered
1721                                                 if ( out_size > 0 )
1722                                                 {
1723                                                         AVPacket pkt;
1724                                                         av_init_packet( &pkt );
1725
1726                                                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1727                                                                 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1728                                                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %"PRId64" frame pts %"PRId64, pkt.pts, c->coded_frame->pts );
1729                                                         if( c->coded_frame && c->coded_frame->key_frame )
1730                                                                 pkt.flags |= PKT_FLAG_KEY;
1731                                                         pkt.stream_index= video_st->index;
1732                                                         pkt.data= video_outbuf;
1733                                                         pkt.size= out_size;
1734
1735                                                         // write the compressed frame in the media file
1736                                                         ret = av_interleaved_write_frame(oc, &pkt);
1737                                                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1738                                                         video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1739                                                         
1740                                                         // Dual pass logging
1741                                                         if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1742                                                                 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1743                                                 } 
1744                                                 else if ( out_size < 0 )
1745                                                 {
1746                                                         mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1747                                                 }
1748                                         }
1749                                         frame_count++;
1750                                         if ( ret )
1751                                         {
1752                                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1753                                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1754                                                 goto on_fatal_error;
1755                                         }
1756                                         mlt_frame_close( frame );
1757                                         frame = NULL;
1758                                 }
1759                                 else
1760                                 {
1761                                         break;
1762                                 }
1763                         }
1764                         if ( audio_st[0] )
1765                                 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1766                         if ( video_st )
1767                                 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1768                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1769                 }
1770
1771                 if ( real_time_output == 1 && frames % 2 == 0 )
1772                 {
1773                         long passed = time_difference( &ante );
1774                         if ( fifo != NULL )
1775                         {
1776                                 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1777                                 passed -= pending;
1778                         }
1779                         if ( passed < total_time )
1780                         {
1781                                 long total = ( total_time - passed );
1782                                 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1783                                 nanosleep( &t, NULL );
1784                         }
1785                 }
1786         }
1787
1788         // Flush the encoder buffers
1789         if ( real_time_output <= 0 )
1790         {
1791                 // Flush audio fifo
1792                 // TODO: flush all audio streams
1793                 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1794                 {
1795                         AVCodecContext *c = audio_st[0]->codec;
1796                         AVPacket pkt;
1797                         av_init_packet( &pkt );
1798                         pkt.size = 0;
1799
1800                         if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1801                                 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1802                         {
1803                                 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size );
1804                                 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1805                         }
1806                         if ( pkt.size <= 0 )
1807                                 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1808                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1809                         if ( pkt.size <= 0 )
1810                                 break;
1811
1812                         // Write the compressed frame in the media file
1813                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1814                                 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1815                         pkt.flags |= PKT_FLAG_KEY;
1816                         pkt.stream_index = audio_st[0]->index;
1817                         pkt.data = audio_outbuf;
1818                         if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1819                         {
1820                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1821                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1822                                 goto on_fatal_error;
1823                         }
1824                 }
1825
1826                 // Flush video
1827                 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1828                 {
1829                         AVCodecContext *c = video_st->codec;
1830                         AVPacket pkt;
1831                         av_init_packet( &pkt );
1832
1833                         // Encode the image
1834                         pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1835                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1836                         if ( pkt.size <= 0 )
1837                                 break;
1838
1839                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1840                                 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1841                         if( c->coded_frame && c->coded_frame->key_frame )
1842                                 pkt.flags |= PKT_FLAG_KEY;
1843                         pkt.stream_index = video_st->index;
1844                         pkt.data = video_outbuf;
1845
1846                         // write the compressed frame in the media file
1847                         if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1848                         {
1849                                 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1850                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1851                                 goto on_fatal_error;
1852                         }
1853                         // Dual pass logging
1854                         if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1855                                 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1856                 }
1857         }
1858
1859 on_fatal_error:
1860         
1861         // Write the trailer, if any
1862         av_write_trailer( oc );
1863
1864         // close each codec
1865         if ( video_st )
1866                 close_video(oc, video_st);
1867         for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1868                 close_audio( oc, audio_st[i] );
1869
1870         // Free the streams
1871         for ( i = 0; i < oc->nb_streams; i++ )
1872                 av_freep( &oc->streams[i] );
1873
1874         // Close the output file
1875         if ( !( fmt->flags & AVFMT_NOFILE ) )
1876         {
1877 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1878                 if ( !mlt_properties_get_int( properties, "redirect" ) )
1879                         avio_close( oc->pb );
1880 #elif LIBAVFORMAT_VERSION_MAJOR >= 52
1881                 url_fclose( oc->pb );
1882 #else
1883                 url_fclose( &oc->pb );
1884 #endif
1885         }
1886
1887         // Clean up input and output frames
1888         if ( output )
1889                 av_free( output->data[0] );
1890         av_free( output );
1891         av_free( input->data[0] );
1892         av_free( input );
1893         av_free( video_outbuf );
1894         av_free( audio_buf_1 );
1895         av_free( audio_buf_2 );
1896
1897         // Free the stream
1898         av_free( oc );
1899
1900         // Just in case we terminated on pause
1901         mlt_properties_set_int( properties, "running", 0 );
1902
1903         mlt_consumer_stopped( consumer );
1904         mlt_properties_close( frame_meta_properties );
1905
1906         if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1907         {
1908                 // Remove the dual pass log file
1909                 if ( mlt_properties_get( properties, "_logfilename" ) )
1910                         remove( mlt_properties_get( properties, "_logfilename" ) );
1911
1912                 // Remove the x264 dual pass logs
1913                 char *cwd = getcwd( NULL, 0 );
1914                 const char *file = "x264_2pass.log";
1915                 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1916                 sprintf( full, "%s/%s", cwd, file );
1917                 remove( full );
1918                 free( full );
1919                 file = "x264_2pass.log.temp";
1920                 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1921                 sprintf( full, "%s/%s", cwd, file );
1922                 remove( full );
1923                 free( full );
1924                 file = "x264_2pass.log.mbtree";
1925                 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1926                 sprintf( full, "%s/%s", cwd, file );
1927                 remove( full );
1928                 free( full );
1929                 free( cwd );
1930                 remove( "x264_2pass.log.temp" );
1931         }
1932
1933         while ( ( frame = mlt_deque_pop_back( queue ) ) )
1934                 mlt_frame_close( frame );
1935
1936         return NULL;
1937 }
1938
1939 /** Close the consumer.
1940 */
1941
1942 static void consumer_close( mlt_consumer consumer )
1943 {
1944         // Stop the consumer
1945         mlt_consumer_stop( consumer );
1946
1947         // Close the parent
1948         mlt_consumer_close( consumer );
1949
1950         // Free the memory
1951         free( consumer );
1952 }