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