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