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