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