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