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