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