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