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