]> git.sesse.net Git - mlt/blob - src/modules/avformat/consumer_avformat.c
Make realtime (streaming) avformat consumer less bursty.
[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
28 // System header files
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <limits.h>
33 #include <pthread.h>
34 #include <sys/time.h>
35 #include <unistd.h>
36
37 // avformat header files
38 #include <avformat.h>
39 #ifdef SWSCALE
40 #include <swscale.h>
41 #endif
42 #include <opt.h>
43
44 #if LIBAVUTIL_VERSION_INT < (50<<16)
45 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
46 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
47 #endif
48
49 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2)
50
51 //
52 // This structure should be extended and made globally available in mlt
53 //
54
55 typedef struct
56 {
57         int16_t *buffer;
58         int size;
59         int used;
60         double time;
61         int frequency;
62         int channels;
63 }
64 *sample_fifo, sample_fifo_s;
65
66 sample_fifo sample_fifo_init( int frequency, int channels )
67 {
68         sample_fifo this = calloc( 1, sizeof( sample_fifo_s ) );
69         this->frequency = frequency;
70         this->channels = channels;
71         return this;
72 }
73
74 // sample_fifo_clear and check are temporarily aborted (not working as intended)
75
76 void sample_fifo_clear( sample_fifo this, double time )
77 {
78         int words = ( float )( time - this->time ) * this->frequency * this->channels;
79         if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) && this->used > words && words > 0 )
80         {
81                 memmove( this->buffer, &this->buffer[ words ], ( this->used - words ) * sizeof( int16_t ) );
82                 this->used -= words;
83                 this->time = time;
84         }
85         else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )this->time * 100 ) )
86         {
87                 this->used = 0;
88                 this->time = time;
89         }
90 }
91
92 void sample_fifo_check( sample_fifo this, double time )
93 {
94         if ( this->used == 0 )
95         {
96                 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) )
97                         this->time = time;
98         }
99 }
100
101 void sample_fifo_append( sample_fifo this, int16_t *samples, int count )
102 {
103         if ( ( this->size - this->used ) < count )
104         {
105                 this->size += count * 5;
106                 this->buffer = realloc( this->buffer, this->size * sizeof( int16_t ) );
107         }
108
109         memcpy( &this->buffer[ this->used ], samples, count * sizeof( int16_t ) );
110         this->used += count;
111 }
112
113 int sample_fifo_used( sample_fifo this )
114 {
115         return this->used;
116 }
117
118 int sample_fifo_fetch( sample_fifo this, int16_t *samples, int count )
119 {
120         if ( count > this->used )
121                 count = this->used;
122
123         memcpy( samples, this->buffer, count * sizeof( int16_t ) );
124         this->used -= count;
125         memmove( this->buffer, &this->buffer[ count ], this->used * sizeof( int16_t ) );
126
127         this->time += ( double )count / this->channels / this->frequency;
128
129         return count;
130 }
131
132 void sample_fifo_close( sample_fifo this )
133 {
134         free( this->buffer );
135         free( this );
136 }
137
138 // Forward references.
139 static int consumer_start( mlt_consumer this );
140 static int consumer_stop( mlt_consumer this );
141 static int consumer_is_stopped( mlt_consumer this );
142 static void *consumer_thread( void *arg );
143 static void consumer_close( mlt_consumer this );
144
145 /** Initialise the dv consumer.
146 */
147
148 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
149 {
150         // Allocate the consumer
151         mlt_consumer this = mlt_consumer_new( profile );
152
153         // If memory allocated and initialises without error
154         if ( this != NULL )
155         {
156                 // Get properties from the consumer
157                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
158
159                 // Assign close callback
160                 this->close = consumer_close;
161
162                 // Interpret the argument
163                 if ( arg != NULL )
164                         mlt_properties_set( properties, "target", arg );
165
166                 // sample and frame queue
167                 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
168
169                 // Audio options not fully handled by AVOptions
170 #define QSCALE_NONE (-99999)
171                 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
172                 
173                 // Video options not fully handled by AVOptions
174                 mlt_properties_set_int( properties, "dc", 8 );
175                 
176                 // Muxer options not fully handled by AVOptions
177                 mlt_properties_set_double( properties, "muxdelay", 0.7 );
178                 mlt_properties_set_double( properties, "muxpreload", 0.5 );
179
180                 // Ensure termination at end of the stream
181                 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
182                 
183                 // Default to separate processing threads for producer and consumer with no frame dropping!
184                 mlt_properties_set_int( properties, "real_time", -1 );
185                 mlt_properties_set_int( properties, "prefill", 1 );
186
187                 // Set up start/stop/terminated callbacks
188                 this->start = consumer_start;
189                 this->stop = consumer_stop;
190                 this->is_stopped = consumer_is_stopped;
191         }
192
193         // Return this
194         return this;
195 }
196
197 /** Start the consumer.
198 */
199
200 static int consumer_start( mlt_consumer this )
201 {
202         // Get the properties
203         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
204         int error = 0;
205
206         // Report information about available muxers and codecs as YAML Tiny
207         char *s = mlt_properties_get( properties, "f" );
208         if ( s && strcmp( s, "list" ) == 0 )
209         {
210                 fprintf( stderr, "---\nformats:\n" );
211                 AVOutputFormat *format = NULL;
212                 while ( ( format = av_oformat_next( format ) ) )
213                         fprintf( stderr, "  - %s\n", format->name );
214                 fprintf( stderr, "...\n" );
215                 error = 1;
216         }
217         s = mlt_properties_get( properties, "acodec" );
218         if ( s && strcmp( s, "list" ) == 0 )
219         {
220                 fprintf( stderr, "---\naudio_codecs:\n" );
221                 AVCodec *codec = NULL;
222                 while ( ( codec = av_codec_next( codec ) ) )
223                         if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
224                                 fprintf( stderr, "  - %s\n", codec->name );
225                 fprintf( stderr, "...\n" );
226                 error = 1;
227         }
228         s = mlt_properties_get( properties, "vcodec" );
229         if ( s && strcmp( s, "list" ) == 0 )
230         {
231                 fprintf( stderr, "---\nvideo_codecs:\n" );
232                 AVCodec *codec = NULL;
233                 while ( ( codec = av_codec_next( codec ) ) )
234                         if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
235                                 fprintf( stderr, "  - %s\n", codec->name );
236                 fprintf( stderr, "...\n" );
237                 error = 1;
238         }
239
240         // Check that we're not already running
241         if ( !error && !mlt_properties_get_int( properties, "running" ) )
242         {
243                 // Allocate a thread
244                 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
245
246                 // Get the width and height
247                 int width = mlt_properties_get_int( properties, "width" );
248                 int height = mlt_properties_get_int( properties, "height" );
249
250                 // Obtain the size property
251                 char *size = mlt_properties_get( properties, "s" );
252
253                 // Interpret it
254                 if ( size != NULL )
255                 {
256                         int tw, th;
257                         if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
258                         {
259                                 width = tw;
260                                 height = th;
261                         }
262                         else
263                         {
264                                 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "Invalid size property %s - ignoring.\n", size );
265                         }
266                 }
267                 
268                 // Now ensure we honour the multiple of two requested by libavformat
269                 width = ( width / 2 ) * 2;
270                 height = ( height / 2 ) * 2;
271                 mlt_properties_set_int( properties, "width", width );
272                 mlt_properties_set_int( properties, "height", height );
273
274                 // We need to set these on the profile as well because the s property is
275                 // an alias to mlt properties that correspond to profile settings.
276                 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
277                 if ( profile )
278                 {
279                         profile->width = width;
280                         profile->height = height;
281                 }
282
283                 // Handle the ffmpeg command line "-r" property for frame rate
284                 if ( mlt_properties_get( properties, "r" ) )
285                 {
286                         double frame_rate = mlt_properties_get_double( properties, "r" );
287                         AVRational rational = av_d2q( frame_rate, 255 );
288                         mlt_properties_set_int( properties, "frame_rate_num", rational.num );
289                         mlt_properties_set_int( properties, "frame_rate_den", rational.den );
290                         if ( profile )
291                         {
292                                 profile->frame_rate_num = rational.num;
293                                 profile->frame_rate_den = rational.den;
294                                 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
295                         }
296                 }
297                 
298                 // Apply AVOptions that are synonyms for standard mlt_consumer options
299                 if ( mlt_properties_get( properties, "ac" ) )
300                         mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
301                 if ( mlt_properties_get( properties, "ar" ) )
302                         mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
303
304                 // Assign the thread to properties
305                 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
306
307                 // Set the running state
308                 mlt_properties_set_int( properties, "running", 1 );
309
310                 // Create the thread
311                 pthread_create( thread, NULL, consumer_thread, this );
312         }
313         return error;
314 }
315
316 /** Stop the consumer.
317 */
318
319 static int consumer_stop( mlt_consumer this )
320 {
321         // Get the properties
322         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
323
324         // Check that we're running
325         if ( mlt_properties_get_int( properties, "running" ) )
326         {
327                 // Get the thread
328                 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
329
330                 // Stop the thread
331                 mlt_properties_set_int( properties, "running", 0 );
332
333                 // Wait for termination
334                 pthread_join( *thread, NULL );
335         }
336
337         return 0;
338 }
339
340 /** Determine if the consumer is stopped.
341 */
342
343 static int consumer_is_stopped( mlt_consumer this )
344 {
345         // Get the properties
346         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
347         return !mlt_properties_get_int( properties, "running" );
348 }
349
350 /** Process properties as AVOptions and apply to AV context obj
351 */
352
353 static void apply_properties( void *obj, mlt_properties properties, int flags, int alloc )
354 {
355         int i;
356         int count = mlt_properties_count( properties ); 
357         for ( i = 0; i < count; i++ )
358         {
359                 const char *opt_name = mlt_properties_get_name( properties, i );
360                 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
361                 if ( opt != NULL )
362 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
363                         av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), alloc, NULL );
364 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
365                         av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), alloc );
366 #else
367                         av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
368 #endif
369         }
370 }
371
372 /** Add an audio output stream
373 */
374
375 static AVStream *add_audio_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
376 {
377         // Get the properties
378         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
379
380         // Create a new stream
381         AVStream *st = av_new_stream( oc, 1 );
382
383         // If created, then initialise from properties
384         if ( st != NULL ) 
385         {
386                 AVCodecContext *c = st->codec;
387
388                 // Establish defaults from AVOptions
389                 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
390
391                 c->codec_id = codec_id;
392                 c->codec_type = CODEC_TYPE_AUDIO;
393                 c->sample_fmt = SAMPLE_FMT_S16;
394
395 #if 0 // disabled until some audio codecs are multi-threaded
396                 // Setup multi-threading
397                 int thread_count = mlt_properties_get_int( properties, "threads" );
398                 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
399                         thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
400                 if ( thread_count > 1 )
401                         avcodec_thread_init( c, thread_count );         
402 #endif
403         
404                 if (oc->oformat->flags & AVFMT_GLOBALHEADER) 
405                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
406                 
407                 // Allow the user to override the audio fourcc
408                 if ( mlt_properties_get( properties, "atag" ) )
409                 {
410                         char *tail = NULL;
411                         char *arg = mlt_properties_get( properties, "atag" );
412                         int tag = strtol( arg, &tail, 0);
413                         if( !tail || *tail )
414                                 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
415                         c->codec_tag = tag;
416                 }
417
418                 // Process properties as AVOptions
419                 char *apre = mlt_properties_get( properties, "apre" );
420                 if ( apre )
421                 {
422                         mlt_properties p = mlt_properties_load( apre );
423                         apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
424                         mlt_properties_close( p );
425                 }
426                 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
427
428                 int audio_qscale = mlt_properties_get_int( properties, "aq" );
429         if ( audio_qscale > QSCALE_NONE )
430                 {
431                         c->flags |= CODEC_FLAG_QSCALE;
432                         c->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
433                 }
434
435                 // Set parameters controlled by MLT
436                 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
437                 c->time_base = ( AVRational ){ 1, c->sample_rate };
438                 c->channels = mlt_properties_get_int( properties, "channels" );
439
440                 if ( mlt_properties_get( properties, "alang" ) != NULL )
441                         strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
442         }
443         else
444         {
445                 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not allocate a stream for audio\n" );
446         }
447
448         return st;
449 }
450
451 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
452 {
453         // We will return the audio input size from here
454         int audio_input_frame_size = 0;
455
456         // Get the context
457         AVCodecContext *c = st->codec;
458
459         // Find the encoder
460         AVCodec *codec = avcodec_find_encoder( c->codec_id );
461
462         // Continue if codec found and we can open it
463         if ( codec != NULL && avcodec_open( c, codec ) >= 0 )
464         {
465                 // ugly hack for PCM codecs (will be removed ASAP with new PCM
466                 // support to compute the input frame size in samples
467                 if ( c->frame_size <= 1 ) 
468                 {
469                         audio_input_frame_size = audio_outbuf_size / c->channels;
470                         switch(st->codec->codec_id) 
471                         {
472                                 case CODEC_ID_PCM_S16LE:
473                                 case CODEC_ID_PCM_S16BE:
474                                 case CODEC_ID_PCM_U16LE:
475                                 case CODEC_ID_PCM_U16BE:
476                                         audio_input_frame_size >>= 1;
477                                         break;
478                                 default:
479                                         break;
480                         }
481                 } 
482                 else 
483                 {
484                         audio_input_frame_size = c->frame_size;
485                 }
486
487                 // Some formats want stream headers to be seperate (hmm)
488                 if ( !strcmp( oc->oformat->name, "mp4" ) ||
489                          !strcmp( oc->oformat->name, "mov" ) ||
490                          !strcmp( oc->oformat->name, "3gp" ) )
491                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
492         }
493         else
494         {
495                 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
496         }
497
498         return audio_input_frame_size;
499 }
500
501 static void close_audio( AVFormatContext *oc, AVStream *st )
502 {
503         if ( st && st->codec )
504                 avcodec_close( st->codec );
505 }
506
507 /** Add a video output stream 
508 */
509
510 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
511 {
512         // Get the properties
513         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
514
515         // Create a new stream
516         AVStream *st = av_new_stream( oc, 0 );
517
518         if ( st != NULL ) 
519         {
520                 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
521                 AVCodecContext *c = st->codec;
522
523                 // Establish defaults from AVOptions
524                 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
525
526                 c->codec_id = codec_id;
527                 c->codec_type = CODEC_TYPE_VIDEO;
528                 
529                 // Setup multi-threading
530                 int thread_count = mlt_properties_get_int( properties, "threads" );
531                 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
532                         thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
533                 if ( thread_count > 1 )
534                         avcodec_thread_init( c, thread_count );         
535         
536                 // Process properties as AVOptions
537                 char *vpre = mlt_properties_get( properties, "vpre" );
538                 if ( vpre )
539                 {
540                         mlt_properties p = mlt_properties_load( vpre );
541                         apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
542                         mlt_properties_close( p );
543                 }
544                 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
545
546                 // Set options controlled by MLT
547                 c->width = mlt_properties_get_int( properties, "width" );
548                 c->height = mlt_properties_get_int( properties, "height" );
549                 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
550                 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
551                 if ( st->time_base.den == 0 )
552                         st->time_base = c->time_base;
553                 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
554
555                 if ( mlt_properties_get( properties, "aspect" ) )
556                 {
557                         // "-aspect" on ffmpeg command line is display aspect ratio
558                         double ar = mlt_properties_get_double( properties, "aspect" );
559                         AVRational rational = av_d2q( ar, 255 );
560
561                         // Update the profile and properties as well since this is an alias 
562                         // for mlt properties that correspond to profile settings
563                         mlt_properties_set_int( properties, "display_aspect_num", rational.num );
564                         mlt_properties_set_int( properties, "display_aspect_den", rational.den );
565                         mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
566                         if ( profile )
567                         {
568                                 profile->display_aspect_num = rational.num;
569                                 profile->display_aspect_den = rational.den;
570                                 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
571                         }
572
573                         // Now compute the sample aspect ratio
574                         rational = av_d2q( ar * c->height / c->width, 255 );
575                         c->sample_aspect_ratio = rational;
576                         // Update the profile and properties as well since this is an alias 
577                         // for mlt properties that correspond to profile settings
578                         mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
579                         mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
580                         if ( profile )
581                         {
582                                 profile->sample_aspect_num = rational.num;
583                                 profile->sample_aspect_den = rational.den;
584                                 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
585                         }
586                 }
587                 else
588                 {
589                         c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
590                         c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
591                 }
592 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
593                 st->sample_aspect_ratio = c->sample_aspect_ratio;
594 #endif
595
596                 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
597                 {
598                         c->flags |= CODEC_FLAG_QSCALE;
599                         st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
600                 }
601
602                 // Allow the user to override the video fourcc
603                 if ( mlt_properties_get( properties, "vtag" ) )
604                 {
605                         char *tail = NULL;
606                         const char *arg = mlt_properties_get( properties, "vtag" );
607                         int tag = strtol( arg, &tail, 0);
608                         if( !tail || *tail )
609                                 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
610                         c->codec_tag = tag;
611                 }
612
613                 // Some formats want stream headers to be seperate
614                 if ( oc->oformat->flags & AVFMT_GLOBALHEADER ) 
615                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
616
617                 // Translate these standard mlt consumer properties to ffmpeg
618                 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
619                      mlt_properties_get_int( properties, "deinterlace" ) == 0 )
620                 {
621                         if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
622                                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
623                         if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
624                                 c->flags |= CODEC_FLAG_INTERLACED_ME;
625                 }
626                 
627                 // parse the ratecontrol override string
628                 int i;
629                 char *rc_override = mlt_properties_get( properties, "rc_override" );
630                 for ( i = 0; rc_override; i++ )
631                 {
632                         int start, end, q;
633                         int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
634                         if ( e != 3 )
635                                 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "Error parsing rc_override\n" );
636                         c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
637                         c->rc_override[i].start_frame = start;
638                         c->rc_override[i].end_frame = end;
639                         if ( q > 0 )
640                         {
641                                 c->rc_override[i].qscale = q;
642                                 c->rc_override[i].quality_factor = 1.0;
643                         }
644                         else
645                         {
646                                 c->rc_override[i].qscale = 0;
647                                 c->rc_override[i].quality_factor = -q / 100.0;
648                         }
649                         rc_override = strchr( rc_override, '/' );
650                         if ( rc_override )
651                                 rc_override++;
652                 }
653                 c->rc_override_count = i;
654                 if ( !c->rc_initial_buffer_occupancy )
655                         c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
656                 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
657
658                 // Setup dual-pass
659                 i = mlt_properties_get_int( properties, "pass" );
660                 if ( i == 1 )
661                         c->flags |= CODEC_FLAG_PASS1;
662                 else if ( i == 2 )
663                         c->flags |= CODEC_FLAG_PASS2;
664                 if ( codec_id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
665                 {
666                         char logfilename[1024];
667                         FILE *f;
668                         int size;
669                         char *logbuffer;
670
671                         snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
672                                 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
673                         if ( c->flags & CODEC_FLAG_PASS1 )
674                         {
675                                 f = fopen( logfilename, "w" );
676                                 if ( !f )
677                                         perror( logfilename );
678                                 else
679                                         mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
680                         }
681                         else
682                         {
683                                 /* read the log file */
684                                 f = fopen( logfilename, "r" );
685                                 if ( !f )
686                                 {
687                                         perror(logfilename);
688                                 }
689                                 else
690                                 {
691                                         mlt_properties_set( properties, "_logfilename", logfilename );
692                                         fseek( f, 0, SEEK_END );
693                                         size = ftell( f );
694                                         fseek( f, 0, SEEK_SET );
695                                         logbuffer = av_malloc( size + 1 );
696                                         if ( !logbuffer )
697                                                 mlt_log_fatal( MLT_CONSUMER_SERVICE( this ), "Could not allocate log buffer\n" );
698                                         else
699                                         {
700                                                 size = fread( logbuffer, 1, size, f );
701                                                 fclose( f );
702                                                 logbuffer[size] = '\0';
703                                                 c->stats_in = logbuffer;
704                                                 mlt_properties_set_data( properties, "_logbuffer", logbuffer, 0, ( mlt_destructor )av_free, NULL );
705                                         }
706                                 }
707                         }
708                 }
709         }
710         else
711         {
712                 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not allocate a stream for video\n" );
713         }
714  
715         return st;
716 }
717
718 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
719 {
720         // Allocate a frame
721         AVFrame *picture = avcodec_alloc_frame();
722
723         // Determine size of the 
724         int size = avpicture_get_size(pix_fmt, width, height);
725
726         // Allocate the picture buf
727         uint8_t *picture_buf = av_malloc(size);
728
729         // If we have both, then fill the image
730         if ( picture != NULL && picture_buf != NULL )
731         {
732                 // Fill the frame with the allocated buffer
733                 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
734         }
735         else
736         {
737                 // Something failed - clean up what we can
738                 av_free( picture );
739                 av_free( picture_buf );
740                 picture = NULL;
741         }
742
743         return picture;
744 }
745         
746 static int open_video(AVFormatContext *oc, AVStream *st)
747 {
748         // Get the codec
749         AVCodecContext *video_enc = st->codec;
750
751         // find the video encoder
752         AVCodec *codec = avcodec_find_encoder( video_enc->codec_id );
753
754         if( codec && codec->pix_fmts )
755         {
756                 const enum PixelFormat *p = codec->pix_fmts;
757                 for( ; *p!=-1; p++ )
758                 {
759                         if( *p == video_enc->pix_fmt )
760                                 break;
761                 }
762                 if( *p == -1 )
763                         video_enc->pix_fmt = codec->pix_fmts[ 0 ];
764         }
765
766         // Open the codec safely
767         return codec != NULL && avcodec_open( video_enc, codec ) >= 0;
768 }
769
770 void close_video(AVFormatContext *oc, AVStream *st)
771 {
772         if ( st && st->codec )
773                 avcodec_close(st->codec);
774 }
775
776 static inline long time_difference( struct timeval *time1 )
777 {
778         struct timeval time2;
779         gettimeofday( &time2, NULL );
780         return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
781 }
782
783 /** The main thread - the argument is simply the consumer.
784 */
785
786 static void *consumer_thread( void *arg )
787 {
788         // Map the argument to the object
789         mlt_consumer this = arg;
790
791         // Get the properties
792         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
793
794         // Get the terminate on pause property
795         int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
796         int terminated = 0;
797
798         // Determine if feed is slow (for realtime stuff)
799         int real_time_output = mlt_properties_get_int( properties, "real_time" );
800
801         // Time structures
802         struct timeval ante;
803
804         // Get the frame rate
805         double fps = mlt_properties_get_double( properties, "fps" );
806
807         // Get width and height
808         int width = mlt_properties_get_int( properties, "width" );
809         int height = mlt_properties_get_int( properties, "height" );
810         int img_width = width;
811         int img_height = height;
812
813         // Get default audio properties
814         mlt_audio_format aud_fmt = mlt_audio_s16;
815         int channels = mlt_properties_get_int( properties, "channels" );
816         int frequency = mlt_properties_get_int( properties, "frequency" );
817         int16_t *pcm = NULL;
818         int samples = 0;
819
820         // AVFormat audio buffer and frame size
821         int audio_outbuf_size = ( 1024 * 42 );
822         uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
823         int audio_input_frame_size = 0;
824
825         // AVFormat video buffer and frame count
826         int frame_count = 0;
827         int video_outbuf_size = ( 1024 * 1024 );
828         uint8_t *video_outbuf = av_malloc( video_outbuf_size );
829
830         // Used for the frame properties
831         mlt_frame frame = NULL;
832         mlt_properties frame_properties = NULL;
833
834         // Get the queues
835         mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
836         sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
837
838         // Need two av pictures for converting
839         AVFrame *output = NULL;
840         AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
841
842         // For receiving images from an mlt_frame
843         uint8_t *image;
844         mlt_image_format img_fmt = mlt_image_yuv422;
845
846         // For receiving audio samples back from the fifo
847         int16_t *buffer = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
848         int count = 0;
849
850         // Allocate the context
851 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
852         AVFormatContext *oc = avformat_alloc_context( );
853 #else
854         AVFormatContext *oc = av_alloc_format_context( );
855 #endif
856
857         // Streams
858         AVStream *audio_st = NULL;
859         AVStream *video_st = NULL;
860
861         // Time stamps
862         double audio_pts = 0;
863         double video_pts = 0;
864
865         // Loop variable
866         int i;
867
868         // Frames despatched
869         long int frames = 0;
870         long int total_time = 0;
871
872         // Determine the format
873         AVOutputFormat *fmt = NULL;
874         const char *filename = mlt_properties_get( properties, "target" );
875         char *format = mlt_properties_get( properties, "f" );
876         char *vcodec = mlt_properties_get( properties, "vcodec" );
877         char *acodec = mlt_properties_get( properties, "acodec" );
878         
879         // Used to store and override codec ids
880         int audio_codec_id;
881         int video_codec_id;
882
883         // Check for user selected format first
884         if ( format != NULL )
885 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
886                 fmt = guess_format( format, NULL, NULL );
887 #else
888                 fmt = av_guess_format( format, NULL, NULL );
889 #endif
890
891         // Otherwise check on the filename
892         if ( fmt == NULL && filename != NULL )
893 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
894                 fmt = guess_format( NULL, filename, NULL );
895 #else
896                 fmt = av_guess_format( NULL, filename, NULL );
897 #endif
898
899         // Otherwise default to mpeg
900         if ( fmt == NULL )
901 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
902                 fmt = guess_format( "mpeg", NULL, NULL );
903 #else
904                 fmt = av_guess_format( "mpeg", NULL, NULL );
905 #endif
906
907         // We need a filename - default to stdout?
908         if ( filename == NULL || !strcmp( filename, "" ) )
909                 filename = "pipe:";
910
911         // Get the codec ids selected
912         audio_codec_id = fmt->audio_codec;
913         video_codec_id = fmt->video_codec;
914
915         // Check for audio codec overides
916         if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
917                 audio_codec_id = CODEC_ID_NONE;
918         else if ( acodec )
919         {
920                 AVCodec *p = avcodec_find_encoder_by_name( acodec );
921                 if ( p != NULL )
922                         audio_codec_id = p->id;
923                 else
924                         mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "audio codec %s unrecognised - ignoring\n", acodec );
925         }
926
927         // Check for video codec overides
928         if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
929                 video_codec_id = CODEC_ID_NONE;
930         else if ( vcodec )
931         {
932                 AVCodec *p = avcodec_find_encoder_by_name( vcodec );
933                 if ( p != NULL )
934                         video_codec_id = p->id;
935                 else
936                         mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "video codec %s unrecognised - ignoring\n", vcodec );
937         }
938
939         // Write metadata
940         char *tmp = NULL;
941         int metavalue;
942
943         tmp = mlt_properties_get( properties, "meta.attr.title.markup");
944         if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
945
946         tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
947         if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
948
949         tmp = mlt_properties_get( properties, "meta.attr.author.markup");
950         if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
951
952         tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
953         if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
954
955         tmp = mlt_properties_get( properties, "meta.attr.album.markup");
956         if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
957
958         metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
959         if (metavalue != 0) oc->year = metavalue;
960
961         metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
962         if (metavalue != 0) oc->track = metavalue;
963
964         oc->oformat = fmt;
965         snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
966
967         // Add audio and video streams 
968         if ( video_codec_id != CODEC_ID_NONE )
969                 video_st = add_video_stream( this, oc, video_codec_id );
970         if ( audio_codec_id != CODEC_ID_NONE )
971                 audio_st = add_audio_stream( this, oc, audio_codec_id );
972
973         // Set the parameters (even though we have none...)
974         if ( av_set_parameters(oc, NULL) >= 0 ) 
975         {
976                 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
977                 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
978
979                 // Process properties as AVOptions
980                 char *fpre = mlt_properties_get( properties, "fpre" );
981                 if ( fpre )
982                 {
983                         mlt_properties p = mlt_properties_load( fpre );
984                         apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM, 1 );
985                         mlt_properties_close( p );
986                 }
987                 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM, 0 );
988
989                 if ( video_st && !open_video( oc, video_st ) )
990                         video_st = NULL;
991                 if ( audio_st )
992                 {
993                         audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
994                         if ( !audio_input_frame_size )
995                                 audio_st = NULL;
996                 }
997
998                 // Open the output file, if needed
999                 if ( !( fmt->flags & AVFMT_NOFILE ) ) 
1000                 {
1001                         if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 ) 
1002                         {
1003                                 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not open '%s'\n", filename );
1004                                 mlt_properties_set_int( properties, "running", 0 );
1005                         }
1006                 }
1007         
1008                 // Write the stream header, if any
1009                 if ( mlt_properties_get_int( properties, "running" ) )
1010                         av_write_header( oc );
1011         }
1012         else
1013         {
1014                 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Invalid output format parameters\n" );
1015                 mlt_properties_set_int( properties, "running", 0 );
1016         }
1017
1018         // Allocate picture
1019         if ( video_st )
1020                 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1021
1022         // Last check - need at least one stream
1023         if ( audio_st == NULL && video_st == NULL )
1024                 mlt_properties_set_int( properties, "running", 0 );
1025
1026         // Get the starting time (can ignore the times above)
1027         gettimeofday( &ante, NULL );
1028
1029         // Loop while running
1030         while( mlt_properties_get_int( properties, "running" ) &&
1031                ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1032         {
1033                 // Get the frame
1034                 frame = mlt_consumer_rt_frame( this );
1035
1036                 // Check that we have a frame to work with
1037                 if ( frame != NULL )
1038                 {
1039                         // Increment frames despatched
1040                         frames ++;
1041
1042                         // Default audio args
1043                         frame_properties = MLT_FRAME_PROPERTIES( frame );
1044
1045                         // Check for the terminated condition
1046                         terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1047
1048                         // Get audio and append to the fifo
1049                         if ( !terminated && audio_st )
1050                         {
1051                                 samples = mlt_sample_calculator( fps, frequency, count ++ );
1052                                 mlt_frame_get_audio( frame, (void**) &pcm, &aud_fmt, &frequency, &channels, &samples );
1053
1054                                 // Create the fifo if we don't have one
1055                                 if ( fifo == NULL )
1056                                 {
1057                                         fifo = sample_fifo_init( frequency, channels );
1058                                         mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1059                                 }
1060
1061                                 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1062                                         memset( pcm, 0, samples * channels * 2 );
1063
1064                                 // Append the samples
1065                                 sample_fifo_append( fifo, pcm, samples * channels );
1066                                 total_time += ( samples * 1000000 ) / frequency;
1067                         }
1068
1069                         // Encode the image
1070                         if ( !terminated && video_st )
1071                                 mlt_deque_push_back( queue, frame );
1072                         else
1073                                 mlt_frame_close( frame );
1074                 }
1075
1076                 // While we have stuff to process, process...
1077                 while ( 1 )
1078                 {
1079                         // Write interleaved audio and video frames
1080                         if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
1081                         {
1082                                 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1083                                 {
1084                                         AVCodecContext *c = audio_st->codec;
1085                                         AVPacket pkt;
1086                                         int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) ), AUDIO_ENCODE_BUFFER_SIZE );
1087
1088                                         if ( n > 0 )
1089                                                 sample_fifo_fetch( fifo, buffer, n );
1090                                         else
1091                                                 memset( buffer, 0, AUDIO_ENCODE_BUFFER_SIZE );
1092                                         
1093                                         av_init_packet( &pkt );
1094                                         pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
1095                                         
1096                                         // Write the compressed frame in the media file
1097                                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1098                                         {
1099                                                 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
1100                                                 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "audio pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1101                                         }
1102                                         pkt.flags |= PKT_FLAG_KEY;
1103                                         pkt.stream_index= audio_st->index;
1104                                         pkt.data= audio_outbuf;
1105
1106                                         if ( pkt.size > 0 )
1107                                                 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1108                                                         mlt_log_error( MLT_CONSUMER_SERVICE( this ), "error writing audio frame\n" );
1109
1110                                         mlt_log_debug( MLT_CONSUMER_SERVICE( this ), " frame_size %d\n", c->frame_size );
1111                                         if ( audio_codec_id == CODEC_ID_VORBIS )
1112                                                 audio_pts = (double)c->coded_frame->pts * av_q2d( audio_st->time_base );
1113                                         else
1114                                                 audio_pts = (double)audio_st->pts.val * av_q2d( audio_st->time_base );
1115                                 }
1116                                 else
1117                                 {
1118                                         break;
1119                                 }
1120                         }
1121                         else if ( video_st )
1122                         {
1123                                 if ( mlt_deque_count( queue ) )
1124                                 {
1125                                         int out_size, ret;
1126                                         AVCodecContext *c;
1127
1128                                         frame = mlt_deque_pop_front( queue );
1129                                         frame_properties = MLT_FRAME_PROPERTIES( frame );
1130
1131                                         c = video_st->codec;
1132                                         
1133                                         if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1134                                         {
1135                                                 int i = 0;
1136                                                 int j = 0;
1137                                                 uint8_t *p;
1138                                                 uint8_t *q;
1139
1140                                                 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1141
1142                                                 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1143
1144                                                 q = image;
1145
1146                                                 // Convert the mlt frame to an AVPicture
1147                                                 for ( i = 0; i < height; i ++ )
1148                                                 {
1149                                                         p = input->data[ 0 ] + i * input->linesize[ 0 ];
1150                                                         j = width;
1151                                                         while( j -- )
1152                                                         {
1153                                                                 *p ++ = *q ++;
1154                                                                 *p ++ = *q ++;
1155                                                         }
1156                                                 }
1157
1158                                                 // Do the colour space conversion
1159 #ifdef SWSCALE
1160                                                 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1161                                                         width, height, video_st->codec->pix_fmt, SWS_FAST_BILINEAR, NULL, NULL, NULL);
1162                                                 sws_scale( context, input->data, input->linesize, 0, height,
1163                                                         output->data, output->linesize);
1164                                                 sws_freeContext( context );
1165 #else
1166                                                 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1167 #endif
1168
1169                                                 // Apply the alpha if applicable
1170                                                 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1171                                                 {
1172                                                         uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1173                                                         register int n;
1174
1175                                                         for ( i = 0; i < height; i ++ )
1176                                                         {
1177                                                                 n = ( width + 7 ) / 8;
1178                                                                 p = output->data[ 0 ] + i * output->linesize[ 0 ];
1179
1180                                                                 #ifndef __DARWIN__
1181                                                                 p += 3;
1182                                                                 #endif
1183
1184                                                                 switch( width % 8 )
1185                                                                 {
1186                                                                         case 0: do { *p = *alpha++; p += 4;
1187                                                                         case 7:          *p = *alpha++; p += 4;
1188                                                                         case 6:          *p = *alpha++; p += 4;
1189                                                                         case 5:          *p = *alpha++; p += 4;
1190                                                                         case 4:          *p = *alpha++; p += 4;
1191                                                                         case 3:          *p = *alpha++; p += 4;
1192                                                                         case 2:          *p = *alpha++; p += 4;
1193                                                                         case 1:          *p = *alpha++; p += 4;
1194                                                                                         }
1195                                                                                         while( --n );
1196                                                                 }
1197                                                         }
1198                                                 }
1199                                         }
1200
1201                                         if (oc->oformat->flags & AVFMT_RAWPICTURE) 
1202                                         {
1203                                                 // raw video case. The API will change slightly in the near future for that
1204                                                 AVPacket pkt;
1205                                                 av_init_packet(&pkt);
1206
1207                                                 pkt.flags |= PKT_FLAG_KEY;
1208                                                 pkt.stream_index= video_st->index;
1209                                                 pkt.data= (uint8_t *)output;
1210                                                 pkt.size= sizeof(AVPicture);
1211
1212                                                 ret = av_write_frame(oc, &pkt);
1213                                                 video_pts += c->frame_size;
1214                                         } 
1215                                         else 
1216                                         {
1217                                                 // Set the quality
1218                                                 output->quality = video_st->quality;
1219
1220                                                 // Set frame interlace hints
1221                                                 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1222                                                 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1223                                                 output->pts = frame_count;
1224
1225                                                 // Encode the image
1226                                                 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1227
1228                                                 // If zero size, it means the image was buffered
1229                                                 if ( out_size > 0 )
1230                                                 {
1231                                                         AVPacket pkt;
1232                                                         av_init_packet( &pkt );
1233
1234                                                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1235                                                                 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1236                                                         mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "video pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1237                                                         if( c->coded_frame && c->coded_frame->key_frame )
1238                                                                 pkt.flags |= PKT_FLAG_KEY;
1239                                                         pkt.stream_index= video_st->index;
1240                                                         pkt.data= video_outbuf;
1241                                                         pkt.size= out_size;
1242
1243                                                         // write the compressed frame in the media file
1244                                                         ret = av_interleaved_write_frame(oc, &pkt);
1245                                                         mlt_log_debug( MLT_CONSUMER_SERVICE( this ), " frame_size %d\n", c->frame_size );
1246                                                         video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1247                                                         
1248                                                         // Dual pass logging
1249                                                         if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1250                                                                 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1251                                                 } 
1252                                                 else if ( out_size < 0 )
1253                                                 {
1254                                                         mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "error with video encode %d\n", frame_count );
1255                                                 }
1256                                         }
1257                                         frame_count++;
1258                                         mlt_frame_close( frame );
1259                                 }
1260                                 else
1261                                 {
1262                                         break;
1263                                 }
1264                         }
1265                         if ( audio_st )
1266                                 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "audio pts %lld (%f) ", audio_st->pts.val, audio_pts );
1267                         if ( video_st )
1268                                 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "video pts %lld (%f) ", video_st->pts.val, video_pts );
1269                         mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "\n" );
1270                 }
1271
1272                 if ( real_time_output == 1 && frames % 2 == 0 )
1273                 {
1274                         long passed = time_difference( &ante );
1275                         if ( fifo != NULL )
1276                         {
1277                                 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1278                                 passed -= pending;
1279                         }
1280                         if ( passed < total_time )
1281                         {
1282                                 long total = ( total_time - passed );
1283                                 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1284                                 nanosleep( &t, NULL );
1285                         }
1286                 }
1287         }
1288
1289 #ifdef FLUSH
1290         if ( ! real_time_output )
1291         {
1292                 // Flush audio fifo
1293                 if ( audio_st && audio_st->codec->frame_size > 1 ) for (;;)
1294                 {
1295                         AVCodecContext *c = audio_st->codec;
1296                         AVPacket pkt;
1297                         av_init_packet( &pkt );
1298                         pkt.size = 0;
1299
1300                         if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1301                                 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1302                         {
1303                                 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
1304                                 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
1305                         }
1306                         if ( pkt.size <= 0 )
1307                                 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1308                         if ( pkt.size <= 0 )
1309                                 break;
1310
1311                         // Write the compressed frame in the media file
1312                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1313                                 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
1314                         pkt.flags |= PKT_FLAG_KEY;
1315                         pkt.stream_index = audio_st->index;
1316                         pkt.data = audio_outbuf;
1317                         if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1318                         {
1319                                 fprintf( stderr, "%s: Error while writing flushed audio frame\n", __FILE__ );
1320                                 break;
1321                         }
1322                 }
1323
1324                 // Flush video
1325                 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1326                 {
1327                         AVCodecContext *c = video_st->codec;
1328                         AVPacket pkt;
1329                         av_init_packet( &pkt );
1330
1331                         // Encode the image
1332                         pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1333                         if ( pkt.size <= 0 )
1334                                 break;
1335
1336                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1337                                 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1338                         if( c->coded_frame && c->coded_frame->key_frame )
1339                                 pkt.flags |= PKT_FLAG_KEY;
1340                         pkt.stream_index = video_st->index;
1341                         pkt.data = video_outbuf;
1342
1343                         // write the compressed frame in the media file
1344                         if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1345                         {
1346                                 mlt_log_error( MLT_CONSUMER_SERVICE(this), "error while writing flushing video frame\n" );
1347                                 break;
1348                         }
1349                 }
1350         }
1351 #endif
1352
1353         // XXX ugly hack to prevent x264 from crashing on second pass of multi-threaded encoding
1354         int pass = mlt_properties_get_int( properties, "pass" );
1355         int thread_count = mlt_properties_get_int( properties, "threads" );
1356         if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1357                 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1358         int multithreaded_x264 = ( video_codec_id == CODEC_ID_H264 && pass == 2 && thread_count > 1 );
1359         
1360         // close each codec
1361         if ( video_st && !multithreaded_x264 )
1362                 close_video(oc, video_st);
1363         if (audio_st)
1364                 close_audio(oc, audio_st);
1365
1366         // Write the trailer, if any
1367         av_write_trailer(oc);
1368
1369         // Free the streams
1370         for(i = 0; i < oc->nb_streams; i++)
1371                 av_freep(&oc->streams[i]);
1372
1373         // Close the output file
1374         if (!(fmt->flags & AVFMT_NOFILE))
1375 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1376                 url_fclose(oc->pb);
1377 #else
1378                 url_fclose(&oc->pb);
1379 #endif
1380
1381         // Clean up input and output frames
1382         if ( output )
1383                 av_free( output->data[0] );
1384         av_free( output );
1385         av_free( input->data[0] );
1386         av_free( input );
1387         av_free( video_outbuf );
1388         av_free( buffer );
1389
1390         // Free the stream
1391         av_free(oc);
1392
1393         // Just in case we terminated on pause
1394         mlt_properties_set_int( properties, "running", 0 );
1395
1396         mlt_consumer_stopped( this );
1397
1398         if ( pass == 2 )
1399         {
1400                 // Remove the dual pass log file
1401                 if ( mlt_properties_get( properties, "_logfilename" ) )
1402                         remove( mlt_properties_get( properties, "_logfilename" ) );
1403
1404                 // Remove the x264 dual pass logs
1405                 char *cwd = getcwd( NULL, 0 );
1406                 const char *file = "x264_2pass.log";
1407                 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1408                 sprintf( full, "%s/%s", cwd, file );
1409                 remove( full );
1410                 free( full );
1411                 file = "x264_2pass.log.temp";
1412                 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1413                 sprintf( full, "%s/%s", cwd, file );
1414                 remove( full );
1415                 free( full );
1416                 file = "x264_2pass.log.mbtree";
1417                 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1418                 sprintf( full, "%s/%s", cwd, file );
1419                 remove( full );
1420                 free( full );
1421                 free( cwd );
1422                 remove( "x264_2pass.log.temp" );
1423         }
1424
1425         return NULL;
1426 }
1427
1428 /** Close the consumer.
1429 */
1430
1431 static void consumer_close( mlt_consumer this )
1432 {
1433         // Stop the consumer
1434         mlt_consumer_stop( this );
1435
1436         // Close the parent
1437         mlt_consumer_close( this );
1438
1439         // Free the memory
1440         free( this );
1441 }