]> git.sesse.net Git - mlt/blob - src/modules/avformat/consumer_avformat.c
consumer_avformat: handle negative return value
[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                 audio_input_frame_size = 0;
672         }
673
674         return audio_input_frame_size;
675 }
676
677 static void close_audio( AVFormatContext *oc, AVStream *st )
678 {
679         if ( st && st->codec )
680                 avcodec_close( st->codec );
681 }
682
683 /** Add a video output stream 
684 */
685
686 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
687 {
688         // Get the properties
689         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
690
691         // Create a new stream
692 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
693         AVStream *st = avformat_new_stream( oc, codec );
694 #else
695         AVStream *st = av_new_stream( oc, oc->nb_streams );
696 #endif
697
698         if ( st != NULL ) 
699         {
700                 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
701                 AVCodecContext *c = st->codec;
702
703                 // Establish defaults from AVOptions
704 #if LIBAVCODEC_VERSION_MAJOR >= 53
705                 avcodec_get_context_defaults3( c, codec );
706 #else
707                 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
708 #endif
709
710                 c->codec_id = codec->id;
711                 c->codec_type = CODEC_TYPE_VIDEO;
712                 
713                 // Setup multi-threading
714                 int thread_count = mlt_properties_get_int( properties, "threads" );
715                 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
716                         thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
717                 if ( thread_count > 1 )
718 #if LIBAVCODEC_VERSION_MAJOR >= 53
719                         c->thread_count = thread_count;
720 #else
721                         avcodec_thread_init( c, thread_count );
722 #endif
723
724                 // Process properties as AVOptions
725                 char *vpre = mlt_properties_get( properties, "vpre" );
726                 if ( vpre )
727                 {
728                         mlt_properties p = mlt_properties_load( vpre );
729 #ifdef AVDATADIR
730                         if ( mlt_properties_count( p ) < 1 )
731                         {
732                                 AVCodec *codec = avcodec_find_encoder( c->codec_id );
733                                 if ( codec )
734                                 {
735                                         char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
736                                         strcpy( path, AVDATADIR );
737                                         strcat( path, codec->name );
738                                         strcat( path, "-" );
739                                         strcat( path, vpre );
740                                         strcat( path, ".ffpreset" );
741                                         
742                                         mlt_properties_close( p );
743                                         p = mlt_properties_load( path );
744                                         if ( mlt_properties_count( p ) > 0 )
745                                                 mlt_properties_debug( p, path, stderr );
746                                         free( path );   
747                                 }
748                         }
749                         else
750                         {
751                                 mlt_properties_debug( p, vpre, stderr );                        
752                         }
753 #endif
754                         apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
755                         mlt_properties_close( p );
756                 }
757                 int colorspace = mlt_properties_get_int( properties, "colorspace" );
758                 mlt_properties_set( properties, "colorspace", NULL );
759                 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
760                 mlt_properties_set_int( properties, "colorspace", colorspace );
761
762                 // Set options controlled by MLT
763                 c->width = mlt_properties_get_int( properties, "width" );
764                 c->height = mlt_properties_get_int( properties, "height" );
765                 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
766                 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
767                 if ( st->time_base.den == 0 )
768                         st->time_base = c->time_base;
769 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
770                 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
771 #else
772                 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
773 #endif
774                 
775 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
776                 switch ( colorspace )
777                 {
778                 case 170:
779                         c->colorspace = AVCOL_SPC_SMPTE170M;
780                         break;
781                 case 240:
782                         c->colorspace = AVCOL_SPC_SMPTE240M;
783                         break;
784                 case 470:
785                         c->colorspace = AVCOL_SPC_BT470BG;
786                         break;
787                 case 601:
788                         c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
789                         break;
790                 case 709:
791                         c->colorspace = AVCOL_SPC_BT709;
792                         break;
793                 }
794 #endif
795
796                 if ( mlt_properties_get( properties, "aspect" ) )
797                 {
798                         // "-aspect" on ffmpeg command line is display aspect ratio
799                         double ar = mlt_properties_get_double( properties, "aspect" );
800                         AVRational rational = av_d2q( ar, 255 );
801
802                         // Update the profile and properties as well since this is an alias 
803                         // for mlt properties that correspond to profile settings
804                         mlt_properties_set_int( properties, "display_aspect_num", rational.num );
805                         mlt_properties_set_int( properties, "display_aspect_den", rational.den );
806                         mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
807                         if ( profile )
808                         {
809                                 profile->display_aspect_num = rational.num;
810                                 profile->display_aspect_den = rational.den;
811                                 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
812                         }
813
814                         // Now compute the sample aspect ratio
815                         rational = av_d2q( ar * c->height / c->width, 255 );
816                         c->sample_aspect_ratio = rational;
817                         // Update the profile and properties as well since this is an alias 
818                         // for mlt properties that correspond to profile settings
819                         mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
820                         mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
821                         if ( profile )
822                         {
823                                 profile->sample_aspect_num = rational.num;
824                                 profile->sample_aspect_den = rational.den;
825                                 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
826                         }
827                 }
828                 else
829                 {
830                         c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
831                         c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
832                 }
833 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
834                 st->sample_aspect_ratio = c->sample_aspect_ratio;
835 #endif
836
837                 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
838                 {
839                         c->flags |= CODEC_FLAG_QSCALE;
840                         c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
841 #if LIBAVFORMAT_VERSION_MAJOR < 53
842                         st->quality = c->global_quality;
843 #endif
844                 }
845
846                 // Allow the user to override the video fourcc
847                 if ( mlt_properties_get( properties, "vtag" ) )
848                 {
849                         char *tail = NULL;
850                         const char *arg = mlt_properties_get( properties, "vtag" );
851                         int tag = strtol( arg, &tail, 0);
852                         if( !tail || *tail )
853                                 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
854                         c->codec_tag = tag;
855                 }
856
857                 // Some formats want stream headers to be seperate
858                 if ( oc->oformat->flags & AVFMT_GLOBALHEADER ) 
859                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
860
861                 // Translate these standard mlt consumer properties to ffmpeg
862                 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
863                      mlt_properties_get_int( properties, "deinterlace" ) == 0 )
864                 {
865                         if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
866                                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
867                         if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
868                                 c->flags |= CODEC_FLAG_INTERLACED_ME;
869                 }
870                 
871                 // parse the ratecontrol override string
872                 int i;
873                 char *rc_override = mlt_properties_get( properties, "rc_override" );
874                 for ( i = 0; rc_override; i++ )
875                 {
876                         int start, end, q;
877                         int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
878                         if ( e != 3 )
879                                 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
880                         c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
881                         c->rc_override[i].start_frame = start;
882                         c->rc_override[i].end_frame = end;
883                         if ( q > 0 )
884                         {
885                                 c->rc_override[i].qscale = q;
886                                 c->rc_override[i].quality_factor = 1.0;
887                         }
888                         else
889                         {
890                                 c->rc_override[i].qscale = 0;
891                                 c->rc_override[i].quality_factor = -q / 100.0;
892                         }
893                         rc_override = strchr( rc_override, '/' );
894                         if ( rc_override )
895                                 rc_override++;
896                 }
897                 c->rc_override_count = i;
898                 if ( !c->rc_initial_buffer_occupancy )
899                         c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
900                 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
901
902                 // Setup dual-pass
903                 i = mlt_properties_get_int( properties, "pass" );
904                 if ( i == 1 )
905                         c->flags |= CODEC_FLAG_PASS1;
906                 else if ( i == 2 )
907                         c->flags |= CODEC_FLAG_PASS2;
908                 if ( codec->id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
909                 {
910                         char logfilename[1024];
911                         FILE *f;
912                         int size;
913                         char *logbuffer;
914
915                         snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
916                                 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
917                         if ( c->flags & CODEC_FLAG_PASS1 )
918                         {
919                                 f = fopen( logfilename, "w" );
920                                 if ( !f )
921                                         perror( logfilename );
922                                 else
923                                         mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
924                         }
925                         else
926                         {
927                                 /* read the log file */
928                                 f = fopen( logfilename, "r" );
929                                 if ( !f )
930                                 {
931                                         perror(logfilename);
932                                 }
933                                 else
934                                 {
935                                         mlt_properties_set( properties, "_logfilename", logfilename );
936                                         fseek( f, 0, SEEK_END );
937                                         size = ftell( f );
938                                         fseek( f, 0, SEEK_SET );
939                                         logbuffer = av_malloc( size + 1 );
940                                         if ( !logbuffer )
941                                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
942                                         else
943                                         {
944                                                 if ( size >= 0 )
945                                                 {
946                                                         size = fread( logbuffer, 1, size, f );
947                                                         logbuffer[size] = '\0';
948                                                         c->stats_in = logbuffer;
949                                                 }
950                                         }
951                                         fclose( f );
952                                 }
953                         }
954                 }
955         }
956         else
957         {
958                 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
959         }
960  
961         return st;
962 }
963
964 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
965 {
966         // Allocate a frame
967         AVFrame *picture = avcodec_alloc_frame();
968
969         // Determine size of the 
970         int size = avpicture_get_size(pix_fmt, width, height);
971
972         // Allocate the picture buf
973         uint8_t *picture_buf = av_malloc(size);
974
975         // If we have both, then fill the image
976         if ( picture != NULL && picture_buf != NULL )
977         {
978                 // Fill the frame with the allocated buffer
979                 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
980         }
981         else
982         {
983                 // Something failed - clean up what we can
984                 av_free( picture );
985                 av_free( picture_buf );
986                 picture = NULL;
987         }
988
989         return picture;
990 }
991
992 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
993 {
994         // Get the codec
995         AVCodecContext *video_enc = st->codec;
996
997         // find the video encoder
998         AVCodec *codec;
999         if ( codec_name )
1000                 codec = avcodec_find_encoder_by_name( codec_name );
1001         else
1002                 codec = avcodec_find_encoder( video_enc->codec_id );
1003
1004 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1005         // Process properties as AVOptions on the AVCodec
1006         if ( codec && codec->priv_class )
1007         {
1008                 char *vpre = mlt_properties_get( properties, "vpre" );
1009                 if ( !video_enc->priv_data && codec->priv_data_size )
1010                 {
1011                         video_enc->priv_data = av_mallocz( codec->priv_data_size );
1012                         *(const AVClass **) video_enc->priv_data = codec->priv_class;
1013 //                      av_opt_set_defaults( video_enc );
1014                 }
1015                 if ( vpre )
1016                 {
1017                         mlt_properties p = mlt_properties_load( vpre );
1018                         apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1019                         mlt_properties_close( p );
1020                 }
1021                 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1022         }
1023 #endif
1024
1025         if( codec && codec->pix_fmts )
1026         {
1027                 const enum PixelFormat *p = codec->pix_fmts;
1028                 for( ; *p!=-1; p++ )
1029                 {
1030                         if( *p == video_enc->pix_fmt )
1031                                 break;
1032                 }
1033                 if( *p == -1 )
1034                         video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1035         }
1036
1037 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1038         int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1039 #else
1040         int result = codec && avcodec_open( video_enc, codec ) >= 0;
1041 #endif
1042         
1043         return result;
1044 }
1045
1046 void close_video(AVFormatContext *oc, AVStream *st)
1047 {
1048         if ( st && st->codec )
1049         {
1050                 av_freep( &st->codec->stats_in );
1051                 avcodec_close(st->codec);
1052         }
1053 }
1054
1055 static inline long time_difference( struct timeval *time1 )
1056 {
1057         struct timeval time2;
1058         gettimeofday( &time2, NULL );
1059         return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1060 }
1061
1062 static int mlt_write(void *h, uint8_t *buf, int size)
1063 {
1064         mlt_properties properties = (mlt_properties) h;
1065         mlt_events_fire( properties, "avformat-write", buf, size, NULL );
1066         return 0;
1067 }
1068
1069 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1070 {
1071         listener( owner, service, (uint8_t*) args[0], (int) args[1] );
1072 }
1073
1074
1075 /** The main thread - the argument is simply the consumer.
1076 */
1077
1078 static void *consumer_thread( void *arg )
1079 {
1080         // Map the argument to the object
1081         mlt_consumer consumer = arg;
1082
1083         // Get the properties
1084         mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1085
1086         // Get the terminate on pause property
1087         int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1088         int terminated = 0;
1089
1090         // Determine if feed is slow (for realtime stuff)
1091         int real_time_output = mlt_properties_get_int( properties, "real_time" );
1092
1093         // Time structures
1094         struct timeval ante;
1095
1096         // Get the frame rate
1097         double fps = mlt_properties_get_double( properties, "fps" );
1098
1099         // Get width and height
1100         int width = mlt_properties_get_int( properties, "width" );
1101         int height = mlt_properties_get_int( properties, "height" );
1102         int img_width = width;
1103         int img_height = height;
1104
1105         // Get default audio properties
1106         int channels = mlt_properties_get_int( properties, "channels" );
1107         int total_channels = channels;
1108         int frequency = mlt_properties_get_int( properties, "frequency" );
1109         void *pcm = NULL;
1110         int samples = 0;
1111
1112         // AVFormat audio buffer and frame size
1113         int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1114         uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1115         int audio_input_frame_size = 0;
1116
1117         // AVFormat video buffer and frame count
1118         int frame_count = 0;
1119         int video_outbuf_size = VIDEO_BUFFER_SIZE;
1120         uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1121
1122         // Used for the frame properties
1123         mlt_frame frame = NULL;
1124         mlt_properties frame_properties = NULL;
1125
1126         // Get the queues
1127         mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1128         sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1129
1130         // Need two av pictures for converting
1131         AVFrame *output = NULL;
1132         AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
1133
1134         // For receiving images from an mlt_frame
1135         uint8_t *image;
1136         mlt_image_format img_fmt = mlt_image_yuv422;
1137
1138         // For receiving audio samples back from the fifo
1139         uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1140         uint8_t *audio_buf_2 = NULL;
1141         int count = 0;
1142
1143         // Allocate the context
1144 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
1145         AVFormatContext *oc = avformat_alloc_context( );
1146 #else
1147         AVFormatContext *oc = av_alloc_format_context( );
1148 #endif
1149
1150         // Streams
1151         AVStream *video_st = NULL;
1152         AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1153
1154         // Time stamps
1155         double audio_pts = 0;
1156         double video_pts = 0;
1157
1158         // Frames dispatched
1159         long int frames = 0;
1160         long int total_time = 0;
1161
1162         // Determine the format
1163         AVOutputFormat *fmt = NULL;
1164         const char *filename = mlt_properties_get( properties, "target" );
1165         char *format = mlt_properties_get( properties, "f" );
1166         char *vcodec = mlt_properties_get( properties, "vcodec" );
1167         char *acodec = mlt_properties_get( properties, "acodec" );
1168         AVCodec *audio_codec = NULL;
1169         AVCodec *video_codec = NULL;
1170         
1171         // Used to store and override codec ids
1172         int audio_codec_id;
1173         int video_codec_id;
1174
1175         // Misc
1176         char key[27];
1177         mlt_properties frame_meta_properties = mlt_properties_new();
1178
1179         // Initialize audio_st
1180         int i = MAX_AUDIO_STREAMS;
1181         while ( i-- )
1182                 audio_st[i] = NULL;
1183
1184         // Check for user selected format first
1185         if ( format != NULL )
1186 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1187                 fmt = guess_format( format, NULL, NULL );
1188 #else
1189                 fmt = av_guess_format( format, NULL, NULL );
1190 #endif
1191
1192         // Otherwise check on the filename
1193         if ( fmt == NULL && filename != NULL )
1194 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1195                 fmt = guess_format( NULL, filename, NULL );
1196 #else
1197                 fmt = av_guess_format( NULL, filename, NULL );
1198 #endif
1199
1200         // Otherwise default to mpeg
1201         if ( fmt == NULL )
1202 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1203                 fmt = guess_format( "mpeg", NULL, NULL );
1204 #else
1205                 fmt = av_guess_format( "mpeg", NULL, NULL );
1206 #endif
1207
1208         // We need a filename - default to stdout?
1209         if ( filename == NULL || !strcmp( filename, "" ) )
1210                 filename = "pipe:";
1211
1212         // Get the codec ids selected
1213         audio_codec_id = fmt->audio_codec;
1214         video_codec_id = fmt->video_codec;
1215
1216         // Check for audio codec overides
1217         if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1218                 audio_codec_id = CODEC_ID_NONE;
1219         else if ( acodec )
1220         {
1221                 audio_codec = avcodec_find_encoder_by_name( acodec );
1222                 if ( audio_codec )
1223                 {
1224                         audio_codec_id = audio_codec->id;
1225                         if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1226                         {
1227                                 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1228                                 acodec = mlt_properties_get( properties, "_acodec" );
1229                                 audio_codec = avcodec_find_encoder_by_name( acodec );
1230                         }
1231                         else if ( !strcmp( acodec, "aac" ) )
1232                         {
1233                                 mlt_properties_set( properties, "astrict", "experimental" );
1234                         }
1235                 }
1236                 else
1237                 {
1238                         audio_codec_id = CODEC_ID_NONE;
1239                         mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1240                 }
1241         }
1242         else
1243         {
1244                 audio_codec = avcodec_find_encoder( audio_codec_id );
1245         }
1246
1247         // Check for video codec overides
1248         if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1249                 video_codec_id = CODEC_ID_NONE;
1250         else if ( vcodec )
1251         {
1252                 video_codec = avcodec_find_encoder_by_name( vcodec );
1253                 if ( video_codec )
1254                 {
1255                         video_codec_id = video_codec->id;
1256                 }
1257                 else
1258                 {
1259                         video_codec_id = CODEC_ID_NONE;
1260                         mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1261                 }
1262         }
1263         else
1264         {
1265                 video_codec = avcodec_find_encoder( video_codec_id );
1266         }
1267
1268         // Write metadata
1269 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1270         for ( i = 0; i < mlt_properties_count( properties ); i++ )
1271         {
1272                 char *name = mlt_properties_get_name( properties, i );
1273                 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1274                 {
1275                         char *key = strdup( name + 10 );
1276                         char *markup = strrchr( key, '.' );
1277                         if ( markup && !strcmp( markup, ".markup") )
1278                         {
1279                                 markup[0] = '\0';
1280                                 if ( !strstr( key, ".stream." ) )
1281 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1282 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1283                                         av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1284 #else
1285                                         av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1286 #endif
1287 #else
1288                                         av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1289 #endif
1290                         }
1291                         free( key );
1292                 }
1293         }
1294 #else
1295         char *tmp = NULL;
1296         int metavalue;
1297
1298         tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1299         if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1300
1301         tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1302         if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1303
1304         tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1305         if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1306
1307         tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1308         if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1309
1310         tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1311         if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1312
1313         metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1314         if (metavalue != 0) oc->year = metavalue;
1315
1316         metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1317         if (metavalue != 0) oc->track = metavalue;
1318 #endif
1319
1320         oc->oformat = fmt;
1321         snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1322
1323         // Get a frame now, so we can set some AVOptions from properties.
1324         frame = mlt_consumer_rt_frame( consumer );
1325
1326         // Set the timecode from the MLT metadata if available.
1327     if ( frame )
1328     {
1329         const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1330         if ( timecode && strcmp( timecode, "" ) )
1331         {
1332             mlt_properties_set( properties, "timecode", timecode );
1333             if ( strchr( timecode, ';' ) )
1334                 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1335         }
1336     }
1337
1338         // Add audio and video streams
1339         if ( video_codec_id != CODEC_ID_NONE )
1340                 video_st = add_video_stream( consumer, oc, video_codec );
1341         if ( audio_codec_id != CODEC_ID_NONE )
1342         {
1343                 int is_multi = 0;
1344
1345                 total_channels = 0;
1346                 // multitrack audio
1347                 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1348                 {
1349                         sprintf( key, "channels.%d", i );
1350                         int j = mlt_properties_get_int( properties, key );
1351                         if ( j )
1352                         {
1353                                 is_multi = 1;
1354                                 total_channels += j;
1355                                 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1356                         }
1357                 }
1358                 // single track
1359                 if ( !is_multi )
1360                 {
1361                         audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1362                         total_channels = channels;
1363                 }
1364         }
1365         mlt_properties_set_int( properties, "channels", total_channels );
1366
1367         // Audio format is determined when adding the audio stream
1368         mlt_audio_format aud_fmt = mlt_audio_none;
1369         if ( audio_st[0] )
1370                 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1371         int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1372         sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1373
1374         // Set the parameters (even though we have none...)
1375 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1376         if ( av_set_parameters(oc, NULL) >= 0 )
1377 #endif
1378         {
1379 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1380                 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1381                         mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1382 #else
1383                 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1384 #endif
1385                 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1386
1387                 // Process properties as AVOptions
1388                 char *fpre = mlt_properties_get( properties, "fpre" );
1389                 if ( fpre )
1390                 {
1391                         mlt_properties p = mlt_properties_load( fpre );
1392                         apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1393 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1394                         if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1395                                 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1396 #endif
1397                         mlt_properties_close( p );
1398                 }
1399                 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1400 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1401                 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1402                         apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1403 #endif
1404
1405                 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1406                         video_st = NULL;
1407                 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1408                 {
1409                         audio_input_frame_size = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1410                                 acodec? acodec : NULL );
1411                         if ( !audio_input_frame_size )
1412                         {
1413                                 // Remove the audio stream from the output context
1414                                 int j;
1415                                 for ( j = 0; j < oc->nb_streams; j++ )
1416                                 {
1417                                         if ( oc->streams[j] == audio_st[i] )
1418                                                 av_freep( &oc->streams[j] );
1419                                 }
1420                                 --oc->nb_streams;
1421                                 audio_st[i] = NULL;
1422                         }
1423                 }
1424
1425                 // Setup custom I/O if redirecting
1426                 if ( mlt_properties_get_int( properties, "redirect" ) )
1427                 {
1428                         int buffer_size = 32768;
1429                         unsigned char *buffer = av_malloc( buffer_size );
1430 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1431                         AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1432 #else
1433                         ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1434 #endif
1435                         if ( buffer && io )
1436                         {
1437                                 oc->pb = io;
1438 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1439                                 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1440 #endif
1441                                 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1442                                 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1443                                 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1444                         }
1445                         else
1446                         {
1447                                 av_free( buffer );
1448                                 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1449                         }
1450                 }
1451                 // Open the output file, if needed
1452                 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1453                 {
1454 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1455                         if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1456 #else
1457                         if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1458 #endif
1459                         {
1460                                 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1461                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1462                                 goto on_fatal_error;
1463                         }
1464                 }
1465         
1466                 // Write the stream header.
1467                 if ( mlt_properties_get_int( properties, "running" ) )
1468 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1469                         avformat_write_header( oc, NULL );
1470 #else
1471                         av_write_header( oc );
1472 #endif
1473         }
1474 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1475         else
1476         {
1477                 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1478                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1479                 goto on_fatal_error;
1480         }
1481 #endif
1482
1483         // Allocate picture
1484         if ( video_st )
1485                 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1486
1487         // Last check - need at least one stream
1488         if ( !audio_st[0] && !video_st )
1489         {
1490                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1491                 goto on_fatal_error;
1492         }
1493
1494         // Get the starting time (can ignore the times above)
1495         gettimeofday( &ante, NULL );
1496
1497         // Loop while running
1498         while( mlt_properties_get_int( properties, "running" ) &&
1499                ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1500         {
1501                 if ( !frame )
1502                         frame = mlt_consumer_rt_frame( consumer );
1503
1504                 // Check that we have a frame to work with
1505                 if ( frame != NULL )
1506                 {
1507                         // Increment frames dispatched
1508                         frames ++;
1509
1510                         // Default audio args
1511                         frame_properties = MLT_FRAME_PROPERTIES( frame );
1512
1513                         // Check for the terminated condition
1514                         terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1515
1516                         // Get audio and append to the fifo
1517                         if ( !terminated && audio_st[0] )
1518                         {
1519                                 samples = mlt_sample_calculator( fps, frequency, count ++ );
1520                                 channels = total_channels;
1521                                 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1522
1523                                 // Save the audio channel remap properties for later
1524                                 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1525
1526                                 // Create the fifo if we don't have one
1527                                 if ( fifo == NULL )
1528                                 {
1529                                         fifo = sample_fifo_init( frequency, channels );
1530                                         mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1531                                 }
1532                                 if ( pcm )
1533                                 {
1534                                         // Silence if not normal forward speed
1535                                         if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1536                                                 memset( pcm, 0, samples * channels * sample_bytes );
1537
1538                                         // Append the samples
1539                                         sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1540                                         total_time += ( samples * 1000000 ) / frequency;
1541                                 }
1542                                 if ( !video_st )
1543                                         mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1544                         }
1545
1546                         // Encode the image
1547                         if ( !terminated && video_st )
1548                                 mlt_deque_push_back( queue, frame );
1549                         else
1550                                 mlt_frame_close( frame );
1551                         frame = NULL;
1552                 }
1553
1554                 // While we have stuff to process, process...
1555                 while ( 1 )
1556                 {
1557                         // Write interleaved audio and video frames
1558                         if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1559                         {
1560                                 // Write audio
1561                                 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) / sample_bytes )
1562                                 {
1563                                         int j = 0; // channel offset into interleaved source buffer
1564                                         int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1565
1566                                         // Get the audio samples
1567                                         if ( n > 0 )
1568                                         {
1569                                                 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1570                                         }
1571                                         else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1572                                         {
1573                                                 // This prevents an infinite loop when some versions of vorbis do not
1574                                                 // increment pts when encoding silence.
1575                                                 audio_pts = video_pts;
1576                                                 break;
1577                                         }
1578                                         else
1579                                         {
1580                                                 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1581                                         }
1582                                         samples = n / channels;
1583
1584                                         // For each output stream
1585                                         for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1586                                         {
1587                                                 AVStream *stream = audio_st[i];
1588                                                 AVCodecContext *codec = stream->codec;
1589                                                 AVPacket pkt;
1590
1591                                                 av_init_packet( &pkt );
1592
1593                                                 // Optimized for single track and no channel remap
1594                                                 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1595                                                 {
1596                                                         pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_1 );
1597                                                 }
1598                                                 else
1599                                                 {
1600                                                         // Extract the audio channels according to channel mapping
1601                                                         int dest_offset = 0; // channel offset into interleaved dest buffer
1602
1603                                                         // Get the number of channels for this stream
1604                                                         sprintf( key, "channels.%d", i );
1605                                                         int current_channels = mlt_properties_get_int( properties, key );
1606
1607                                                         // Clear the destination audio buffer.
1608                                                         if ( !audio_buf_2 )
1609                                                                 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1610                                                         else
1611                                                                 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1612
1613                                                         // For each output channel
1614                                                         while ( dest_offset < current_channels && j < total_channels )
1615                                                         {
1616                                                                 int map_start = -1, map_channels = 0;
1617                                                                 int source_offset = 0;
1618                                                                 int k;
1619
1620                                                                 // Look for a mapping that starts at j
1621                                                                 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1622                                                                 {
1623                                                                         sprintf( key, "%d.channels", k );
1624                                                                         map_channels = mlt_properties_get_int( frame_meta_properties, key );
1625                                                                         sprintf( key, "%d.start", k );
1626                                                                         if ( mlt_properties_get( frame_meta_properties, key ) )
1627                                                                                 map_start = mlt_properties_get_int( frame_meta_properties, key );
1628                                                                         if ( map_start != j )
1629                                                                                 source_offset += map_channels;
1630                                                                 }
1631
1632                                                                 // If no mapping
1633                                                                 if ( map_start != j )
1634                                                                 {
1635                                                                         map_channels = current_channels;
1636                                                                         source_offset = j;
1637                                                                 }
1638
1639                                                                 // Copy samples if source offset valid
1640                                                                 if ( source_offset < channels )
1641                                                                 {
1642                                                                         // Interleave the audio buffer with the # channels for this stream/mapping.
1643                                                                         for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1644                                                                         {
1645                                                                                 void *src = audio_buf_1 + source_offset * sample_bytes;
1646                                                                                 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1647                                                                                 int s = samples + 1;
1648
1649                                                                                 while ( --s ) {
1650                                                                                         memcpy( dest, src, sample_bytes );
1651                                                                                         dest += current_channels * sample_bytes;
1652                                                                                         src += channels * sample_bytes;
1653                                                                                 }
1654                                                                         }
1655                                                                 }
1656                                                                 // Otherwise silence
1657                                                                 else
1658                                                                 {
1659                                                                         j += current_channels;
1660                                                                         dest_offset += current_channels;
1661                                                                 }
1662                                                         }
1663                                                         pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1664                                                 }
1665
1666                                                 // Write the compressed frame in the media file
1667                                                 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1668                                                 {
1669                                                         pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1670                                                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame pts %"PRId64,
1671                                                                 stream->index, pkt.pts, codec->coded_frame->pts );
1672                                                 }
1673                                                 pkt.flags |= PKT_FLAG_KEY;
1674                                                 pkt.stream_index = stream->index;
1675                                                 pkt.data = audio_outbuf;
1676
1677                                                 if ( pkt.size > 0 )
1678                                                 {
1679                                                         if ( av_interleaved_write_frame( oc, &pkt ) )
1680                                                         {
1681                                                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1682                                                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1683                                                                 goto on_fatal_error;
1684                                                         }
1685                                                 }
1686
1687                                                 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1688                                                 if ( i == 0 )
1689                                                 {
1690                                                         audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1691                                                 }
1692                                         }
1693                                 }
1694                                 else
1695                                 {
1696                                         break;
1697                                 }
1698                         }
1699                         else if ( video_st )
1700                         {
1701                                 // Write video
1702                                 if ( mlt_deque_count( queue ) )
1703                                 {
1704                                         int out_size, ret = 0;
1705                                         AVCodecContext *c;
1706
1707                                         frame = mlt_deque_pop_front( queue );
1708                                         frame_properties = MLT_FRAME_PROPERTIES( frame );
1709
1710                                         c = video_st->codec;
1711                                         
1712                                         if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1713                                         {
1714                                                 int i = 0;
1715                                                 uint8_t *p;
1716                                                 uint8_t *q;
1717
1718                                                 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1719
1720                                                 q = image;
1721
1722                                                 // Convert the mlt frame to an AVPicture
1723                                                 for ( i = 0; i < height; i ++ )
1724                                                 {
1725                                                         p = input->data[ 0 ] + i * input->linesize[ 0 ];
1726                                                         memcpy( p, q, width * 2 );
1727                                                         q += width * 2;
1728                                                 }
1729
1730                                                 // Do the colour space conversion
1731 #ifdef SWSCALE
1732                                                 int flags = SWS_BICUBIC;
1733 #ifdef USE_MMX
1734                                                 flags |= SWS_CPU_CAPS_MMX;
1735 #endif
1736 #ifdef USE_SSE
1737                                                 flags |= SWS_CPU_CAPS_MMX2;
1738 #endif
1739                                                 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1740                                                         width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1741                                                 sws_scale( context, (const uint8_t* const*) input->data, input->linesize, 0, height,
1742                                                         output->data, output->linesize);
1743                                                 sws_freeContext( context );
1744 #else
1745                                                 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1746 #endif
1747
1748                                                 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1749
1750                                                 // Apply the alpha if applicable
1751                                                 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1752                                                 {
1753                                                         uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1754                                                         register int n;
1755
1756                                                         for ( i = 0; i < height; i ++ )
1757                                                         {
1758                                                                 n = ( width + 7 ) / 8;
1759                                                                 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1760
1761                                                                 switch( width % 8 )
1762                                                                 {
1763                                                                         case 0: do { *p = *alpha++; p += 4;
1764                                                                         case 7:          *p = *alpha++; p += 4;
1765                                                                         case 6:          *p = *alpha++; p += 4;
1766                                                                         case 5:          *p = *alpha++; p += 4;
1767                                                                         case 4:          *p = *alpha++; p += 4;
1768                                                                         case 3:          *p = *alpha++; p += 4;
1769                                                                         case 2:          *p = *alpha++; p += 4;
1770                                                                         case 1:          *p = *alpha++; p += 4;
1771                                                                                         }
1772                                                                                         while( --n );
1773                                                                 }
1774                                                         }
1775                                                 }
1776                                         }
1777
1778                                         if (oc->oformat->flags & AVFMT_RAWPICTURE) 
1779                                         {
1780                                                 // raw video case. The API will change slightly in the near future for that
1781                                                 AVPacket pkt;
1782                                                 av_init_packet(&pkt);
1783
1784                                                 pkt.flags |= PKT_FLAG_KEY;
1785                                                 pkt.stream_index= video_st->index;
1786                                                 pkt.data= (uint8_t *)output;
1787                                                 pkt.size= sizeof(AVPicture);
1788
1789                                                 ret = av_write_frame(oc, &pkt);
1790                                                 video_pts += c->frame_size;
1791                                         } 
1792                                         else 
1793                                         {
1794                                                 // Set the quality
1795                                                 output->quality = c->global_quality;
1796
1797                                                 // Set frame interlace hints
1798                                                 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1799                                                 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1800                                                 output->pts = frame_count;
1801
1802                                                 // Encode the image
1803                                                 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1804
1805                                                 // If zero size, it means the image was buffered
1806                                                 if ( out_size > 0 )
1807                                                 {
1808                                                         AVPacket pkt;
1809                                                         av_init_packet( &pkt );
1810
1811                                                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1812                                                                 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1813                                                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %"PRId64" frame pts %"PRId64, pkt.pts, c->coded_frame->pts );
1814                                                         if( c->coded_frame && c->coded_frame->key_frame )
1815                                                                 pkt.flags |= PKT_FLAG_KEY;
1816                                                         pkt.stream_index= video_st->index;
1817                                                         pkt.data= video_outbuf;
1818                                                         pkt.size= out_size;
1819
1820                                                         // write the compressed frame in the media file
1821                                                         ret = av_interleaved_write_frame(oc, &pkt);
1822                                                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1823                                                         video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1824                                                         
1825                                                         // Dual pass logging
1826                                                         if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1827                                                                 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1828                                                 } 
1829                                                 else if ( out_size < 0 )
1830                                                 {
1831                                                         mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1832                                                 }
1833                                         }
1834                                         frame_count++;
1835                                         if ( ret )
1836                                         {
1837                                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1838                                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1839                                                 goto on_fatal_error;
1840                                         }
1841                                         mlt_frame_close( frame );
1842                                         frame = NULL;
1843                                 }
1844                                 else
1845                                 {
1846                                         break;
1847                                 }
1848                         }
1849                         if ( audio_st[0] )
1850                                 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1851                         if ( video_st )
1852                                 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1853                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1854                 }
1855
1856                 if ( real_time_output == 1 && frames % 2 == 0 )
1857                 {
1858                         long passed = time_difference( &ante );
1859                         if ( fifo != NULL )
1860                         {
1861                                 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
1862                                 passed -= pending;
1863                         }
1864                         if ( passed < total_time )
1865                         {
1866                                 long total = ( total_time - passed );
1867                                 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1868                                 nanosleep( &t, NULL );
1869                         }
1870                 }
1871         }
1872
1873         // Flush the encoder buffers
1874         if ( real_time_output <= 0 )
1875         {
1876                 // Flush audio fifo
1877                 // TODO: flush all audio streams
1878                 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1879                 {
1880                         AVCodecContext *c = audio_st[0]->codec;
1881                         AVPacket pkt;
1882                         av_init_packet( &pkt );
1883                         pkt.size = 0;
1884
1885                         if ( fifo &&
1886                                 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) / sample_bytes ) )
1887                         {
1888                                 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size * sample_bytes );
1889                                 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, (short*) audio_buf_1 );
1890                         }
1891                         if ( pkt.size <= 0 )
1892                                 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1893                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1894                         if ( pkt.size <= 0 )
1895                                 break;
1896
1897                         // Write the compressed frame in the media file
1898                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1899                                 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1900                         pkt.flags |= PKT_FLAG_KEY;
1901                         pkt.stream_index = audio_st[0]->index;
1902                         pkt.data = audio_outbuf;
1903                         if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1904                         {
1905                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1906                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1907                                 goto on_fatal_error;
1908                         }
1909                 }
1910
1911                 // Flush video
1912                 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1913                 {
1914                         AVCodecContext *c = video_st->codec;
1915                         AVPacket pkt;
1916                         av_init_packet( &pkt );
1917
1918                         // Encode the image
1919                         pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1920                         mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1921                         if ( pkt.size <= 0 )
1922                                 break;
1923
1924                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1925                                 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1926                         if( c->coded_frame && c->coded_frame->key_frame )
1927                                 pkt.flags |= PKT_FLAG_KEY;
1928                         pkt.stream_index = video_st->index;
1929                         pkt.data = video_outbuf;
1930
1931                         // write the compressed frame in the media file
1932                         if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1933                         {
1934                                 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1935                                 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1936                                 goto on_fatal_error;
1937                         }
1938                         // Dual pass logging
1939                         if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1940                                 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1941                 }
1942         }
1943
1944 on_fatal_error:
1945         
1946         // Write the trailer, if any
1947         if ( frames )
1948                 av_write_trailer( oc );
1949
1950         // close each codec
1951         if ( video_st )
1952                 close_video(oc, video_st);
1953         for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1954                 close_audio( oc, audio_st[i] );
1955
1956         // Free the streams
1957         for ( i = 0; i < oc->nb_streams; i++ )
1958                 av_freep( &oc->streams[i] );
1959
1960         // Close the output file
1961         if ( !( fmt->flags & AVFMT_NOFILE ) &&
1962                 !mlt_properties_get_int( properties, "redirect" ) )
1963         {
1964 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1965                 if ( oc->pb  ) avio_close( oc->pb );
1966 #elif LIBAVFORMAT_VERSION_MAJOR >= 52
1967                 if ( oc->pb  ) url_fclose( oc->pb );
1968 #else
1969                 url_fclose( &oc->pb );
1970 #endif
1971         }
1972
1973         // Clean up input and output frames
1974         if ( output )
1975                 av_free( output->data[0] );
1976         av_free( output );
1977         av_free( input->data[0] );
1978         av_free( input );
1979         av_free( video_outbuf );
1980         av_free( audio_buf_1 );
1981         av_free( audio_buf_2 );
1982
1983         // Free the stream
1984         av_free( oc );
1985
1986         // Just in case we terminated on pause
1987         mlt_consumer_stopped( consumer );
1988         mlt_properties_close( frame_meta_properties );
1989
1990         if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1991         {
1992                 // Remove the dual pass log file
1993                 if ( mlt_properties_get( properties, "_logfilename" ) )
1994                         remove( mlt_properties_get( properties, "_logfilename" ) );
1995
1996                 // Remove the x264 dual pass logs
1997                 char *cwd = getcwd( NULL, 0 );
1998                 const char *file = "x264_2pass.log";
1999                 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2000                 sprintf( full, "%s/%s", cwd, file );
2001                 remove( full );
2002                 free( full );
2003                 file = "x264_2pass.log.temp";
2004                 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2005                 sprintf( full, "%s/%s", cwd, file );
2006                 remove( full );
2007                 free( full );
2008                 file = "x264_2pass.log.mbtree";
2009                 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2010                 sprintf( full, "%s/%s", cwd, file );
2011                 remove( full );
2012                 free( full );
2013                 free( cwd );
2014                 remove( "x264_2pass.log.temp" );
2015         }
2016
2017         while ( ( frame = mlt_deque_pop_back( queue ) ) )
2018                 mlt_frame_close( frame );
2019
2020         return NULL;
2021 }
2022
2023 /** Close the consumer.
2024 */
2025
2026 static void consumer_close( mlt_consumer consumer )
2027 {
2028         // Stop the consumer
2029         mlt_consumer_stop( consumer );
2030
2031         // Close the parent
2032         mlt_consumer_close( consumer );
2033
2034         // Free the memory
2035         free( consumer );
2036 }