]> git.sesse.net Git - mlt/blob - src/modules/avformat/consumer_avformat.c
Rename 'this' in avformat module.
[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 )
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 = avcodec_find_encoder( c->codec_id );
500
501         avformat_lock();
502         
503         // Continue if codec found and we can open it
504         if ( codec != NULL && avcodec_open( c, codec ) >= 0 )
505         {
506                 // ugly hack for PCM codecs (will be removed ASAP with new PCM
507                 // support to compute the input frame size in samples
508                 if ( c->frame_size <= 1 ) 
509                 {
510                         audio_input_frame_size = audio_outbuf_size / c->channels;
511                         switch(st->codec->codec_id) 
512                         {
513                                 case CODEC_ID_PCM_S16LE:
514                                 case CODEC_ID_PCM_S16BE:
515                                 case CODEC_ID_PCM_U16LE:
516                                 case CODEC_ID_PCM_U16BE:
517                                         audio_input_frame_size >>= 1;
518                                         break;
519                                 default:
520                                         break;
521                         }
522                 } 
523                 else 
524                 {
525                         audio_input_frame_size = c->frame_size;
526                 }
527
528                 // Some formats want stream headers to be seperate (hmm)
529                 if ( !strcmp( oc->oformat->name, "mp4" ) ||
530                          !strcmp( oc->oformat->name, "mov" ) ||
531                          !strcmp( oc->oformat->name, "3gp" ) )
532                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
533         }
534         else
535         {
536                 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
537         }
538         
539         avformat_unlock();
540
541         return audio_input_frame_size;
542 }
543
544 static void close_audio( AVFormatContext *oc, AVStream *st )
545 {
546         if ( st && st->codec )
547         {
548                 avformat_lock();
549                 avcodec_close( st->codec );
550                 avformat_unlock();
551         }
552 }
553
554 /** Add a video output stream 
555 */
556
557 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, int codec_id )
558 {
559         // Get the properties
560         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
561
562         // Create a new stream
563         AVStream *st = av_new_stream( oc, oc->nb_streams );
564
565         if ( st != NULL ) 
566         {
567                 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
568                 AVCodecContext *c = st->codec;
569
570                 // Establish defaults from AVOptions
571                 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
572
573                 c->codec_id = codec_id;
574                 c->codec_type = CODEC_TYPE_VIDEO;
575                 
576                 // Setup multi-threading
577                 int thread_count = mlt_properties_get_int( properties, "threads" );
578                 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
579                         thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
580                 if ( thread_count > 1 )
581                         avcodec_thread_init( c, thread_count );         
582         
583                 // Process properties as AVOptions
584                 char *vpre = mlt_properties_get( properties, "vpre" );
585                 if ( vpre )
586                 {
587                         mlt_properties p = mlt_properties_load( vpre );
588 #ifdef AVDATADIR
589                         if ( mlt_properties_count( p ) < 1 )
590                         {
591                                 AVCodec *codec = avcodec_find_encoder( c->codec_id );
592                                 if ( codec )
593                                 {
594                                         char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
595                                         strcpy( path, AVDATADIR );
596                                         strcat( path, codec->name );
597                                         strcat( path, "-" );
598                                         strcat( path, vpre );
599                                         strcat( path, ".ffpreset" );
600                                         
601                                         mlt_properties_close( p );
602                                         p = mlt_properties_load( path );
603                                         mlt_properties_debug( p, path, stderr );
604                                         free( path );   
605                                 }
606                         }
607                         else
608                         {
609                                 mlt_properties_debug( p, vpre, stderr );                        
610                         }
611 #endif
612                         apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
613                         mlt_properties_close( p );
614                 }
615                 int colorspace = mlt_properties_get_int( properties, "colorspace" );
616                 mlt_properties_set( properties, "colorspace", NULL );
617                 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
618                 mlt_properties_set_int( properties, "colorspace", colorspace );
619
620                 // Set options controlled by MLT
621                 c->width = mlt_properties_get_int( properties, "width" );
622                 c->height = mlt_properties_get_int( properties, "height" );
623                 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
624                 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
625                 if ( st->time_base.den == 0 )
626                         st->time_base = c->time_base;
627 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
628                 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
629 #else
630                 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
631 #endif
632                 
633 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
634                 switch ( colorspace )
635                 {
636                 case 170:
637                         c->colorspace = AVCOL_SPC_SMPTE170M;
638                         break;
639                 case 240:
640                         c->colorspace = AVCOL_SPC_SMPTE240M;
641                         break;
642                 case 470:
643                         c->colorspace = AVCOL_SPC_BT470BG;
644                         break;
645                 case 601:
646                         c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
647                         break;
648                 case 709:
649                         c->colorspace = AVCOL_SPC_BT709;
650                         break;
651                 }
652 #endif
653
654                 if ( mlt_properties_get( properties, "aspect" ) )
655                 {
656                         // "-aspect" on ffmpeg command line is display aspect ratio
657                         double ar = mlt_properties_get_double( properties, "aspect" );
658                         AVRational rational = av_d2q( ar, 255 );
659
660                         // Update the profile and properties as well since this is an alias 
661                         // for mlt properties that correspond to profile settings
662                         mlt_properties_set_int( properties, "display_aspect_num", rational.num );
663                         mlt_properties_set_int( properties, "display_aspect_den", rational.den );
664                         mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
665                         if ( profile )
666                         {
667                                 profile->display_aspect_num = rational.num;
668                                 profile->display_aspect_den = rational.den;
669                                 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
670                         }
671
672                         // Now compute the sample aspect ratio
673                         rational = av_d2q( ar * c->height / c->width, 255 );
674                         c->sample_aspect_ratio = rational;
675                         // Update the profile and properties as well since this is an alias 
676                         // for mlt properties that correspond to profile settings
677                         mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
678                         mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
679                         if ( profile )
680                         {
681                                 profile->sample_aspect_num = rational.num;
682                                 profile->sample_aspect_den = rational.den;
683                                 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
684                         }
685                 }
686                 else
687                 {
688                         c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
689                         c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
690                 }
691 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
692                 st->sample_aspect_ratio = c->sample_aspect_ratio;
693 #endif
694
695                 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
696                 {
697                         c->flags |= CODEC_FLAG_QSCALE;
698                         st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
699                 }
700
701                 // Allow the user to override the video fourcc
702                 if ( mlt_properties_get( properties, "vtag" ) )
703                 {
704                         char *tail = NULL;
705                         const char *arg = mlt_properties_get( properties, "vtag" );
706                         int tag = strtol( arg, &tail, 0);
707                         if( !tail || *tail )
708                                 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
709                         c->codec_tag = tag;
710                 }
711
712                 // Some formats want stream headers to be seperate
713                 if ( oc->oformat->flags & AVFMT_GLOBALHEADER ) 
714                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
715
716                 // Translate these standard mlt consumer properties to ffmpeg
717                 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
718                      mlt_properties_get_int( properties, "deinterlace" ) == 0 )
719                 {
720                         if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
721                                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
722                         if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
723                                 c->flags |= CODEC_FLAG_INTERLACED_ME;
724                 }
725                 
726                 // parse the ratecontrol override string
727                 int i;
728                 char *rc_override = mlt_properties_get( properties, "rc_override" );
729                 for ( i = 0; rc_override; i++ )
730                 {
731                         int start, end, q;
732                         int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
733                         if ( e != 3 )
734                                 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
735                         c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
736                         c->rc_override[i].start_frame = start;
737                         c->rc_override[i].end_frame = end;
738                         if ( q > 0 )
739                         {
740                                 c->rc_override[i].qscale = q;
741                                 c->rc_override[i].quality_factor = 1.0;
742                         }
743                         else
744                         {
745                                 c->rc_override[i].qscale = 0;
746                                 c->rc_override[i].quality_factor = -q / 100.0;
747                         }
748                         rc_override = strchr( rc_override, '/' );
749                         if ( rc_override )
750                                 rc_override++;
751                 }
752                 c->rc_override_count = i;
753                 if ( !c->rc_initial_buffer_occupancy )
754                         c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
755                 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
756
757                 // Setup dual-pass
758                 i = mlt_properties_get_int( properties, "pass" );
759                 if ( i == 1 )
760                         c->flags |= CODEC_FLAG_PASS1;
761                 else if ( i == 2 )
762                         c->flags |= CODEC_FLAG_PASS2;
763                 if ( codec_id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
764                 {
765                         char logfilename[1024];
766                         FILE *f;
767                         int size;
768                         char *logbuffer;
769
770                         snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
771                                 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
772                         if ( c->flags & CODEC_FLAG_PASS1 )
773                         {
774                                 f = fopen( logfilename, "w" );
775                                 if ( !f )
776                                         perror( logfilename );
777                                 else
778                                         mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
779                         }
780                         else
781                         {
782                                 /* read the log file */
783                                 f = fopen( logfilename, "r" );
784                                 if ( !f )
785                                 {
786                                         perror(logfilename);
787                                 }
788                                 else
789                                 {
790                                         mlt_properties_set( properties, "_logfilename", logfilename );
791                                         fseek( f, 0, SEEK_END );
792                                         size = ftell( f );
793                                         fseek( f, 0, SEEK_SET );
794                                         logbuffer = av_malloc( size + 1 );
795                                         if ( !logbuffer )
796                                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
797                                         else
798                                         {
799                                                 size = fread( logbuffer, 1, size, f );
800                                                 fclose( f );
801                                                 logbuffer[size] = '\0';
802                                                 c->stats_in = logbuffer;
803                                                 mlt_properties_set_data( properties, "_logbuffer", logbuffer, 0, ( mlt_destructor )av_free, NULL );
804                                         }
805                                 }
806                         }
807                 }
808         }
809         else
810         {
811                 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
812         }
813  
814         return st;
815 }
816
817 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
818 {
819         // Allocate a frame
820         AVFrame *picture = avcodec_alloc_frame();
821
822         // Determine size of the 
823         int size = avpicture_get_size(pix_fmt, width, height);
824
825         // Allocate the picture buf
826         uint8_t *picture_buf = av_malloc(size);
827
828         // If we have both, then fill the image
829         if ( picture != NULL && picture_buf != NULL )
830         {
831                 // Fill the frame with the allocated buffer
832                 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
833         }
834         else
835         {
836                 // Something failed - clean up what we can
837                 av_free( picture );
838                 av_free( picture_buf );
839                 picture = NULL;
840         }
841
842         return picture;
843 }
844         
845 static int open_video(AVFormatContext *oc, AVStream *st)
846 {
847         // Get the codec
848         AVCodecContext *video_enc = st->codec;
849
850         // find the video encoder
851         AVCodec *codec = avcodec_find_encoder( video_enc->codec_id );
852
853         if( codec && codec->pix_fmts )
854         {
855                 const enum PixelFormat *p = codec->pix_fmts;
856                 for( ; *p!=-1; p++ )
857                 {
858                         if( *p == video_enc->pix_fmt )
859                                 break;
860                 }
861                 if( *p == -1 )
862                         video_enc->pix_fmt = codec->pix_fmts[ 0 ];
863         }
864
865         // Open the codec safely
866         avformat_lock();
867         int result = codec != NULL && avcodec_open( video_enc, codec ) >= 0;
868         avformat_unlock();
869         
870         return result;
871 }
872
873 void close_video(AVFormatContext *oc, AVStream *st)
874 {
875         if ( st && st->codec )
876         {
877                 avformat_lock();
878                 avcodec_close(st->codec);
879                 avformat_unlock();
880         }
881 }
882
883 static inline long time_difference( struct timeval *time1 )
884 {
885         struct timeval time2;
886         gettimeofday( &time2, NULL );
887         return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
888 }
889
890 /** The main thread - the argument is simply the consumer.
891 */
892
893 static void *consumer_thread( void *arg )
894 {
895         // Map the argument to the object
896         mlt_consumer consumer = arg;
897
898         // Get the properties
899         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
900
901         // Get the terminate on pause property
902         int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
903         int terminated = 0;
904
905         // Determine if feed is slow (for realtime stuff)
906         int real_time_output = mlt_properties_get_int( properties, "real_time" );
907
908         // Time structures
909         struct timeval ante;
910
911         // Get the frame rate
912         double fps = mlt_properties_get_double( properties, "fps" );
913
914         // Get width and height
915         int width = mlt_properties_get_int( properties, "width" );
916         int height = mlt_properties_get_int( properties, "height" );
917         int img_width = width;
918         int img_height = height;
919
920         // Get default audio properties
921         mlt_audio_format aud_fmt = mlt_audio_s16;
922         int channels = mlt_properties_get_int( properties, "channels" );
923         int total_channels = channels;
924         int frequency = mlt_properties_get_int( properties, "frequency" );
925         int16_t *pcm = NULL;
926         int samples = 0;
927
928         // AVFormat audio buffer and frame size
929         int audio_outbuf_size = AUDIO_BUFFER_SIZE;
930         uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
931         int audio_input_frame_size = 0;
932
933         // AVFormat video buffer and frame count
934         int frame_count = 0;
935         int video_outbuf_size = VIDEO_BUFFER_SIZE;
936         uint8_t *video_outbuf = av_malloc( video_outbuf_size );
937
938         // Used for the frame properties
939         mlt_frame frame = NULL;
940         mlt_properties frame_properties = NULL;
941
942         // Get the queues
943         mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
944         sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
945
946         // Need two av pictures for converting
947         AVFrame *output = NULL;
948         AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
949
950         // For receiving images from an mlt_frame
951         uint8_t *image;
952         mlt_image_format img_fmt = mlt_image_yuv422;
953
954         // For receiving audio samples back from the fifo
955         int16_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
956         int16_t *audio_buf_2 = NULL;
957         int count = 0;
958
959         // Allocate the context
960 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
961         AVFormatContext *oc = avformat_alloc_context( );
962 #else
963         AVFormatContext *oc = av_alloc_format_context( );
964 #endif
965
966         // Streams
967         AVStream *video_st = NULL;
968         AVStream *audio_st[ MAX_AUDIO_STREAMS ];
969
970         // Time stamps
971         double audio_pts = 0;
972         double video_pts = 0;
973
974         // Frames dispatched
975         long int frames = 0;
976         long int total_time = 0;
977
978         // Determine the format
979         AVOutputFormat *fmt = NULL;
980         const char *filename = mlt_properties_get( properties, "target" );
981         char *format = mlt_properties_get( properties, "f" );
982         char *vcodec = mlt_properties_get( properties, "vcodec" );
983         char *acodec = mlt_properties_get( properties, "acodec" );
984         
985         // Used to store and override codec ids
986         int audio_codec_id;
987         int video_codec_id;
988
989         // Misc
990         char key[27];
991         mlt_properties frame_meta_properties = mlt_properties_new();
992
993         // Initialize audio_st
994         int i = MAX_AUDIO_STREAMS;
995         while ( i-- )
996                 audio_st[i] = NULL;
997
998         // Check for user selected format first
999         if ( format != NULL )
1000 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1001                 fmt = guess_format( format, NULL, NULL );
1002 #else
1003                 fmt = av_guess_format( format, NULL, NULL );
1004 #endif
1005
1006         // Otherwise check on the filename
1007         if ( fmt == NULL && filename != NULL )
1008 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1009                 fmt = guess_format( NULL, filename, NULL );
1010 #else
1011                 fmt = av_guess_format( NULL, filename, NULL );
1012 #endif
1013
1014         // Otherwise default to mpeg
1015         if ( fmt == NULL )
1016 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1017                 fmt = guess_format( "mpeg", NULL, NULL );
1018 #else
1019                 fmt = av_guess_format( "mpeg", NULL, NULL );
1020 #endif
1021
1022         // We need a filename - default to stdout?
1023         if ( filename == NULL || !strcmp( filename, "" ) )
1024                 filename = "pipe:";
1025
1026         // Get the codec ids selected
1027         audio_codec_id = fmt->audio_codec;
1028         video_codec_id = fmt->video_codec;
1029
1030         // Check for audio codec overides
1031         if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1032                 audio_codec_id = CODEC_ID_NONE;
1033         else if ( acodec )
1034         {
1035                 AVCodec *p = avcodec_find_encoder_by_name( acodec );
1036                 if ( p != NULL )
1037                         audio_codec_id = p->id;
1038                 else
1039                         mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1040         }
1041
1042         // Check for video codec overides
1043         if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1044                 video_codec_id = CODEC_ID_NONE;
1045         else if ( vcodec )
1046         {
1047                 AVCodec *p = avcodec_find_encoder_by_name( vcodec );
1048                 if ( p != NULL )
1049                         video_codec_id = p->id;
1050                 else
1051                         mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1052         }
1053
1054         // Write metadata
1055 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1056         for ( i = 0; i < mlt_properties_count( properties ); i++ )
1057         {
1058                 char *name = mlt_properties_get_name( properties, i );
1059                 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1060                 {
1061                         char *key = strdup( name + 10 );
1062                         char *markup = strrchr( key, '.' );
1063                         if ( markup && !strcmp( markup, ".markup") )
1064                         {
1065                                 markup[0] = '\0';
1066                                 if ( !strstr( key, ".stream." ) )
1067 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1068                                         av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1069 #else
1070                                         av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1071 #endif
1072                         }
1073                         free( key );
1074                 }
1075         }
1076 #else
1077         char *tmp = NULL;
1078         int metavalue;
1079
1080         tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1081         if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1082
1083         tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1084         if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1085
1086         tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1087         if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1088
1089         tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1090         if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1091
1092         tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1093         if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1094
1095         metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1096         if (metavalue != 0) oc->year = metavalue;
1097
1098         metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1099         if (metavalue != 0) oc->track = metavalue;
1100 #endif
1101
1102         oc->oformat = fmt;
1103         snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1104
1105         // Add audio and video streams
1106         if ( video_codec_id != CODEC_ID_NONE )
1107                 video_st = add_video_stream( consumer, oc, video_codec_id );
1108         if ( audio_codec_id != CODEC_ID_NONE )
1109         {
1110                 int is_multi = 0;
1111
1112                 total_channels = 0;
1113                 // multitrack audio
1114                 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1115                 {
1116                         sprintf( key, "channels.%d", i );
1117                         int j = mlt_properties_get_int( properties, key );
1118                         if ( j )
1119                         {
1120                                 is_multi = 1;
1121                                 total_channels += j;
1122                                 audio_st[i] = add_audio_stream( consumer, oc, audio_codec_id, j );
1123                         }
1124                 }
1125                 // single track
1126                 if ( !is_multi )
1127                 {
1128                         audio_st[0] = add_audio_stream( consumer, oc, audio_codec_id, channels );
1129                         total_channels = channels;
1130                 }
1131         }
1132
1133         // Set the parameters (even though we have none...)
1134         if ( av_set_parameters(oc, NULL) >= 0 ) 
1135         {
1136                 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1137                 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1138
1139                 // Process properties as AVOptions
1140                 char *fpre = mlt_properties_get( properties, "fpre" );
1141                 if ( fpre )
1142                 {
1143                         mlt_properties p = mlt_properties_load( fpre );
1144                         apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM, 1 );
1145                         mlt_properties_close( p );
1146                 }
1147                 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM, 0 );
1148
1149                 if ( video_st && !open_video( oc, video_st ) )
1150                         video_st = NULL;
1151                 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1152                 {
1153                         audio_input_frame_size = open_audio( oc, audio_st[i], audio_outbuf_size );
1154                         if ( !audio_input_frame_size )
1155                                 audio_st[i] = NULL;
1156                 }
1157
1158                 // Open the output file, if needed
1159                 if ( !( fmt->flags & AVFMT_NOFILE ) ) 
1160                 {
1161                         if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 ) 
1162                         {
1163                                 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1164                                 mlt_properties_set_int( properties, "running", 0 );
1165                         }
1166                 }
1167         
1168                 // Write the stream header.
1169                 if ( mlt_properties_get_int( properties, "running" ) )
1170                         av_write_header( oc );
1171         }
1172         else
1173         {
1174                 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1175                 mlt_properties_set_int( properties, "running", 0 );
1176         }
1177
1178         // Allocate picture
1179         if ( video_st )
1180                 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1181
1182         // Last check - need at least one stream
1183         if ( !audio_st[0] && !video_st )
1184                 mlt_properties_set_int( properties, "running", 0 );
1185
1186         // Get the starting time (can ignore the times above)
1187         gettimeofday( &ante, NULL );
1188
1189         // Loop while running
1190         while( mlt_properties_get_int( properties, "running" ) &&
1191                ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1192         {
1193                 frame = mlt_consumer_rt_frame( consumer );
1194
1195                 // Check that we have a frame to work with
1196                 if ( frame != NULL )
1197                 {
1198                         // Increment frames dispatched
1199                         frames ++;
1200
1201                         // Default audio args
1202                         frame_properties = MLT_FRAME_PROPERTIES( frame );
1203
1204                         // Check for the terminated condition
1205                         terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1206
1207                         // Get audio and append to the fifo
1208                         if ( !terminated && audio_st[0] )
1209                         {
1210                                 samples = mlt_sample_calculator( fps, frequency, count ++ );
1211                                 mlt_frame_get_audio( frame, (void**) &pcm, &aud_fmt, &frequency, &channels, &samples );
1212
1213                                 // Save the audio channel remap properties for later
1214                                 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1215
1216                                 // Create the fifo if we don't have one
1217                                 if ( fifo == NULL )
1218                                 {
1219                                         fifo = sample_fifo_init( frequency, channels );
1220                                         mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1221                                 }
1222
1223                                 // Silence if not normal forward speed
1224                                 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1225                                         memset( pcm, 0, samples * channels * 2 );
1226
1227                                 // Append the samples
1228                                 sample_fifo_append( fifo, pcm, samples * channels );
1229                                 total_time += ( samples * 1000000 ) / frequency;
1230
1231                                 if ( !video_st )
1232                                         mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1233                         }
1234
1235                         // Encode the image
1236                         if ( !terminated && video_st )
1237                                 mlt_deque_push_back( queue, frame );
1238                         else
1239                                 mlt_frame_close( frame );
1240                 }
1241
1242                 // While we have stuff to process, process...
1243                 while ( 1 )
1244                 {
1245                         // Write interleaved audio and video frames
1246                         if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1247                         {
1248                                 // Write audio
1249                                 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1250                                 {
1251                                         int j = 0; // channel offset into interleaved source buffer
1252                                         int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) ), AUDIO_ENCODE_BUFFER_SIZE );
1253
1254                                         // Get the audio samples
1255                                         if ( n > 0 )
1256                                         {
1257                                                 sample_fifo_fetch( fifo, audio_buf_1, n );
1258                                         }
1259                                         else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1260                                         {
1261                                                 // This prevents an infinite loop when some versions of vorbis do not
1262                                                 // increment pts when encoding silence.
1263                                                 audio_pts = video_pts;
1264                                                 break;
1265                                         }
1266                                         else
1267                                         {
1268                                                 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1269                                         }
1270                                         samples = n / channels;
1271
1272                                         // For each output stream
1273                                         for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1274                                         {
1275                                                 AVStream *stream = audio_st[i];
1276                                                 AVCodecContext *codec = stream->codec;
1277                                                 AVPacket pkt;
1278
1279                                                 av_init_packet( &pkt );
1280
1281                                                 // Optimized for single track and no channel remap
1282                                                 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1283                                                 {
1284                                                         pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1285                                                 }
1286                                                 else
1287                                                 {
1288                                                         // Extract the audio channels according to channel mapping
1289                                                         int dest_offset = 0; // channel offset into interleaved dest buffer
1290
1291                                                         // Get the number of channels for this stream
1292                                                         sprintf( key, "channels.%d", i );
1293                                                         int current_channels = mlt_properties_get_int( properties, key );
1294
1295                                                         // Clear the destination audio buffer.
1296                                                         if ( !audio_buf_2 )
1297                                                                 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1298                                                         else
1299                                                                 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1300
1301                                                         // For each output channel
1302                                                         while ( dest_offset < current_channels && j < total_channels )
1303                                                         {
1304                                                                 int map_start = -1, map_channels = 0;
1305                                                                 int source_offset = 0;
1306                                                                 int k;
1307
1308                                                                 // Look for a mapping that starts at j
1309                                                                 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1310                                                                 {
1311                                                                         sprintf( key, "%d.channels", k );
1312                                                                         map_channels = mlt_properties_get_int( frame_meta_properties, key );
1313                                                                         sprintf( key, "%d.start", k );
1314                                                                         if ( mlt_properties_get( frame_meta_properties, key ) )
1315                                                                                 map_start = mlt_properties_get_int( frame_meta_properties, key );
1316                                                                         if ( map_start != j )
1317                                                                                 source_offset += map_channels;
1318                                                                 }
1319
1320                                                                 // If no mapping
1321                                                                 if ( map_start != j )
1322                                                                 {
1323                                                                         map_channels = current_channels;
1324                                                                         source_offset = j;
1325                                                                 }
1326
1327                                                                 // Copy samples if source offset valid
1328                                                                 if ( source_offset < channels )
1329                                                                 {
1330                                                                         // Interleave the audio buffer with the # channels for this stream/mapping.
1331                                                                         for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1332                                                                         {
1333                                                                                 int16_t *src = audio_buf_1 + source_offset;
1334                                                                                 int16_t *dest = audio_buf_2 + dest_offset;
1335                                                                                 int s = samples + 1;
1336
1337                                                                                 while ( --s ) {
1338                                                                                         *dest = *src;
1339                                                                                         dest += current_channels;
1340                                                                                         src += channels;
1341                                                                                 }
1342                                                                         }
1343                                                                 }
1344                                                                 // Otherwise silence
1345                                                                 else
1346                                                                 {
1347                                                                         j += current_channels;
1348                                                                         dest_offset += current_channels;
1349                                                                 }
1350                                                         }
1351                                                         pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_2 );
1352                                                 }
1353
1354                                                 // Write the compressed frame in the media file
1355                                                 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1356                                                 {
1357                                                         pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1358                                                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %lld frame pts %lld",
1359                                                                 stream->index, pkt.pts, codec->coded_frame->pts );
1360                                                 }
1361                                                 pkt.flags |= PKT_FLAG_KEY;
1362                                                 pkt.stream_index = stream->index;
1363                                                 pkt.data = audio_outbuf;
1364
1365                                                 if ( pkt.size > 0 )
1366                                                 {
1367                                                         if ( av_interleaved_write_frame( oc, &pkt ) )
1368                                                         {
1369                                                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1370                                                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1371                                                                 goto on_fatal_error;
1372                                                         }
1373                                                 }
1374
1375                                                 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1376                                                 if ( i == 0 )
1377                                                 {
1378                                                         audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1379                                                 }
1380                                         }
1381                                 }
1382                                 else
1383                                 {
1384                                         break;
1385                                 }
1386                         }
1387                         else if ( video_st )
1388                         {
1389                                 // Write video
1390                                 if ( mlt_deque_count( queue ) )
1391                                 {
1392                                         int out_size, ret = 0;
1393                                         AVCodecContext *c;
1394
1395                                         frame = mlt_deque_pop_front( queue );
1396                                         frame_properties = MLT_FRAME_PROPERTIES( frame );
1397
1398                                         c = video_st->codec;
1399                                         
1400                                         if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1401                                         {
1402                                                 int i = 0;
1403                                                 uint8_t *p;
1404                                                 uint8_t *q;
1405
1406                                                 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1407
1408                                                 q = image;
1409
1410                                                 // Convert the mlt frame to an AVPicture
1411                                                 for ( i = 0; i < height; i ++ )
1412                                                 {
1413                                                         p = input->data[ 0 ] + i * input->linesize[ 0 ];
1414                                                         memcpy( p, q, width * 2 );
1415                                                         q += width * 2;
1416                                                 }
1417
1418                                                 // Do the colour space conversion
1419 #ifdef SWSCALE
1420                                                 int flags = SWS_BILINEAR;
1421 #ifdef USE_MMX
1422                                                 flags |= SWS_CPU_CAPS_MMX;
1423 #endif
1424 #ifdef USE_SSE
1425                                                 flags |= SWS_CPU_CAPS_MMX2;
1426 #endif
1427                                                 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1428                                                         width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1429                                                 sws_scale( context, input->data, input->linesize, 0, height,
1430                                                         output->data, output->linesize);
1431                                                 sws_freeContext( context );
1432 #else
1433                                                 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1434 #endif
1435
1436                                                 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1437
1438                                                 // Apply the alpha if applicable
1439                                                 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1440                                                 {
1441                                                         uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1442                                                         register int n;
1443
1444                                                         for ( i = 0; i < height; i ++ )
1445                                                         {
1446                                                                 n = ( width + 7 ) / 8;
1447                                                                 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1448
1449                                                                 switch( width % 8 )
1450                                                                 {
1451                                                                         case 0: do { *p = *alpha++; p += 4;
1452                                                                         case 7:          *p = *alpha++; p += 4;
1453                                                                         case 6:          *p = *alpha++; p += 4;
1454                                                                         case 5:          *p = *alpha++; p += 4;
1455                                                                         case 4:          *p = *alpha++; p += 4;
1456                                                                         case 3:          *p = *alpha++; p += 4;
1457                                                                         case 2:          *p = *alpha++; p += 4;
1458                                                                         case 1:          *p = *alpha++; p += 4;
1459                                                                                         }
1460                                                                                         while( --n );
1461                                                                 }
1462                                                         }
1463                                                 }
1464                                         }
1465
1466                                         if (oc->oformat->flags & AVFMT_RAWPICTURE) 
1467                                         {
1468                                                 // raw video case. The API will change slightly in the near future for that
1469                                                 AVPacket pkt;
1470                                                 av_init_packet(&pkt);
1471
1472                                                 pkt.flags |= PKT_FLAG_KEY;
1473                                                 pkt.stream_index= video_st->index;
1474                                                 pkt.data= (uint8_t *)output;
1475                                                 pkt.size= sizeof(AVPicture);
1476
1477                                                 ret = av_write_frame(oc, &pkt);
1478                                                 video_pts += c->frame_size;
1479                                         } 
1480                                         else 
1481                                         {
1482                                                 // Set the quality
1483                                                 output->quality = video_st->quality;
1484
1485                                                 // Set frame interlace hints
1486                                                 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1487                                                 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1488                                                 output->pts = frame_count;
1489
1490                                                 // Encode the image
1491                                                 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1492
1493                                                 // If zero size, it means the image was buffered
1494                                                 if ( out_size > 0 )
1495                                                 {
1496                                                         AVPacket pkt;
1497                                                         av_init_packet( &pkt );
1498
1499                                                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1500                                                                 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1501                                                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1502                                                         if( c->coded_frame && c->coded_frame->key_frame )
1503                                                                 pkt.flags |= PKT_FLAG_KEY;
1504                                                         pkt.stream_index= video_st->index;
1505                                                         pkt.data= video_outbuf;
1506                                                         pkt.size= out_size;
1507
1508                                                         // write the compressed frame in the media file
1509                                                         ret = av_interleaved_write_frame(oc, &pkt);
1510                                                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1511                                                         video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1512                                                         
1513                                                         // Dual pass logging
1514                                                         if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1515                                                                 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1516                                                 } 
1517                                                 else if ( out_size < 0 )
1518                                                 {
1519                                                         mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1520                                                 }
1521                                         }
1522                                         frame_count++;
1523                                         if ( ret )
1524                                         {
1525                                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1526                                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1527                                                 goto on_fatal_error;
1528                                         }
1529                                         mlt_frame_close( frame );
1530                                 }
1531                                 else
1532                                 {
1533                                         break;
1534                                 }
1535                         }
1536                         if ( audio_st[0] )
1537                                 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %lld (%f) ", audio_st[0]->pts.val, audio_pts );
1538                         if ( video_st )
1539                                 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %lld (%f) ", video_st->pts.val, video_pts );
1540                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1541                 }
1542
1543                 if ( real_time_output == 1 && frames % 2 == 0 )
1544                 {
1545                         long passed = time_difference( &ante );
1546                         if ( fifo != NULL )
1547                         {
1548                                 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1549                                 passed -= pending;
1550                         }
1551                         if ( passed < total_time )
1552                         {
1553                                 long total = ( total_time - passed );
1554                                 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1555                                 nanosleep( &t, NULL );
1556                         }
1557                 }
1558         }
1559
1560         // Flush the encoder buffers
1561         if ( real_time_output <= 0 )
1562         {
1563                 // Flush audio fifo
1564                 // TODO: flush all audio streams
1565                 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1566                 {
1567                         AVCodecContext *c = audio_st[0]->codec;
1568                         AVPacket pkt;
1569                         av_init_packet( &pkt );
1570                         pkt.size = 0;
1571
1572                         if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1573                                 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1574                         {
1575                                 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size );
1576                                 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1577                         }
1578                         if ( pkt.size <= 0 )
1579                                 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1580                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1581                         if ( pkt.size <= 0 )
1582                                 break;
1583
1584                         // Write the compressed frame in the media file
1585                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1586                                 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1587                         pkt.flags |= PKT_FLAG_KEY;
1588                         pkt.stream_index = audio_st[0]->index;
1589                         pkt.data = audio_outbuf;
1590                         if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1591                         {
1592                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1593                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1594                                 goto on_fatal_error;
1595                         }
1596                 }
1597
1598                 // Flush video
1599                 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1600                 {
1601                         AVCodecContext *c = video_st->codec;
1602                         AVPacket pkt;
1603                         av_init_packet( &pkt );
1604
1605                         // Encode the image
1606                         pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1607                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1608                         if ( pkt.size <= 0 )
1609                                 break;
1610
1611                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1612                                 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1613                         if( c->coded_frame && c->coded_frame->key_frame )
1614                                 pkt.flags |= PKT_FLAG_KEY;
1615                         pkt.stream_index = video_st->index;
1616                         pkt.data = video_outbuf;
1617
1618                         // write the compressed frame in the media file
1619                         if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1620                         {
1621                                 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1622                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1623                                 goto on_fatal_error;
1624                         }
1625                         // Dual pass logging
1626                         if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1627                                 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1628                 }
1629         }
1630
1631 on_fatal_error:
1632         
1633         // Write the trailer, if any
1634         av_write_trailer( oc );
1635
1636         // close each codec
1637         if ( video_st )
1638                 close_video(oc, video_st);
1639         for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1640                 close_audio( oc, audio_st[i] );
1641
1642         // Free the streams
1643         for ( i = 0; i < oc->nb_streams; i++ )
1644                 av_freep( &oc->streams[i] );
1645
1646         // Close the output file
1647         if ( !( fmt->flags & AVFMT_NOFILE ) )
1648 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1649                 url_fclose( oc->pb );
1650 #else
1651                 url_fclose( &oc->pb );
1652 #endif
1653
1654         // Clean up input and output frames
1655         if ( output )
1656                 av_free( output->data[0] );
1657         av_free( output );
1658         av_free( input->data[0] );
1659         av_free( input );
1660         av_free( video_outbuf );
1661         av_free( audio_buf_1 );
1662         av_free( audio_buf_2 );
1663
1664         // Free the stream
1665         av_free( oc );
1666
1667         // Just in case we terminated on pause
1668         mlt_properties_set_int( properties, "running", 0 );
1669
1670         mlt_consumer_stopped( consumer );
1671         mlt_properties_close( frame_meta_properties );
1672
1673         if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1674         {
1675                 // Remove the dual pass log file
1676                 if ( mlt_properties_get( properties, "_logfilename" ) )
1677                         remove( mlt_properties_get( properties, "_logfilename" ) );
1678
1679                 // Remove the x264 dual pass logs
1680                 char *cwd = getcwd( NULL, 0 );
1681                 const char *file = "x264_2pass.log";
1682                 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1683                 sprintf( full, "%s/%s", cwd, file );
1684                 remove( full );
1685                 free( full );
1686                 file = "x264_2pass.log.temp";
1687                 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1688                 sprintf( full, "%s/%s", cwd, file );
1689                 remove( full );
1690                 free( full );
1691                 file = "x264_2pass.log.mbtree";
1692                 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1693                 sprintf( full, "%s/%s", cwd, file );
1694                 remove( full );
1695                 free( full );
1696                 free( cwd );
1697                 remove( "x264_2pass.log.temp" );
1698         }
1699
1700         return NULL;
1701 }
1702
1703 /** Close the consumer.
1704 */
1705
1706 static void consumer_close( mlt_consumer consumer )
1707 {
1708         // Stop the consumer
1709         mlt_consumer_stop( consumer );
1710
1711         // Close the parent
1712         mlt_consumer_close( consumer );
1713
1714         // Free the memory
1715         free( consumer );
1716 }