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