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