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