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