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