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