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