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