]> git.sesse.net Git - mlt/blob - src/modules/avformat/consumer_avformat.c
fix samples number calculation for 24 and 32 bit output
[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 #if LIBAVCODEC_VERSION_INT >= ((54<<16)+(59<<8)+0)
713                                 case AV_CODEC_ID_PCM_S24LE:
714                                 case AV_CODEC_ID_PCM_S24BE:
715                                 case AV_CODEC_ID_PCM_U24LE:
716                                 case AV_CODEC_ID_PCM_U24BE:
717                                         audio_input_frame_size /= 3;
718                                         break;
719                                 case AV_CODEC_ID_PCM_S32LE:
720                                 case AV_CODEC_ID_PCM_S32BE:
721                                 case AV_CODEC_ID_PCM_U32LE:
722                                 case AV_CODEC_ID_PCM_U32BE:
723                                         audio_input_frame_size >>= 2;
724                                         break;
725 #endif
726                                 default:
727                                         break;
728                         }
729                 } 
730                 else 
731                 {
732                         audio_input_frame_size = c->frame_size;
733                 }
734
735                 // Some formats want stream headers to be seperate (hmm)
736                 if ( !strcmp( oc->oformat->name, "mp4" ) ||
737                          !strcmp( oc->oformat->name, "mov" ) ||
738                          !strcmp( oc->oformat->name, "3gp" ) )
739                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
740         }
741         else
742         {
743                 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
744                 audio_input_frame_size = 0;
745         }
746
747         return audio_input_frame_size;
748 }
749
750 static void close_audio( AVFormatContext *oc, AVStream *st )
751 {
752         if ( st && st->codec )
753                 avcodec_close( st->codec );
754 }
755
756 /** Add a video output stream 
757 */
758
759 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
760 {
761         // Get the properties
762         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
763
764         // Create a new stream
765 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
766         AVStream *st = avformat_new_stream( oc, codec );
767 #else
768         AVStream *st = av_new_stream( oc, oc->nb_streams );
769 #endif
770
771         if ( st != NULL ) 
772         {
773                 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
774                 AVCodecContext *c = st->codec;
775
776                 // Establish defaults from AVOptions
777 #if LIBAVCODEC_VERSION_MAJOR >= 53
778                 avcodec_get_context_defaults3( c, codec );
779 #else
780                 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
781 #endif
782
783                 c->codec_id = codec->id;
784                 c->codec_type = CODEC_TYPE_VIDEO;
785                 
786                 // Setup multi-threading
787                 int thread_count = mlt_properties_get_int( properties, "threads" );
788                 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
789                         thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
790                 if ( thread_count > 1 )
791 #if LIBAVCODEC_VERSION_MAJOR >= 53
792                         c->thread_count = thread_count;
793 #else
794                         avcodec_thread_init( c, thread_count );
795 #endif
796
797                 // Process properties as AVOptions
798                 char *vpre = mlt_properties_get( properties, "vpre" );
799                 if ( vpre )
800                 {
801                         mlt_properties p = mlt_properties_load( vpre );
802 #ifdef AVDATADIR
803                         if ( mlt_properties_count( p ) < 1 )
804                         {
805                                 AVCodec *codec = avcodec_find_encoder( c->codec_id );
806                                 if ( codec )
807                                 {
808                                         char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
809                                         strcpy( path, AVDATADIR );
810                                         strcat( path, codec->name );
811                                         strcat( path, "-" );
812                                         strcat( path, vpre );
813                                         strcat( path, ".ffpreset" );
814                                         
815                                         mlt_properties_close( p );
816                                         p = mlt_properties_load( path );
817                                         if ( mlt_properties_count( p ) > 0 )
818                                                 mlt_properties_debug( p, path, stderr );
819                                         free( path );   
820                                 }
821                         }
822                         else
823                         {
824                                 mlt_properties_debug( p, vpre, stderr );                        
825                         }
826 #endif
827                         apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
828                         mlt_properties_close( p );
829                 }
830                 int colorspace = mlt_properties_get_int( properties, "colorspace" );
831                 mlt_properties_set( properties, "colorspace", NULL );
832                 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
833                 mlt_properties_set_int( properties, "colorspace", colorspace );
834
835                 // Set options controlled by MLT
836                 c->width = mlt_properties_get_int( properties, "width" );
837                 c->height = mlt_properties_get_int( properties, "height" );
838                 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
839                 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
840                 if ( st->time_base.den == 0 )
841                         st->time_base = c->time_base;
842                 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
843                 
844                 switch ( colorspace )
845                 {
846                 case 170:
847                         c->colorspace = AVCOL_SPC_SMPTE170M;
848                         break;
849                 case 240:
850                         c->colorspace = AVCOL_SPC_SMPTE240M;
851                         break;
852                 case 470:
853                         c->colorspace = AVCOL_SPC_BT470BG;
854                         break;
855                 case 601:
856                         c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
857                         break;
858                 case 709:
859                         c->colorspace = AVCOL_SPC_BT709;
860                         break;
861                 }
862
863                 if ( mlt_properties_get( properties, "aspect" ) )
864                 {
865                         // "-aspect" on ffmpeg command line is display aspect ratio
866                         double ar = mlt_properties_get_double( properties, "aspect" );
867                         c->sample_aspect_ratio = av_d2q( ar * c->height / c->width, 255 );
868                 }
869                 else
870                 {
871                         c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
872                         c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
873                 }
874                 st->sample_aspect_ratio = c->sample_aspect_ratio;
875
876                 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
877                 {
878                         c->flags |= CODEC_FLAG_QSCALE;
879                         c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
880 #if LIBAVFORMAT_VERSION_MAJOR < 53
881                         st->quality = c->global_quality;
882 #endif
883                 }
884
885                 // Allow the user to override the video fourcc
886                 if ( mlt_properties_get( properties, "vtag" ) )
887                 {
888                         char *tail = NULL;
889                         const char *arg = mlt_properties_get( properties, "vtag" );
890                         int tag = strtol( arg, &tail, 0);
891                         if( !tail || *tail )
892                                 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
893                         c->codec_tag = tag;
894                 }
895
896                 // Some formats want stream headers to be seperate
897                 if ( oc->oformat->flags & AVFMT_GLOBALHEADER ) 
898                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
899
900                 // Translate these standard mlt consumer properties to ffmpeg
901                 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
902                      mlt_properties_get_int( properties, "deinterlace" ) == 0 )
903                 {
904                         if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
905                                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
906                         if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
907                                 c->flags |= CODEC_FLAG_INTERLACED_ME;
908                 }
909                 
910                 // parse the ratecontrol override string
911                 int i;
912                 char *rc_override = mlt_properties_get( properties, "rc_override" );
913                 for ( i = 0; rc_override; i++ )
914                 {
915                         int start, end, q;
916                         int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
917                         if ( e != 3 )
918                                 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
919                         c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
920                         c->rc_override[i].start_frame = start;
921                         c->rc_override[i].end_frame = end;
922                         if ( q > 0 )
923                         {
924                                 c->rc_override[i].qscale = q;
925                                 c->rc_override[i].quality_factor = 1.0;
926                         }
927                         else
928                         {
929                                 c->rc_override[i].qscale = 0;
930                                 c->rc_override[i].quality_factor = -q / 100.0;
931                         }
932                         rc_override = strchr( rc_override, '/' );
933                         if ( rc_override )
934                                 rc_override++;
935                 }
936                 c->rc_override_count = i;
937                 if ( !c->rc_initial_buffer_occupancy )
938                         c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
939                 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
940
941                 // Setup dual-pass
942                 i = mlt_properties_get_int( properties, "pass" );
943                 if ( i == 1 )
944                         c->flags |= CODEC_FLAG_PASS1;
945                 else if ( i == 2 )
946                         c->flags |= CODEC_FLAG_PASS2;
947                 if ( codec->id != AV_CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
948                 {
949                         char logfilename[1024];
950                         FILE *f;
951                         int size;
952                         char *logbuffer;
953
954                         snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
955                                 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
956                         if ( c->flags & CODEC_FLAG_PASS1 )
957                         {
958                                 f = fopen( logfilename, "w" );
959                                 if ( !f )
960                                         perror( logfilename );
961                                 else
962                                         mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
963                         }
964                         else
965                         {
966                                 /* read the log file */
967                                 f = fopen( logfilename, "r" );
968                                 if ( !f )
969                                 {
970                                         perror(logfilename);
971                                 }
972                                 else
973                                 {
974                                         mlt_properties_set( properties, "_logfilename", logfilename );
975                                         fseek( f, 0, SEEK_END );
976                                         size = ftell( f );
977                                         fseek( f, 0, SEEK_SET );
978                                         logbuffer = av_malloc( size + 1 );
979                                         if ( !logbuffer )
980                                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
981                                         else
982                                         {
983                                                 if ( size >= 0 )
984                                                 {
985                                                         size = fread( logbuffer, 1, size, f );
986                                                         logbuffer[size] = '\0';
987                                                         c->stats_in = logbuffer;
988                                                 }
989                                         }
990                                         fclose( f );
991                                 }
992                         }
993                 }
994         }
995         else
996         {
997                 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
998         }
999  
1000         return st;
1001 }
1002
1003 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
1004 {
1005         // Allocate a frame
1006         AVFrame *picture = avcodec_alloc_frame();
1007
1008         // Determine size of the 
1009         int size = avpicture_get_size(pix_fmt, width, height);
1010
1011         // Allocate the picture buf
1012         uint8_t *picture_buf = av_malloc(size);
1013
1014         // If we have both, then fill the image
1015         if ( picture != NULL && picture_buf != NULL )
1016         {
1017                 // Fill the frame with the allocated buffer
1018                 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
1019         }
1020         else
1021         {
1022                 // Something failed - clean up what we can
1023                 av_free( picture );
1024                 av_free( picture_buf );
1025                 picture = NULL;
1026         }
1027
1028         return picture;
1029 }
1030
1031 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
1032 {
1033         // Get the codec
1034         AVCodecContext *video_enc = st->codec;
1035
1036         // find the video encoder
1037         AVCodec *codec;
1038         if ( codec_name )
1039                 codec = avcodec_find_encoder_by_name( codec_name );
1040         else
1041                 codec = avcodec_find_encoder( video_enc->codec_id );
1042
1043         // Process properties as AVOptions on the AVCodec
1044         if ( codec && codec->priv_class )
1045         {
1046                 char *vpre = mlt_properties_get( properties, "vpre" );
1047                 if ( !video_enc->priv_data && codec->priv_data_size )
1048                 {
1049                         video_enc->priv_data = av_mallocz( codec->priv_data_size );
1050                         *(const AVClass **) video_enc->priv_data = codec->priv_class;
1051 //                      av_opt_set_defaults( video_enc );
1052                 }
1053                 if ( vpre )
1054                 {
1055                         mlt_properties p = mlt_properties_load( vpre );
1056                         apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1057                         mlt_properties_close( p );
1058                 }
1059                 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1060         }
1061
1062         if( codec && codec->pix_fmts )
1063         {
1064                 const enum PixelFormat *p = codec->pix_fmts;
1065                 for( ; *p!=-1; p++ )
1066                 {
1067                         if( *p == video_enc->pix_fmt )
1068                                 break;
1069                 }
1070                 if( *p == -1 )
1071                         video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1072         }
1073
1074 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1075         int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1076 #else
1077         int result = codec && avcodec_open( video_enc, codec ) >= 0;
1078 #endif
1079         
1080         return result;
1081 }
1082
1083 void close_video(AVFormatContext *oc, AVStream *st)
1084 {
1085         if ( st && st->codec )
1086         {
1087                 av_freep( &st->codec->stats_in );
1088                 avcodec_close(st->codec);
1089         }
1090 }
1091
1092 static inline long time_difference( struct timeval *time1 )
1093 {
1094         struct timeval time2;
1095         gettimeofday( &time2, NULL );
1096         return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1097 }
1098
1099 static int mlt_write(void *h, uint8_t *buf, int size)
1100 {
1101         mlt_properties properties = (mlt_properties) h;
1102         mlt_events_fire( properties, "avformat-write", buf, &size, NULL );
1103         return 0;
1104 }
1105
1106 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1107 {
1108         int *p_size = (int*) args[1];
1109         listener( owner, service, (uint8_t*) args[0], *p_size );
1110 }
1111
1112 /** The main thread - the argument is simply the consumer.
1113 */
1114
1115 static void *consumer_thread( void *arg )
1116 {
1117         // Map the argument to the object
1118         mlt_consumer consumer = arg;
1119
1120         // Get the properties
1121         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1122
1123         // Get the terminate on pause property
1124         int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1125         int terminated = 0;
1126
1127         // Determine if feed is slow (for realtime stuff)
1128         int real_time_output = mlt_properties_get_int( properties, "real_time" );
1129
1130         // Time structures
1131         struct timeval ante;
1132
1133         // Get the frame rate
1134         double fps = mlt_properties_get_double( properties, "fps" );
1135
1136         // Get width and height
1137         int width = mlt_properties_get_int( properties, "width" );
1138         int height = mlt_properties_get_int( properties, "height" );
1139         int img_width = width;
1140         int img_height = height;
1141
1142         // Get default audio properties
1143         int channels = mlt_properties_get_int( properties, "channels" );
1144         int total_channels = channels;
1145         int frequency = mlt_properties_get_int( properties, "frequency" );
1146         void *pcm = NULL;
1147         int samples = 0;
1148
1149         // AVFormat audio buffer and frame size
1150         int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1151         uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1152         int audio_input_nb_samples = 0;
1153
1154         // AVFormat video buffer and frame count
1155         int frame_count = 0;
1156         int video_outbuf_size = VIDEO_BUFFER_SIZE;
1157         uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1158
1159         // Used for the frame properties
1160         mlt_frame frame = NULL;
1161         mlt_properties frame_properties = NULL;
1162
1163         // Get the queues
1164         mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1165         sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1166
1167         // For receiving images from an mlt_frame
1168         uint8_t *image;
1169         mlt_image_format img_fmt = mlt_image_yuv422;
1170         // Get the image format to use for rendering threads
1171         const char* img_fmt_name = mlt_properties_get( properties, "mlt_image_format" );
1172         if ( img_fmt_name )
1173         {
1174                 if ( !strcmp( img_fmt_name, "rgb24" ) )
1175                         img_fmt = mlt_image_rgb24;
1176                 else if ( !strcmp( img_fmt_name, "rgb24a" ) )
1177                         img_fmt = mlt_image_rgb24a;
1178                 else if ( !strcmp( img_fmt_name, "yuv420p" ) )
1179                         img_fmt = mlt_image_yuv420p;
1180         }
1181         else if ( mlt_properties_get( properties, "pix_fmt" ) )
1182         {
1183                 img_fmt_name = mlt_properties_get( properties, "pix_fmt" );
1184                 if ( !strcmp( img_fmt_name, "rgba" ) ||
1185                      !strcmp( img_fmt_name, "argb" ) ||
1186                      !strcmp( img_fmt_name, "bgra" ) )
1187                         img_fmt = mlt_image_rgb24a;
1188         }
1189
1190         // Need two av pictures for converting
1191         AVFrame *converted_avframe = NULL;
1192         AVFrame *audio_avframe = NULL;
1193         AVFrame *video_avframe = alloc_picture( pick_pix_fmt( img_fmt ), width, height );
1194
1195         // For receiving audio samples back from the fifo
1196         uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1197         uint8_t *audio_buf_2 = NULL;
1198         int count = 0;
1199
1200         // Allocate the context
1201         AVFormatContext *oc = NULL;
1202
1203         // Streams
1204         AVStream *video_st = NULL;
1205         AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1206
1207         // Time stamps
1208         double audio_pts = 0;
1209         double video_pts = 0;
1210
1211         // Frames dispatched
1212         long int frames = 0;
1213         long int total_time = 0;
1214
1215         // Determine the format
1216         AVOutputFormat *fmt = NULL;
1217         const char *filename = mlt_properties_get( properties, "target" );
1218         char *format = mlt_properties_get( properties, "f" );
1219         char *vcodec = mlt_properties_get( properties, "vcodec" );
1220         char *acodec = mlt_properties_get( properties, "acodec" );
1221         AVCodec *audio_codec = NULL;
1222         AVCodec *video_codec = NULL;
1223         
1224         // Used to store and override codec ids
1225         int audio_codec_id;
1226         int video_codec_id;
1227
1228         // Misc
1229         char key[27];
1230         mlt_properties frame_meta_properties = mlt_properties_new();
1231         int error_count = 0;
1232         int64_t synth_audio_pts = 0;
1233
1234         // Initialize audio_st
1235         int i = MAX_AUDIO_STREAMS;
1236         while ( i-- )
1237                 audio_st[i] = NULL;
1238
1239         // Check for user selected format first
1240         if ( format != NULL )
1241                 fmt = av_guess_format( format, NULL, NULL );
1242
1243         // Otherwise check on the filename
1244         if ( fmt == NULL && filename != NULL )
1245                 fmt = av_guess_format( NULL, filename, NULL );
1246
1247         // Otherwise default to mpeg
1248         if ( fmt == NULL )
1249                 fmt = av_guess_format( "mpeg", NULL, NULL );
1250
1251         // We need a filename - default to stdout?
1252         if ( filename == NULL || !strcmp( filename, "" ) )
1253                 filename = "pipe:";
1254
1255 #if defined(FFUDIV) && LIBAVUTIL_VERSION_INT >= ((53<<16)+(2<<8)+0)
1256         avformat_alloc_output_context2( &oc, fmt, format, filename );
1257 #else
1258         oc = avformat_alloc_context( );
1259         oc->oformat = fmt;
1260         snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1261
1262         if ( oc->oformat && oc->oformat->priv_class && !oc->priv_data && oc->oformat->priv_data_size ) {
1263                 oc->priv_data = av_mallocz( oc->oformat->priv_data_size );
1264                 if ( oc->priv_data ) {
1265                         *(const AVClass**)oc->priv_data = oc->oformat->priv_class;
1266                         av_opt_set_defaults( oc->priv_data );
1267                 }
1268         }
1269 #endif
1270
1271         // Get the codec ids selected
1272         audio_codec_id = fmt->audio_codec;
1273         video_codec_id = fmt->video_codec;
1274
1275         // Check for audio codec overides
1276         if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1277                 audio_codec_id = AV_CODEC_ID_NONE;
1278         else if ( acodec )
1279         {
1280                 audio_codec = avcodec_find_encoder_by_name( acodec );
1281                 if ( audio_codec )
1282                 {
1283                         audio_codec_id = audio_codec->id;
1284                         if ( audio_codec_id == AV_CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1285                         {
1286                                 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1287                                 acodec = mlt_properties_get( properties, "_acodec" );
1288                                 audio_codec = avcodec_find_encoder_by_name( acodec );
1289                         }
1290                         else if ( !strcmp( acodec, "aac" ) || !strcmp( acodec, "vorbis" ) )
1291                         {
1292                                 mlt_properties_set( properties, "astrict", "experimental" );
1293                         }
1294                 }
1295                 else
1296                 {
1297                         audio_codec_id = AV_CODEC_ID_NONE;
1298                         mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1299                 }
1300         }
1301         else
1302         {
1303                 audio_codec = avcodec_find_encoder( audio_codec_id );
1304         }
1305
1306         // Check for video codec overides
1307         if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1308                 video_codec_id = AV_CODEC_ID_NONE;
1309         else if ( vcodec )
1310         {
1311                 video_codec = avcodec_find_encoder_by_name( vcodec );
1312                 if ( video_codec )
1313                 {
1314                         video_codec_id = video_codec->id;
1315                 }
1316                 else
1317                 {
1318                         video_codec_id = AV_CODEC_ID_NONE;
1319                         mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1320                 }
1321         }
1322         else
1323         {
1324                 video_codec = avcodec_find_encoder( video_codec_id );
1325         }
1326
1327         // Write metadata
1328         for ( i = 0; i < mlt_properties_count( properties ); i++ )
1329         {
1330                 char *name = mlt_properties_get_name( properties, i );
1331                 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1332                 {
1333                         char *key = strdup( name + 10 );
1334                         char *markup = strrchr( key, '.' );
1335                         if ( markup && !strcmp( markup, ".markup") )
1336                         {
1337                                 markup[0] = '\0';
1338                                 if ( !strstr( key, ".stream." ) )
1339 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1340                                         av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1341 #else
1342                                         av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1343 #endif
1344                         }
1345                         free( key );
1346                 }
1347         }
1348
1349         // Get a frame now, so we can set some AVOptions from properties.
1350         frame = mlt_consumer_rt_frame( consumer );
1351
1352         // Set the timecode from the MLT metadata if available.
1353     if ( frame )
1354     {
1355         const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1356         if ( timecode && strcmp( timecode, "" ) )
1357         {
1358             mlt_properties_set( properties, "timecode", timecode );
1359             if ( strchr( timecode, ';' ) )
1360                 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1361         }
1362     }
1363
1364         // Add audio and video streams
1365         if ( video_codec_id != AV_CODEC_ID_NONE )
1366                 video_st = add_video_stream( consumer, oc, video_codec );
1367         if ( audio_codec_id != AV_CODEC_ID_NONE )
1368         {
1369                 int is_multi = 0;
1370
1371                 total_channels = 0;
1372                 // multitrack audio
1373                 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1374                 {
1375                         sprintf( key, "channels.%d", i );
1376                         int j = mlt_properties_get_int( properties, key );
1377                         if ( j )
1378                         {
1379                                 is_multi = 1;
1380                                 total_channels += j;
1381                                 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1382                         }
1383                 }
1384                 // single track
1385                 if ( !is_multi )
1386                 {
1387                         audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1388                         total_channels = channels;
1389                 }
1390         }
1391         mlt_properties_set_int( properties, "channels", total_channels );
1392
1393         // Audio format is determined when adding the audio stream
1394         mlt_audio_format aud_fmt = mlt_audio_none;
1395         if ( audio_st[0] )
1396                 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1397         int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1398         sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1399
1400         // Set the parameters (even though we have none...)
1401 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1402         if ( av_set_parameters(oc, NULL) >= 0 )
1403 #endif
1404         {
1405 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1406                 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1407                         mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1408 #else
1409                 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1410 #endif
1411                 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1412
1413                 // Process properties as AVOptions
1414                 char *fpre = mlt_properties_get( properties, "fpre" );
1415                 if ( fpre )
1416                 {
1417                         mlt_properties p = mlt_properties_load( fpre );
1418                         apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1419                         if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1420                                 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1421                         mlt_properties_close( p );
1422                 }
1423                 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1424                 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1425                         apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1426
1427                 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1428                         video_st = NULL;
1429                 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1430                 {
1431                         audio_input_nb_samples = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1432                                 acodec? acodec : NULL );
1433                         if ( !audio_input_nb_samples )
1434                         {
1435                                 // Remove the audio stream from the output context
1436                                 int j;
1437                                 for ( j = 0; j < oc->nb_streams; j++ )
1438                                 {
1439                                         if ( oc->streams[j] == audio_st[i] )
1440                                                 av_freep( &oc->streams[j] );
1441                                 }
1442                                 --oc->nb_streams;
1443                                 audio_st[i] = NULL;
1444                         }
1445                 }
1446
1447                 // Setup custom I/O if redirecting
1448                 if ( mlt_properties_get_int( properties, "redirect" ) )
1449                 {
1450                         int buffer_size = 32768;
1451                         unsigned char *buffer = av_malloc( buffer_size );
1452 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1453                         AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1454 #else
1455                         ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1456 #endif
1457                         if ( buffer && io )
1458                         {
1459                                 oc->pb = io;
1460 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1461                                 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1462 #endif
1463                                 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1464                                 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1465                                 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1466                         }
1467                         else
1468                         {
1469                                 av_free( buffer );
1470                                 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1471                         }
1472                 }
1473                 // Open the output file, if needed
1474                 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1475                 {
1476 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1477                         if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1478 #else
1479                         if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1480 #endif
1481                         {
1482                                 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1483                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1484                                 goto on_fatal_error;
1485                         }
1486                 }
1487         
1488                 // Write the stream header.
1489                 if ( mlt_properties_get_int( properties, "running" ) )
1490 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1491                         if ( avformat_write_header( oc, NULL ) < 0 )
1492 #else
1493                         if ( av_write_header( oc ) < 0 )
1494 #endif
1495                         {
1496                                 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not write header '%s'\n", filename );
1497                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1498                                 goto on_fatal_error;
1499                         }
1500         }
1501 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1502         else
1503         {
1504                 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1505                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1506                 goto on_fatal_error;
1507         }
1508 #endif
1509
1510         // Last check - need at least one stream
1511         if ( !audio_st[0] && !video_st )
1512         {
1513                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1514                 goto on_fatal_error;
1515         }
1516
1517         // Allocate picture
1518         if ( video_st )
1519                 converted_avframe = alloc_picture( video_st->codec->pix_fmt, width, height );
1520
1521 #if LIBAVCODEC_VERSION_MAJOR >= 54
1522         // Allocate audio AVFrame
1523         if ( audio_st[0] )
1524         {
1525                 audio_avframe = avcodec_alloc_frame();
1526                 if ( audio_avframe ) {
1527                         AVCodecContext *c = audio_st[0]->codec;
1528                         audio_avframe->format = c->sample_fmt;
1529                         audio_avframe->nb_samples = audio_input_nb_samples;
1530                         audio_avframe->channel_layout = c->channel_layout;
1531                 } else {
1532                         mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to allocate audio AVFrame\n" );
1533                         mlt_events_fire( properties, "consumer-fatal-error", NULL );
1534                         goto on_fatal_error;
1535                 }
1536         }
1537 #endif
1538
1539         // Get the starting time (can ignore the times above)
1540         gettimeofday( &ante, NULL );
1541
1542         // Loop while running
1543         while( mlt_properties_get_int( properties, "running" ) &&
1544                ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1545         {
1546                 if ( !frame )
1547                         frame = mlt_consumer_rt_frame( consumer );
1548
1549                 // Check that we have a frame to work with
1550                 if ( frame != NULL )
1551                 {
1552                         // Increment frames dispatched
1553                         frames ++;
1554
1555                         // Default audio args
1556                         frame_properties = MLT_FRAME_PROPERTIES( frame );
1557
1558                         // Check for the terminated condition
1559                         terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1560
1561                         // Get audio and append to the fifo
1562                         if ( !terminated && audio_st[0] )
1563                         {
1564                                 samples = mlt_sample_calculator( fps, frequency, count ++ );
1565                                 channels = total_channels;
1566                                 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1567
1568                                 // Save the audio channel remap properties for later
1569                                 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1570
1571                                 // Create the fifo if we don't have one
1572                                 if ( fifo == NULL )
1573                                 {
1574                                         fifo = sample_fifo_init( frequency, channels );
1575                                         mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1576                                 }
1577                                 if ( pcm )
1578                                 {
1579                                         // Silence if not normal forward speed
1580                                         if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1581                                                 memset( pcm, 0, samples * channels * sample_bytes );
1582
1583                                         // Append the samples
1584                                         sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1585                                         total_time += ( samples * 1000000 ) / frequency;
1586                                 }
1587                                 if ( !video_st )
1588                                         mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1589                         }
1590
1591                         // Encode the image
1592                         if ( !terminated && video_st )
1593                                 mlt_deque_push_back( queue, frame );
1594                         else
1595                                 mlt_frame_close( frame );
1596                         frame = NULL;
1597                 }
1598
1599                 // While we have stuff to process, process...
1600                 while ( 1 )
1601                 {
1602                         // Write interleaved audio and video frames
1603                         if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1604                         {
1605                                 // Write audio
1606                                 if ( ( video_st && terminated ) || ( channels * audio_input_nb_samples ) < sample_fifo_used( fifo ) / sample_bytes )
1607                                 {
1608                                         int j = 0; // channel offset into interleaved source buffer
1609                                         int n = FFMIN( FFMIN( channels * audio_input_nb_samples, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1610
1611                                         // Get the audio samples
1612                                         if ( n > 0 )
1613                                         {
1614                                                 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1615                                         }
1616                                         else if ( audio_codec_id == AV_CODEC_ID_VORBIS && terminated )
1617                                         {
1618                                                 // This prevents an infinite loop when some versions of vorbis do not
1619                                                 // increment pts when encoding silence.
1620                                                 audio_pts = video_pts;
1621                                                 break;
1622                                         }
1623                                         else
1624                                         {
1625                                                 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1626                                         }
1627                                         samples = n / channels;
1628
1629                                         // For each output stream
1630                                         for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1631                                         {
1632                                                 AVStream *stream = audio_st[i];
1633                                                 AVCodecContext *codec = stream->codec;
1634                                                 AVPacket pkt;
1635
1636                                                 av_init_packet( &pkt );
1637                                                 pkt.data = audio_outbuf;
1638                                                 pkt.size = audio_outbuf_size;
1639
1640                                                 // Optimized for single track and no channel remap
1641                                                 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1642                                                 {
1643                                                         void* p = audio_buf_1;
1644 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1645                                                         if ( codec->sample_fmt == AV_SAMPLE_FMT_FLTP )
1646                                                                 p = interleaved_to_planar( samples, channels, p, sizeof( float ) );
1647                                                         else if ( codec->sample_fmt == AV_SAMPLE_FMT_S16P )
1648                                                                 p = interleaved_to_planar( samples, channels, p, sizeof( int16_t ) );
1649                                                         else if ( codec->sample_fmt == AV_SAMPLE_FMT_S32P )
1650                                                                 p = interleaved_to_planar( samples, channels, p, sizeof( int32_t ) );
1651                                                         else if ( codec->sample_fmt == AV_SAMPLE_FMT_U8P )
1652                                                                 p = interleaved_to_planar( samples, channels, p, sizeof( uint8_t ) );
1653 #endif
1654 #if LIBAVCODEC_VERSION_MAJOR >= 54
1655                                                         audio_avframe->nb_samples = FFMAX( samples, audio_input_nb_samples );
1656 #if LIBAVCODEC_VERSION_MAJOR >= 55
1657                                                         if ( audio_codec_id == AV_CODEC_ID_VORBIS )
1658                                                                 audio_avframe->pts = synth_audio_pts;
1659                                                         synth_audio_pts += audio_avframe->nb_samples;
1660 #endif
1661                                                         avcodec_fill_audio_frame( audio_avframe, codec->channels, codec->sample_fmt,
1662                                                                 (const uint8_t*) p, AUDIO_ENCODE_BUFFER_SIZE, 0 );
1663                                                         int got_packet = 0;
1664                                                         int ret = avcodec_encode_audio2( codec, &pkt, audio_avframe, &got_packet );
1665                                                         if ( ret < 0 )
1666                                                                 pkt.size = ret;
1667                                                         else if ( !got_packet )
1668                                                                 pkt.size = 0;
1669 #else
1670                                                         codec->frame_size = FFMAX( samples, audio_input_nb_samples );
1671                                                         pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, p );
1672                                                         pkt.pts = codec->coded_frame? codec->coded_frame->pts : AV_NOPTS_VALUE;
1673                                                         pkt.flags |= PKT_FLAG_KEY;
1674 #endif
1675
1676 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1677                                                         if ( p != audio_buf_1 )
1678                                                                 mlt_pool_release( p );
1679 #endif
1680                                                 }
1681                                                 else
1682                                                 {
1683                                                         // Extract the audio channels according to channel mapping
1684                                                         int dest_offset = 0; // channel offset into interleaved dest buffer
1685
1686                                                         // Get the number of channels for this stream
1687                                                         sprintf( key, "channels.%d", i );
1688                                                         int current_channels = mlt_properties_get_int( properties, key );
1689
1690                                                         // Clear the destination audio buffer.
1691                                                         if ( !audio_buf_2 )
1692                                                                 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1693                                                         else
1694                                                                 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1695
1696                                                         // For each output channel
1697                                                         while ( dest_offset < current_channels && j < total_channels )
1698                                                         {
1699                                                                 int map_start = -1, map_channels = 0;
1700                                                                 int source_offset = 0;
1701                                                                 int k;
1702
1703                                                                 // Look for a mapping that starts at j
1704                                                                 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1705                                                                 {
1706                                                                         sprintf( key, "%d.channels", k );
1707                                                                         map_channels = mlt_properties_get_int( frame_meta_properties, key );
1708                                                                         sprintf( key, "%d.start", k );
1709                                                                         if ( mlt_properties_get( frame_meta_properties, key ) )
1710                                                                                 map_start = mlt_properties_get_int( frame_meta_properties, key );
1711                                                                         if ( map_start != j )
1712                                                                                 source_offset += map_channels;
1713                                                                 }
1714
1715                                                                 // If no mapping
1716                                                                 if ( map_start != j )
1717                                                                 {
1718                                                                         map_channels = current_channels;
1719                                                                         source_offset = j;
1720                                                                 }
1721
1722                                                                 // Copy samples if source offset valid
1723                                                                 if ( source_offset < channels )
1724                                                                 {
1725                                                                         // Interleave the audio buffer with the # channels for this stream/mapping.
1726                                                                         for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1727                                                                         {
1728                                                                                 void *src = audio_buf_1 + source_offset * sample_bytes;
1729                                                                                 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1730                                                                                 int s = samples + 1;
1731
1732                                                                                 while ( --s ) {
1733                                                                                         memcpy( dest, src, sample_bytes );
1734                                                                                         dest += current_channels * sample_bytes;
1735                                                                                         src += channels * sample_bytes;
1736                                                                                 }
1737                                                                         }
1738                                                                 }
1739                                                                 // Otherwise silence
1740                                                                 else
1741                                                                 {
1742                                                                         j += current_channels;
1743                                                                         dest_offset += current_channels;
1744                                                                 }
1745                                                         }
1746 #if LIBAVCODEC_VERSION_MAJOR >= 54
1747                                                         audio_avframe->nb_samples = FFMAX( samples, audio_input_nb_samples );
1748 #if LIBAVCODEC_VERSION_MAJOR >= 55
1749                                                         if ( audio_codec_id == AV_CODEC_ID_VORBIS )
1750                                                                 audio_avframe->pts = synth_audio_pts;
1751                                                         synth_audio_pts += audio_avframe->nb_samples;
1752 #endif
1753                                                         avcodec_fill_audio_frame( audio_avframe, codec->channels, codec->sample_fmt,
1754                                                                 (const uint8_t*) audio_buf_2, AUDIO_ENCODE_BUFFER_SIZE, 0 );
1755                                                         int got_packet = 0;
1756                                                         int ret = avcodec_encode_audio2( codec, &pkt, audio_avframe, &got_packet );
1757                                                         if ( ret < 0 )
1758                                                                 pkt.size = ret;
1759                                                         else if ( !got_packet )
1760                                                                 pkt.size = 0;
1761 #else
1762                                                         codec->frame_size = FFMAX( samples, audio_input_nb_samples );
1763                                                         pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1764                                                         pkt.pts = codec->coded_frame? codec->coded_frame->pts : AV_NOPTS_VALUE;
1765                                                         pkt.flags |= PKT_FLAG_KEY;
1766 #endif
1767                                                 }
1768
1769                                                 if ( pkt.size > 0 )
1770                                                 {
1771                                                         // Write the compressed frame in the media file
1772                                                         if ( pkt.pts != AV_NOPTS_VALUE )
1773                                                                 pkt.pts = av_rescale_q( pkt.pts, codec->time_base, stream->time_base );
1774 #if LIBAVCODEC_VERSION_MAJOR >= 55
1775                                                         if ( pkt.dts != AV_NOPTS_VALUE )
1776                                                                 pkt.dts = av_rescale_q( pkt.dts, codec->time_base, stream->time_base );
1777                                                         if ( pkt.duration > 0 )
1778                                                                 pkt.duration = av_rescale_q( pkt.duration, codec->time_base, stream->time_base );
1779 #endif
1780                                                         pkt.stream_index = stream->index;
1781                                                         if ( av_interleaved_write_frame( oc, &pkt ) )
1782                                                         {
1783                                                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1784                                                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1785                                                                 goto on_fatal_error;
1786                                                         }
1787                                                         error_count = 0;
1788                                                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame_size %d stream pts %"PRId64"\n",
1789                                                                 stream->index, pkt.pts, codec->frame_size, stream->pts.val );
1790                                                 }
1791                                                 else if ( pkt.size < 0 )
1792                                                 {
1793                                                         mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with audio encode %d\n", frame_count );
1794                                                         if ( ++error_count > 2 )
1795                                                                 goto on_fatal_error;
1796                                                 }
1797
1798                                                 if ( i == 0 )
1799                                                 {
1800                                                         audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1801                                                 }
1802                                         }
1803                                 }
1804                                 else
1805                                 {
1806                                         break;
1807                                 }
1808                         }
1809                         else if ( video_st )
1810                         {
1811                                 // Write video
1812                                 if ( mlt_deque_count( queue ) )
1813                                 {
1814                                         int ret = 0;
1815                                         AVCodecContext *c = video_st->codec;
1816
1817                                         frame = mlt_deque_pop_front( queue );
1818                                         frame_properties = MLT_FRAME_PROPERTIES( frame );
1819
1820                                         if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1821                                         {
1822                                                 int i = 0;
1823                                                 uint8_t *p;
1824                                                 uint8_t *q;
1825                                                 int stride = mlt_image_format_size( img_fmt, width, 0, NULL );
1826
1827                                                 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1828                                                 q = image;
1829
1830                                                 // Convert the mlt frame to an AVPicture
1831                                                 if ( img_fmt == mlt_image_yuv420p )
1832                                                 {
1833                                                         memcpy( video_avframe->data[0], q, video_avframe->linesize[0] );
1834                                                         q += stride;
1835                                                         memcpy( video_avframe->data[1], q, video_avframe->linesize[1] );
1836                                                         q += stride / 4;
1837                                                         memcpy( video_avframe->data[2], q, video_avframe->linesize[2] );
1838                                                 }
1839                                                 else for ( i = 0; i < height; i ++ )
1840                                                 {
1841                                                         p = video_avframe->data[0] + i * video_avframe->linesize[0];
1842                                                         memcpy( p, q, stride );
1843                                                         q += stride;
1844                                                 }
1845
1846                                                 // Do the colour space conversion
1847                                                 int flags = SWS_BICUBIC;
1848 #ifdef USE_MMX
1849                                                 flags |= SWS_CPU_CAPS_MMX;
1850 #endif
1851 #ifdef USE_SSE
1852                                                 flags |= SWS_CPU_CAPS_MMX2;
1853 #endif
1854                                                 struct SwsContext *context = sws_getContext( width, height, pick_pix_fmt( img_fmt ),
1855                                                         width, height, c->pix_fmt, flags, NULL, NULL, NULL);
1856                                                 sws_scale( context, (const uint8_t* const*) video_avframe->data, video_avframe->linesize, 0, height,
1857                                                         converted_avframe->data, converted_avframe->linesize);
1858                                                 sws_freeContext( context );
1859
1860                                                 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1861
1862                                                 // Apply the alpha if applicable
1863                                                 if ( !mlt_properties_get( properties, "mlt_image_format" ) ||
1864                                                      strcmp( mlt_properties_get( properties, "mlt_image_format" ), "rgb24a" ) )
1865                                                 if ( c->pix_fmt == PIX_FMT_RGBA ||
1866                                                      c->pix_fmt == PIX_FMT_ARGB ||
1867                                                      c->pix_fmt == PIX_FMT_BGRA )
1868                                                 {
1869                                                         uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1870                                                         register int n;
1871
1872                                                         for ( i = 0; i < height; i ++ )
1873                                                         {
1874                                                                 n = ( width + 7 ) / 8;
1875                                                                 p = converted_avframe->data[ 0 ] + i * converted_avframe->linesize[ 0 ] + 3;
1876
1877                                                                 switch( width % 8 )
1878                                                                 {
1879                                                                         case 0: do { *p = *alpha++; p += 4;
1880                                                                         case 7:          *p = *alpha++; p += 4;
1881                                                                         case 6:          *p = *alpha++; p += 4;
1882                                                                         case 5:          *p = *alpha++; p += 4;
1883                                                                         case 4:          *p = *alpha++; p += 4;
1884                                                                         case 3:          *p = *alpha++; p += 4;
1885                                                                         case 2:          *p = *alpha++; p += 4;
1886                                                                         case 1:          *p = *alpha++; p += 4;
1887                                                                                         }
1888                                                                                         while( --n );
1889                                                                 }
1890                                                         }
1891                                                 }
1892                                         }
1893
1894                                         if (oc->oformat->flags & AVFMT_RAWPICTURE) 
1895                                         {
1896                                                 // raw video case. The API will change slightly in the near future for that
1897                                                 AVPacket pkt;
1898                                                 av_init_packet(&pkt);
1899
1900                                                 // Set frame interlace hints
1901                                                 c->coded_frame->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1902                                                 c->coded_frame->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1903 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(61<<8)+100)
1904                                                 if ( mlt_properties_get_int( frame_properties, "progressive" ) )
1905                                                         c->field_order = AV_FIELD_PROGRESSIVE;
1906                                                 else
1907                                                         c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TT : AV_FIELD_BB;
1908 #endif
1909                                                 pkt.flags |= PKT_FLAG_KEY;
1910                                                 pkt.stream_index = video_st->index;
1911                                                 pkt.data = (uint8_t *)converted_avframe;
1912                                                 pkt.size = sizeof(AVPicture);
1913
1914                                                 ret = av_write_frame(oc, &pkt);
1915                                                 video_pts += c->frame_size;
1916                                         } 
1917                                         else 
1918                                         {
1919                                                 AVPacket pkt;
1920                                                 av_init_packet( &pkt );
1921                                                 if ( c->codec->id == AV_CODEC_ID_RAWVIDEO ) {
1922                                                         pkt.data = NULL;
1923                                                         pkt.size = 0;
1924                                                 } else {
1925                                                         pkt.data = video_outbuf;
1926                                                         pkt.size = video_outbuf_size;
1927                                                 }
1928
1929                                                 // Set the quality
1930                                                 converted_avframe->quality = c->global_quality;
1931                                                 converted_avframe->pts = frame_count;
1932
1933                                                 // Set frame interlace hints
1934                                                 converted_avframe->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1935                                                 converted_avframe->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1936 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(61<<8)+100)
1937                                                 if ( mlt_properties_get_int( frame_properties, "progressive" ) )
1938                                                         c->field_order = AV_FIELD_PROGRESSIVE;
1939                                                 else if ( c->codec_id == AV_CODEC_ID_MJPEG )
1940                                                         c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TT : AV_FIELD_BB;
1941                                                 else
1942                                                         c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TB : AV_FIELD_BT;
1943 #endif
1944
1945                                                 // Encode the image
1946 #if LIBAVCODEC_VERSION_MAJOR >= 55
1947                                                 int got_packet;
1948                                                 ret = avcodec_encode_video2( c, &pkt, converted_avframe, &got_packet );
1949                                                 if ( ret < 0 )
1950                                                         pkt.size = ret;
1951                                                 else if ( !got_packet )
1952                                                         pkt.size = 0;
1953 #else
1954                                                 pkt.size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, converted_avframe );
1955                                                 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
1956                                                 if ( c->coded_frame && c->coded_frame->key_frame )
1957                                                         pkt.flags |= PKT_FLAG_KEY;
1958 #endif
1959
1960                                                 // If zero size, it means the image was buffered
1961                                                 if ( pkt.size > 0 )
1962                                                 {
1963                                                         if ( pkt.pts != AV_NOPTS_VALUE )
1964                                                                 pkt.pts = av_rescale_q( pkt.pts, c->time_base, video_st->time_base );
1965 #if LIBAVCODEC_VERSION_MAJOR >= 55
1966                                                         if ( pkt.dts != AV_NOPTS_VALUE )
1967                                                                 pkt.dts = av_rescale_q( pkt.dts, c->time_base, video_st->time_base );
1968 #endif
1969                                                         pkt.stream_index = video_st->index;
1970
1971                                                         // write the compressed frame in the media file
1972                                                         ret = av_interleaved_write_frame(oc, &pkt);
1973                                                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1974                                                         video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1975                                                         
1976                                                         // Dual pass logging
1977                                                         if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1978                                                                 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1979
1980                                                         error_count = 0;
1981                                                 } 
1982                                                 else if ( pkt.size < 0 )
1983                                                 {
1984                                                         mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1985                                                         if ( ++error_count > 2 )
1986                                                                 goto on_fatal_error;
1987                                                         ret = 0;
1988                                                 }
1989                                         }
1990                                         frame_count++;
1991                                         if ( ret )
1992                                         {
1993                                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1994                                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1995                                                 goto on_fatal_error;
1996                                         }
1997                                         mlt_frame_close( frame );
1998                                         frame = NULL;
1999                                 }
2000                                 else
2001                                 {
2002                                         break;
2003                                 }
2004                         }
2005                         if ( audio_st[0] )
2006                                 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
2007                         if ( video_st )
2008                                 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
2009                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
2010                 }
2011
2012                 if ( real_time_output == 1 && frames % 2 == 0 )
2013                 {
2014                         long passed = time_difference( &ante );
2015                         if ( fifo != NULL )
2016                         {
2017                                 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
2018                                 passed -= pending;
2019                         }
2020                         if ( passed < total_time )
2021                         {
2022                                 long total = ( total_time - passed );
2023                                 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
2024                                 nanosleep( &t, NULL );
2025                         }
2026                 }
2027         }
2028
2029         // Flush the encoder buffers
2030         if ( real_time_output <= 0 )
2031         {
2032                 // Flush audio fifo
2033                 // TODO: flush all audio streams
2034                 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
2035                 {
2036                         AVCodecContext *c = audio_st[0]->codec;
2037                         AVPacket pkt;
2038                         av_init_packet( &pkt );
2039                         pkt.data = audio_outbuf;
2040                         pkt.size = 0;
2041
2042                         if ( fifo && sample_fifo_used( fifo ) > 0 )
2043                         {
2044                                 // Drain the MLT FIFO
2045                                 int samples = FFMIN( FFMIN( channels * audio_input_nb_samples, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
2046                                 sample_fifo_fetch( fifo, audio_buf_1, samples * sample_bytes );
2047                                 void* p = audio_buf_1;
2048 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2049                                 if ( c->sample_fmt == AV_SAMPLE_FMT_FLTP )
2050                                         p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( float ) );
2051                                 else if ( c->sample_fmt == AV_SAMPLE_FMT_S16P )
2052                                         p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( int16_t ) );
2053                                 else if ( c->sample_fmt == AV_SAMPLE_FMT_S32P )
2054                                         p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( int32_t ) );
2055                                 else if ( c->sample_fmt == AV_SAMPLE_FMT_U8P )
2056                                         p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( uint8_t ) );
2057 #endif
2058 #if LIBAVCODEC_VERSION_MAJOR >= 54
2059                                 pkt.size = audio_outbuf_size;
2060                                 audio_avframe->nb_samples = FFMAX( samples / channels, audio_input_nb_samples );
2061 #if LIBAVCODEC_VERSION_MAJOR >= 55
2062                                 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
2063                                         audio_avframe->pts = synth_audio_pts;
2064                                 synth_audio_pts += audio_avframe->nb_samples;
2065 #endif
2066                                 avcodec_fill_audio_frame( audio_avframe, c->channels, c->sample_fmt,
2067                                         (const uint8_t*) p, AUDIO_ENCODE_BUFFER_SIZE, 0 );
2068                                 int got_packet = 0;
2069                                 int ret = avcodec_encode_audio2( c, &pkt, audio_avframe, &got_packet );
2070                                 if ( ret < 0 )
2071                                         pkt.size = ret;
2072                                 else if ( !got_packet )
2073                                         pkt.size = 0;
2074 #else
2075                                 c->frame_size = FFMAX( samples / channels, audio_input_nb_samples );
2076                                 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, p );
2077 #endif
2078 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2079                                 if ( p != audio_buf_1 )
2080                                         mlt_pool_release( p );
2081 #endif
2082                                 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
2083                         }
2084                         else
2085                         {
2086                                 // Drain the codec
2087                                 if ( pkt.size <= 0 ) {
2088 #if LIBAVCODEC_VERSION_MAJOR >= 54
2089                                         pkt.size = audio_outbuf_size;
2090                                         int got_packet = 0;
2091                                         int ret = avcodec_encode_audio2( c, &pkt, NULL, &got_packet );
2092                                         if ( ret < 0 )
2093                                                 pkt.size = ret;
2094                                         else if ( !got_packet )
2095                                                 pkt.size = 0;
2096 #else
2097                                         pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
2098                                         pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
2099                                         pkt.flags |= PKT_FLAG_KEY;
2100 #endif
2101                                 }
2102                                 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
2103                                 if ( pkt.size <= 0 )
2104                                         break;
2105                         }
2106
2107                         // Write the compressed frame in the media file
2108                         if ( pkt.pts != AV_NOPTS_VALUE )
2109                                 pkt.pts = av_rescale_q( pkt.pts, c->time_base, audio_st[0]->time_base );
2110 #if LIBAVCODEC_VERSION_MAJOR >= 55
2111                         if ( pkt.dts != AV_NOPTS_VALUE )
2112                                 pkt.dts = av_rescale_q( pkt.dts, c->time_base, audio_st[0]->time_base );
2113                         if ( pkt.duration > 0 )
2114                                 pkt.duration = av_rescale_q( pkt.duration, c->time_base, audio_st[0]->time_base );
2115 #endif
2116                         pkt.stream_index = audio_st[0]->index;
2117                         if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
2118                         {
2119                                 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
2120                                 break;
2121                         }
2122                 }
2123
2124                 // Flush video
2125                 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
2126                 {
2127                         AVCodecContext *c = video_st->codec;
2128                         AVPacket pkt;
2129                         av_init_packet( &pkt );
2130                         if ( c->codec->id == AV_CODEC_ID_RAWVIDEO ) {
2131                                 pkt.data = NULL;
2132                                 pkt.size = 0;
2133                         } else {
2134                                 pkt.data = video_outbuf;
2135                                 pkt.size = video_outbuf_size;
2136                         }
2137
2138                         // Encode the image
2139 #if LIBAVCODEC_VERSION_MAJOR >= 55
2140                         int got_packet = 0;
2141                         int ret = avcodec_encode_video2( c, &pkt, NULL, &got_packet );
2142                         if ( ret < 0 )
2143                                 pkt.size = ret;
2144                         else if ( !got_packet )
2145                                 pkt.size = 0;
2146 #else
2147                         pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
2148                         pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
2149                         if( c->coded_frame && c->coded_frame->key_frame )
2150                                 pkt.flags |= PKT_FLAG_KEY;
2151 #endif
2152                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
2153                         if ( pkt.size <= 0 )
2154                                 break;
2155
2156                         if ( pkt.pts != AV_NOPTS_VALUE )
2157                                 pkt.pts = av_rescale_q( pkt.pts, c->time_base, video_st->time_base );
2158 #if LIBAVCODEC_VERSION_MAJOR >= 55
2159                         if ( pkt.dts != AV_NOPTS_VALUE )
2160                                 pkt.dts = av_rescale_q( pkt.dts, c->time_base, video_st->time_base );
2161 #endif
2162                         pkt.stream_index = video_st->index;
2163
2164                         // write the compressed frame in the media file
2165                         if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
2166                         {
2167                                 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
2168                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
2169                                 goto on_fatal_error;
2170                         }
2171                         // Dual pass logging
2172                         if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
2173                                 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
2174                 }
2175         }
2176
2177 on_fatal_error:
2178
2179         if ( frame )
2180                 mlt_frame_close( frame );
2181
2182         // Write the trailer, if any
2183         if ( frames )
2184                 av_write_trailer( oc );
2185
2186         // close each codec
2187         if ( video_st )
2188                 close_video(oc, video_st);
2189         for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
2190                 close_audio( oc, audio_st[i] );
2191
2192         // Free the streams
2193         for ( i = 0; i < oc->nb_streams; i++ )
2194                 av_freep( &oc->streams[i] );
2195
2196         // Close the output file
2197         if ( !( fmt->flags & AVFMT_NOFILE ) &&
2198                 !mlt_properties_get_int( properties, "redirect" ) )
2199         {
2200 #if LIBAVFORMAT_VERSION_MAJOR >= 53
2201                 if ( oc->pb  ) avio_close( oc->pb );
2202 #else
2203                 if ( oc->pb  ) url_fclose( oc->pb );
2204 #endif
2205         }
2206
2207         // Clean up input and output frames
2208         if ( converted_avframe )
2209                 av_free( converted_avframe->data[0] );
2210         av_free( converted_avframe );
2211         av_free( video_avframe->data[0] );
2212         av_free( video_avframe );
2213         av_free( video_outbuf );
2214         av_free( audio_avframe );
2215         av_free( audio_buf_1 );
2216         av_free( audio_buf_2 );
2217
2218         // Free the stream
2219         av_free( oc );
2220
2221         // Just in case we terminated on pause
2222         mlt_consumer_stopped( consumer );
2223         mlt_properties_close( frame_meta_properties );
2224
2225         if ( mlt_properties_get_int( properties, "pass" ) > 1 )
2226         {
2227                 // Remove the dual pass log file
2228                 if ( mlt_properties_get( properties, "_logfilename" ) )
2229                         remove( mlt_properties_get( properties, "_logfilename" ) );
2230
2231                 // Remove the x264 dual pass logs
2232                 char *cwd = getcwd( NULL, 0 );
2233                 const char *file = "x264_2pass.log";
2234                 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2235                 sprintf( full, "%s/%s", cwd, file );
2236                 remove( full );
2237                 free( full );
2238                 file = "x264_2pass.log.temp";
2239                 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2240                 sprintf( full, "%s/%s", cwd, file );
2241                 remove( full );
2242                 free( full );
2243                 file = "x264_2pass.log.mbtree";
2244                 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2245                 sprintf( full, "%s/%s", cwd, file );
2246                 remove( full );
2247                 free( full );
2248                 free( cwd );
2249                 remove( "x264_2pass.log.temp" );
2250
2251                 // Recent versions of libavcodec/x264 support passlogfile and need cleanup if specified.
2252                 if ( !mlt_properties_get( properties, "_logfilename" ) &&
2253                       mlt_properties_get( properties, "passlogfile" ) )
2254                 {
2255                         file = mlt_properties_get( properties, "passlogfile" );
2256                         remove( file );
2257                         full = malloc( strlen( file ) + strlen( ".mbtree" ) + 1 );
2258                         sprintf( full, "%s.mbtree", file );
2259                         remove( full );
2260                         free( full );
2261                 }
2262         }
2263
2264         while ( ( frame = mlt_deque_pop_back( queue ) ) )
2265                 mlt_frame_close( frame );
2266
2267         return NULL;
2268 }
2269
2270 /** Close the consumer.
2271 */
2272
2273 static void consumer_close( mlt_consumer consumer )
2274 {
2275         // Stop the consumer
2276         mlt_consumer_stop( consumer );
2277
2278         // Close the parent
2279         mlt_consumer_close( consumer );
2280
2281         // Free the memory
2282         free( consumer );
2283 }