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