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