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