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