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