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