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