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