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