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