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