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