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