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