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