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