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