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
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.
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.
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
23 #include <framework/mlt_consumer.h>
24 #include <framework/mlt_frame.h>
25 #include <framework/mlt_profile.h>
26 #include <framework/mlt_log.h>
27 #include <framework/mlt_events.h>
29 // System header files
38 // avformat header files
39 #include <libavformat/avformat.h>
41 #include <libswscale/swscale.h>
43 #include <libavcodec/opt.h>
44 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
45 #include <libavutil/pixdesc.h>
48 #if LIBAVUTIL_VERSION_INT < (50<<16)
49 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
50 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
53 #define MAX_AUDIO_STREAMS (8)
54 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
55 #define AUDIO_BUFFER_SIZE (1024 * 42)
56 #define VIDEO_BUFFER_SIZE (2048 * 1024)
58 void avformat_lock( );
59 void avformat_unlock( );
62 // This structure should be extended and made globally available in mlt
74 *sample_fifo, sample_fifo_s;
76 sample_fifo sample_fifo_init( int frequency, int channels )
78 sample_fifo this = calloc( 1, sizeof( sample_fifo_s ) );
79 this->frequency = frequency;
80 this->channels = channels;
84 // sample_fifo_clear and check are temporarily aborted (not working as intended)
86 void sample_fifo_clear( sample_fifo this, double time )
88 int words = ( float )( time - this->time ) * this->frequency * this->channels;
89 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) && this->used > words && words > 0 )
91 memmove( this->buffer, &this->buffer[ words ], ( this->used - words ) * sizeof( int16_t ) );
95 else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )this->time * 100 ) )
102 void sample_fifo_check( sample_fifo this, double time )
104 if ( this->used == 0 )
106 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) )
111 void sample_fifo_append( sample_fifo this, int16_t *samples, int count )
113 if ( ( this->size - this->used ) < count )
115 this->size += count * 5;
116 this->buffer = realloc( this->buffer, this->size * sizeof( int16_t ) );
119 memcpy( &this->buffer[ this->used ], samples, count * sizeof( int16_t ) );
123 int sample_fifo_used( sample_fifo this )
128 int sample_fifo_fetch( sample_fifo this, int16_t *samples, int count )
130 if ( count > this->used )
133 memcpy( samples, this->buffer, count * sizeof( int16_t ) );
135 memmove( this->buffer, &this->buffer[ count ], this->used * sizeof( int16_t ) );
137 this->time += ( double )count / this->channels / this->frequency;
142 void sample_fifo_close( sample_fifo this )
144 free( this->buffer );
148 // Forward references.
149 static int consumer_start( mlt_consumer this );
150 static int consumer_stop( mlt_consumer this );
151 static int consumer_is_stopped( mlt_consumer this );
152 static void *consumer_thread( void *arg );
153 static void consumer_close( mlt_consumer this );
155 /** Initialise the consumer.
158 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
160 // Allocate the consumer
161 mlt_consumer this = mlt_consumer_new( profile );
163 // If memory allocated and initialises without error
166 // Get properties from the consumer
167 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
169 // Assign close callback
170 this->close = consumer_close;
172 // Interpret the argument
174 mlt_properties_set( properties, "target", arg );
176 // sample and frame queue
177 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
179 // Audio options not fully handled by AVOptions
180 #define QSCALE_NONE (-99999)
181 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
183 // Video options not fully handled by AVOptions
184 mlt_properties_set_int( properties, "dc", 8 );
186 // Muxer options not fully handled by AVOptions
187 mlt_properties_set_double( properties, "muxdelay", 0.7 );
188 mlt_properties_set_double( properties, "muxpreload", 0.5 );
190 // Ensure termination at end of the stream
191 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
193 // Default to separate processing threads for producer and consumer with no frame dropping!
194 mlt_properties_set_int( properties, "real_time", -1 );
195 mlt_properties_set_int( properties, "prefill", 1 );
197 // Set up start/stop/terminated callbacks
198 this->start = consumer_start;
199 this->stop = consumer_stop;
200 this->is_stopped = consumer_is_stopped;
202 mlt_events_register( properties, "consumer-fatal-error", NULL );
209 /** Start the consumer.
212 static int consumer_start( mlt_consumer this )
214 // Get the properties
215 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
218 // Report information about available muxers and codecs as YAML Tiny
219 char *s = mlt_properties_get( properties, "f" );
220 if ( s && strcmp( s, "list" ) == 0 )
222 mlt_properties doc = mlt_properties_new();
223 mlt_properties formats = mlt_properties_new();
225 AVOutputFormat *format = NULL;
227 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
228 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
229 while ( ( format = av_oformat_next( format ) ) )
231 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
232 mlt_properties_set( formats, key, format->name );
234 fprintf( stderr, "%s", mlt_properties_serialise_yaml( doc ) );
235 mlt_properties_close( doc );
238 s = mlt_properties_get( properties, "acodec" );
239 if ( s && strcmp( s, "list" ) == 0 )
241 mlt_properties doc = mlt_properties_new();
242 mlt_properties codecs = mlt_properties_new();
244 AVCodec *codec = NULL;
246 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
247 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
248 while ( ( codec = av_codec_next( codec ) ) )
249 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
251 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
252 mlt_properties_set( codecs, key, codec->name );
254 fprintf( stderr, "%s", mlt_properties_serialise_yaml( doc ) );
255 mlt_properties_close( doc );
258 s = mlt_properties_get( properties, "vcodec" );
259 if ( s && strcmp( s, "list" ) == 0 )
261 mlt_properties doc = mlt_properties_new();
262 mlt_properties codecs = mlt_properties_new();
264 AVCodec *codec = NULL;
266 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
267 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
268 while ( ( codec = av_codec_next( codec ) ) )
269 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
271 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
272 mlt_properties_set( codecs, key, codec->name );
274 fprintf( stderr, "%s", mlt_properties_serialise_yaml( doc ) );
275 mlt_properties_close( doc );
279 // Check that we're not already running
280 if ( !error && !mlt_properties_get_int( properties, "running" ) )
283 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
285 // Get the width and height
286 int width = mlt_properties_get_int( properties, "width" );
287 int height = mlt_properties_get_int( properties, "height" );
289 // Obtain the size property
290 char *size = mlt_properties_get( properties, "s" );
296 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
303 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "Invalid size property %s - ignoring.\n", size );
307 // Now ensure we honour the multiple of two requested by libavformat
308 width = ( width / 2 ) * 2;
309 height = ( height / 2 ) * 2;
310 mlt_properties_set_int( properties, "width", width );
311 mlt_properties_set_int( properties, "height", height );
313 // We need to set these on the profile as well because the s property is
314 // an alias to mlt properties that correspond to profile settings.
315 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
318 profile->width = width;
319 profile->height = height;
322 // Handle the ffmpeg command line "-r" property for frame rate
323 if ( mlt_properties_get( properties, "r" ) )
325 double frame_rate = mlt_properties_get_double( properties, "r" );
326 AVRational rational = av_d2q( frame_rate, 255 );
327 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
328 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
331 profile->frame_rate_num = rational.num;
332 profile->frame_rate_den = rational.den;
333 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
337 // Apply AVOptions that are synonyms for standard mlt_consumer options
338 if ( mlt_properties_get( properties, "ac" ) )
339 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
340 if ( mlt_properties_get( properties, "ar" ) )
341 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
343 // Assign the thread to properties
344 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
346 // Set the running state
347 mlt_properties_set_int( properties, "running", 1 );
350 pthread_create( thread, NULL, consumer_thread, this );
355 /** Stop the consumer.
358 static int consumer_stop( mlt_consumer this )
360 // Get the properties
361 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
363 // Check that we're running
364 if ( mlt_properties_get_int( properties, "running" ) )
367 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
370 mlt_properties_set_int( properties, "running", 0 );
372 // Wait for termination
373 pthread_join( *thread, NULL );
379 /** Determine if the consumer is stopped.
382 static int consumer_is_stopped( mlt_consumer this )
384 // Get the properties
385 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
386 return !mlt_properties_get_int( properties, "running" );
389 /** Process properties as AVOptions and apply to AV context obj
392 static void apply_properties( void *obj, mlt_properties properties, int flags, int alloc )
395 int count = mlt_properties_count( properties );
396 for ( i = 0; i < count; i++ )
398 const char *opt_name = mlt_properties_get_name( properties, i );
399 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
401 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
402 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), alloc, NULL );
403 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
404 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), alloc );
406 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
411 /** Add an audio output stream
414 static AVStream *add_audio_stream( mlt_consumer this, AVFormatContext *oc, int codec_id, int channels )
416 // Get the properties
417 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
419 // Create a new stream
420 AVStream *st = av_new_stream( oc, oc->nb_streams );
422 // If created, then initialise from properties
425 AVCodecContext *c = st->codec;
427 // Establish defaults from AVOptions
428 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
430 c->codec_id = codec_id;
431 c->codec_type = CODEC_TYPE_AUDIO;
432 c->sample_fmt = SAMPLE_FMT_S16;
434 #if 0 // disabled until some audio codecs are multi-threaded
435 // Setup multi-threading
436 int thread_count = mlt_properties_get_int( properties, "threads" );
437 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
438 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
439 if ( thread_count > 1 )
440 avcodec_thread_init( c, thread_count );
443 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
444 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
446 // Allow the user to override the audio fourcc
447 if ( mlt_properties_get( properties, "atag" ) )
450 char *arg = mlt_properties_get( properties, "atag" );
451 int tag = strtol( arg, &tail, 0);
453 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
457 // Process properties as AVOptions
458 char *apre = mlt_properties_get( properties, "apre" );
461 mlt_properties p = mlt_properties_load( apre );
462 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
463 mlt_properties_close( p );
465 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
467 int audio_qscale = mlt_properties_get_int( properties, "aq" );
468 if ( audio_qscale > QSCALE_NONE )
470 c->flags |= CODEC_FLAG_QSCALE;
471 c->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
474 // Set parameters controlled by MLT
475 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
476 c->time_base = ( AVRational ){ 1, c->sample_rate };
477 c->channels = channels;
479 if ( mlt_properties_get( properties, "alang" ) != NULL )
480 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
484 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not allocate a stream for audio\n" );
490 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
492 // We will return the audio input size from here
493 int audio_input_frame_size = 0;
496 AVCodecContext *c = st->codec;
499 AVCodec *codec = avcodec_find_encoder( c->codec_id );
503 // Continue if codec found and we can open it
504 if ( codec != NULL && avcodec_open( c, codec ) >= 0 )
506 // ugly hack for PCM codecs (will be removed ASAP with new PCM
507 // support to compute the input frame size in samples
508 if ( c->frame_size <= 1 )
510 audio_input_frame_size = audio_outbuf_size / c->channels;
511 switch(st->codec->codec_id)
513 case CODEC_ID_PCM_S16LE:
514 case CODEC_ID_PCM_S16BE:
515 case CODEC_ID_PCM_U16LE:
516 case CODEC_ID_PCM_U16BE:
517 audio_input_frame_size >>= 1;
525 audio_input_frame_size = c->frame_size;
528 // Some formats want stream headers to be seperate (hmm)
529 if ( !strcmp( oc->oformat->name, "mp4" ) ||
530 !strcmp( oc->oformat->name, "mov" ) ||
531 !strcmp( oc->oformat->name, "3gp" ) )
532 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
536 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
541 return audio_input_frame_size;
544 static void close_audio( AVFormatContext *oc, AVStream *st )
546 if ( st && st->codec )
549 avcodec_close( st->codec );
554 /** Add a video output stream
557 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
559 // Get the properties
560 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
562 // Create a new stream
563 AVStream *st = av_new_stream( oc, oc->nb_streams );
567 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
568 AVCodecContext *c = st->codec;
570 // Establish defaults from AVOptions
571 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
573 c->codec_id = codec_id;
574 c->codec_type = CODEC_TYPE_VIDEO;
576 // Setup multi-threading
577 int thread_count = mlt_properties_get_int( properties, "threads" );
578 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
579 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
580 if ( thread_count > 1 )
581 avcodec_thread_init( c, thread_count );
583 // Process properties as AVOptions
584 char *vpre = mlt_properties_get( properties, "vpre" );
587 mlt_properties p = mlt_properties_load( vpre );
589 if ( mlt_properties_count( p ) < 1 )
591 AVCodec *codec = avcodec_find_encoder( c->codec_id );
594 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
595 strcpy( path, AVDATADIR );
596 strcat( path, codec->name );
598 strcat( path, vpre );
599 strcat( path, ".ffpreset" );
601 mlt_properties_close( p );
602 p = mlt_properties_load( path );
603 mlt_properties_debug( p, path, stderr );
609 mlt_properties_debug( p, vpre, stderr );
612 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
613 mlt_properties_close( p );
615 int colorspace = mlt_properties_get_int( properties, "colorspace" );
616 mlt_properties_set( properties, "colorspace", NULL );
617 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
618 mlt_properties_set_int( properties, "colorspace", colorspace );
620 // Set options controlled by MLT
621 c->width = mlt_properties_get_int( properties, "width" );
622 c->height = mlt_properties_get_int( properties, "height" );
623 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
624 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
625 if ( st->time_base.den == 0 )
626 st->time_base = c->time_base;
627 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
628 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
630 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
633 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
634 switch ( colorspace )
637 c->colorspace = AVCOL_SPC_SMPTE170M;
640 c->colorspace = AVCOL_SPC_SMPTE240M;
643 c->colorspace = AVCOL_SPC_BT470BG;
646 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
649 c->colorspace = AVCOL_SPC_BT709;
654 if ( mlt_properties_get( properties, "aspect" ) )
656 // "-aspect" on ffmpeg command line is display aspect ratio
657 double ar = mlt_properties_get_double( properties, "aspect" );
658 AVRational rational = av_d2q( ar, 255 );
660 // Update the profile and properties as well since this is an alias
661 // for mlt properties that correspond to profile settings
662 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
663 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
664 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
667 profile->display_aspect_num = rational.num;
668 profile->display_aspect_den = rational.den;
669 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
672 // Now compute the sample aspect ratio
673 rational = av_d2q( ar * c->height / c->width, 255 );
674 c->sample_aspect_ratio = rational;
675 // Update the profile and properties as well since this is an alias
676 // for mlt properties that correspond to profile settings
677 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
678 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
681 profile->sample_aspect_num = rational.num;
682 profile->sample_aspect_den = rational.den;
683 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
688 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
689 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
691 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
692 st->sample_aspect_ratio = c->sample_aspect_ratio;
695 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
697 c->flags |= CODEC_FLAG_QSCALE;
698 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
701 // Allow the user to override the video fourcc
702 if ( mlt_properties_get( properties, "vtag" ) )
705 const char *arg = mlt_properties_get( properties, "vtag" );
706 int tag = strtol( arg, &tail, 0);
708 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
712 // Some formats want stream headers to be seperate
713 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
714 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
716 // Translate these standard mlt consumer properties to ffmpeg
717 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
718 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
720 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
721 c->flags |= CODEC_FLAG_INTERLACED_DCT;
722 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
723 c->flags |= CODEC_FLAG_INTERLACED_ME;
726 // parse the ratecontrol override string
728 char *rc_override = mlt_properties_get( properties, "rc_override" );
729 for ( i = 0; rc_override; i++ )
732 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
734 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "Error parsing rc_override\n" );
735 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
736 c->rc_override[i].start_frame = start;
737 c->rc_override[i].end_frame = end;
740 c->rc_override[i].qscale = q;
741 c->rc_override[i].quality_factor = 1.0;
745 c->rc_override[i].qscale = 0;
746 c->rc_override[i].quality_factor = -q / 100.0;
748 rc_override = strchr( rc_override, '/' );
752 c->rc_override_count = i;
753 if ( !c->rc_initial_buffer_occupancy )
754 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
755 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
758 i = mlt_properties_get_int( properties, "pass" );
760 c->flags |= CODEC_FLAG_PASS1;
762 c->flags |= CODEC_FLAG_PASS2;
763 if ( codec_id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
765 char logfilename[1024];
770 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
771 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
772 if ( c->flags & CODEC_FLAG_PASS1 )
774 f = fopen( logfilename, "w" );
776 perror( logfilename );
778 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
782 /* read the log file */
783 f = fopen( logfilename, "r" );
790 mlt_properties_set( properties, "_logfilename", logfilename );
791 fseek( f, 0, SEEK_END );
793 fseek( f, 0, SEEK_SET );
794 logbuffer = av_malloc( size + 1 );
796 mlt_log_fatal( MLT_CONSUMER_SERVICE( this ), "Could not allocate log buffer\n" );
799 size = fread( logbuffer, 1, size, f );
801 logbuffer[size] = '\0';
802 c->stats_in = logbuffer;
803 mlt_properties_set_data( properties, "_logbuffer", logbuffer, 0, ( mlt_destructor )av_free, NULL );
811 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not allocate a stream for video\n" );
817 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
820 AVFrame *picture = avcodec_alloc_frame();
822 // Determine size of the
823 int size = avpicture_get_size(pix_fmt, width, height);
825 // Allocate the picture buf
826 uint8_t *picture_buf = av_malloc(size);
828 // If we have both, then fill the image
829 if ( picture != NULL && picture_buf != NULL )
831 // Fill the frame with the allocated buffer
832 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
836 // Something failed - clean up what we can
838 av_free( picture_buf );
845 static int open_video(AVFormatContext *oc, AVStream *st)
848 AVCodecContext *video_enc = st->codec;
850 // find the video encoder
851 AVCodec *codec = avcodec_find_encoder( video_enc->codec_id );
853 if( codec && codec->pix_fmts )
855 const enum PixelFormat *p = codec->pix_fmts;
858 if( *p == video_enc->pix_fmt )
862 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
865 // Open the codec safely
867 int result = codec != NULL && avcodec_open( video_enc, codec ) >= 0;
873 void close_video(AVFormatContext *oc, AVStream *st)
875 if ( st && st->codec )
878 avcodec_close(st->codec);
883 static inline long time_difference( struct timeval *time1 )
885 struct timeval time2;
886 gettimeofday( &time2, NULL );
887 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
890 /** The main thread - the argument is simply the consumer.
893 static void *consumer_thread( void *arg )
895 // Map the argument to the object
896 mlt_consumer this = arg;
898 // Get the properties
899 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
901 // Get the terminate on pause property
902 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
905 // Determine if feed is slow (for realtime stuff)
906 int real_time_output = mlt_properties_get_int( properties, "real_time" );
911 // Get the frame rate
912 double fps = mlt_properties_get_double( properties, "fps" );
914 // Get width and height
915 int width = mlt_properties_get_int( properties, "width" );
916 int height = mlt_properties_get_int( properties, "height" );
917 int img_width = width;
918 int img_height = height;
920 // Get default audio properties
921 mlt_audio_format aud_fmt = mlt_audio_s16;
922 int channels = mlt_properties_get_int( properties, "channels" );
923 int total_channels = channels;
924 int frequency = mlt_properties_get_int( properties, "frequency" );
928 // AVFormat audio buffer and frame size
929 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
930 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
931 int audio_input_frame_size = 0;
933 // AVFormat video buffer and frame count
935 int video_outbuf_size = VIDEO_BUFFER_SIZE;
936 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
938 // Used for the frame properties
939 mlt_frame frame = NULL;
940 mlt_properties frame_properties = NULL;
943 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
944 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
946 // Need two av pictures for converting
947 AVFrame *output = NULL;
948 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
950 // For receiving images from an mlt_frame
952 mlt_image_format img_fmt = mlt_image_yuv422;
954 // For receiving audio samples back from the fifo
955 int16_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
956 int16_t *audio_buf_2 = NULL;
959 // Allocate the context
960 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
961 AVFormatContext *oc = avformat_alloc_context( );
963 AVFormatContext *oc = av_alloc_format_context( );
967 AVStream *video_st = NULL;
968 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
971 double audio_pts = 0;
972 double video_pts = 0;
976 long int total_time = 0;
978 // Determine the format
979 AVOutputFormat *fmt = NULL;
980 const char *filename = mlt_properties_get( properties, "target" );
981 char *format = mlt_properties_get( properties, "f" );
982 char *vcodec = mlt_properties_get( properties, "vcodec" );
983 char *acodec = mlt_properties_get( properties, "acodec" );
985 // Used to store and override codec ids
991 mlt_properties frame_meta_properties = mlt_properties_new();
993 // Initialize audio_st
994 int i = MAX_AUDIO_STREAMS;
998 // Check for user selected format first
999 if ( format != NULL )
1000 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1001 fmt = guess_format( format, NULL, NULL );
1003 fmt = av_guess_format( format, NULL, NULL );
1006 // Otherwise check on the filename
1007 if ( fmt == NULL && filename != NULL )
1008 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1009 fmt = guess_format( NULL, filename, NULL );
1011 fmt = av_guess_format( NULL, filename, NULL );
1014 // Otherwise default to mpeg
1016 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1017 fmt = guess_format( "mpeg", NULL, NULL );
1019 fmt = av_guess_format( "mpeg", NULL, NULL );
1022 // We need a filename - default to stdout?
1023 if ( filename == NULL || !strcmp( filename, "" ) )
1026 // Get the codec ids selected
1027 audio_codec_id = fmt->audio_codec;
1028 video_codec_id = fmt->video_codec;
1030 // Check for audio codec overides
1031 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1032 audio_codec_id = CODEC_ID_NONE;
1035 AVCodec *p = avcodec_find_encoder_by_name( acodec );
1037 audio_codec_id = p->id;
1039 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "audio codec %s unrecognised - ignoring\n", acodec );
1042 // Check for video codec overides
1043 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1044 video_codec_id = CODEC_ID_NONE;
1047 AVCodec *p = avcodec_find_encoder_by_name( vcodec );
1049 video_codec_id = p->id;
1051 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "video codec %s unrecognised - ignoring\n", vcodec );
1058 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1059 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1061 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1062 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1064 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1065 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1067 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1068 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1070 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1071 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1073 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1074 if (metavalue != 0) oc->year = metavalue;
1076 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1077 if (metavalue != 0) oc->track = metavalue;
1080 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1082 // Add audio and video streams
1083 if ( video_codec_id != CODEC_ID_NONE )
1084 video_st = add_video_stream( this, oc, video_codec_id );
1085 if ( audio_codec_id != CODEC_ID_NONE )
1091 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1093 sprintf( key, "channels.%d", i );
1094 int j = mlt_properties_get_int( properties, key );
1098 total_channels += j;
1099 audio_st[i] = add_audio_stream( this, oc, audio_codec_id, j );
1105 audio_st[0] = add_audio_stream( this, oc, audio_codec_id, channels );
1106 total_channels = channels;
1110 // Set the parameters (even though we have none...)
1111 if ( av_set_parameters(oc, NULL) >= 0 )
1113 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1114 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1116 // Process properties as AVOptions
1117 char *fpre = mlt_properties_get( properties, "fpre" );
1120 mlt_properties p = mlt_properties_load( fpre );
1121 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM, 1 );
1122 mlt_properties_close( p );
1124 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM, 0 );
1126 if ( video_st && !open_video( oc, video_st ) )
1128 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1130 audio_input_frame_size = open_audio( oc, audio_st[i], audio_outbuf_size );
1131 if ( !audio_input_frame_size )
1135 // Open the output file, if needed
1136 if ( !( fmt->flags & AVFMT_NOFILE ) )
1138 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1140 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not open '%s'\n", filename );
1141 mlt_properties_set_int( properties, "running", 0 );
1145 // Write the stream header.
1146 if ( mlt_properties_get_int( properties, "running" ) )
1147 av_write_header( oc );
1151 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Invalid output format parameters\n" );
1152 mlt_properties_set_int( properties, "running", 0 );
1157 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1159 // Last check - need at least one stream
1160 if ( !audio_st[0] && !video_st )
1161 mlt_properties_set_int( properties, "running", 0 );
1163 // Get the starting time (can ignore the times above)
1164 gettimeofday( &ante, NULL );
1166 // Loop while running
1167 while( mlt_properties_get_int( properties, "running" ) &&
1168 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1170 frame = mlt_consumer_rt_frame( this );
1172 // Check that we have a frame to work with
1173 if ( frame != NULL )
1175 // Increment frames dispatched
1178 // Default audio args
1179 frame_properties = MLT_FRAME_PROPERTIES( frame );
1181 // Check for the terminated condition
1182 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1184 // Get audio and append to the fifo
1185 if ( !terminated && audio_st[0] )
1187 samples = mlt_sample_calculator( fps, frequency, count ++ );
1188 mlt_frame_get_audio( frame, (void**) &pcm, &aud_fmt, &frequency, &channels, &samples );
1190 // Save the audio channel remap properties for later
1191 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1193 // Create the fifo if we don't have one
1196 fifo = sample_fifo_init( frequency, channels );
1197 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1200 // Silence if not normal forward speed
1201 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1202 memset( pcm, 0, samples * channels * 2 );
1204 // Append the samples
1205 sample_fifo_append( fifo, pcm, samples * channels );
1206 total_time += ( samples * 1000000 ) / frequency;
1210 if ( !terminated && video_st )
1211 mlt_deque_push_back( queue, frame );
1213 mlt_frame_close( frame );
1216 // While we have stuff to process, process...
1219 // Write interleaved audio and video frames
1220 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1223 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1225 int j = 0; // channel offset into interleaved source buffer
1226 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) ), AUDIO_ENCODE_BUFFER_SIZE );
1228 // Get the audio samples
1231 sample_fifo_fetch( fifo, audio_buf_1, n );
1233 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1235 // This prevents an infinite loop when some versions of vorbis do not
1236 // increment pts when encoding silence.
1237 audio_pts = video_pts;
1242 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1244 samples = n / channels;
1246 // For each output stream
1247 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1249 AVStream *stream = audio_st[i];
1250 AVCodecContext *codec = stream->codec;
1253 av_init_packet( &pkt );
1255 // Optimized for single track and no channel remap
1256 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1258 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1262 // Extract the audio channels according to channel mapping
1263 int dest_offset = 0; // channel offset into interleaved dest buffer
1265 // Get the number of channels for this stream
1266 sprintf( key, "channels.%d", i );
1267 int current_channels = mlt_properties_get_int( properties, key );
1269 // Clear the destination audio buffer.
1271 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1273 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1275 // For each output channel
1276 while ( dest_offset < current_channels && j < total_channels )
1278 int map_start = -1, map_channels = 0;
1279 int source_offset = 0;
1282 // Look for a mapping that starts at j
1283 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1285 sprintf( key, "%d.channels", k );
1286 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1287 sprintf( key, "%d.start", k );
1288 if ( mlt_properties_get( frame_meta_properties, key ) )
1289 map_start = mlt_properties_get_int( frame_meta_properties, key );
1290 if ( map_start != j )
1291 source_offset += map_channels;
1295 if ( map_start != j )
1297 map_channels = current_channels;
1301 // Copy samples if source offset valid
1302 if ( source_offset < channels )
1304 // Interleave the audio buffer with the # channels for this stream/mapping.
1305 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1307 int16_t *src = audio_buf_1 + source_offset;
1308 int16_t *dest = audio_buf_2 + dest_offset;
1309 int s = samples + 1;
1313 dest += current_channels;
1318 // Otherwise silence
1321 j += current_channels;
1322 dest_offset += current_channels;
1325 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_2 );
1328 // Write the compressed frame in the media file
1329 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1331 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1332 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "audio stream %d pkt pts %lld frame pts %lld",
1333 stream->index, pkt.pts, codec->coded_frame->pts );
1335 pkt.flags |= PKT_FLAG_KEY;
1336 pkt.stream_index = stream->index;
1337 pkt.data = audio_outbuf;
1341 if ( av_interleaved_write_frame( oc, &pkt ) )
1343 mlt_log_fatal( MLT_CONSUMER_SERVICE( this ), "error writing audio frame\n" );
1344 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1345 goto on_fatal_error;
1349 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), " frame_size %d\n", codec->frame_size );
1352 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1361 else if ( video_st )
1364 if ( mlt_deque_count( queue ) )
1366 int out_size, ret = 0;
1369 frame = mlt_deque_pop_front( queue );
1370 frame_properties = MLT_FRAME_PROPERTIES( frame );
1372 c = video_st->codec;
1374 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1380 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1384 // Convert the mlt frame to an AVPicture
1385 for ( i = 0; i < height; i ++ )
1387 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1388 memcpy( p, q, width * 2 );
1392 // Do the colour space conversion
1394 int flags = SWS_BILINEAR;
1396 flags |= SWS_CPU_CAPS_MMX;
1399 flags |= SWS_CPU_CAPS_MMX2;
1401 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1402 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1403 sws_scale( context, input->data, input->linesize, 0, height,
1404 output->data, output->linesize);
1405 sws_freeContext( context );
1407 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1410 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1412 // Apply the alpha if applicable
1413 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1415 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1418 for ( i = 0; i < height; i ++ )
1420 n = ( width + 7 ) / 8;
1421 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1425 case 0: do { *p = *alpha++; p += 4;
1426 case 7: *p = *alpha++; p += 4;
1427 case 6: *p = *alpha++; p += 4;
1428 case 5: *p = *alpha++; p += 4;
1429 case 4: *p = *alpha++; p += 4;
1430 case 3: *p = *alpha++; p += 4;
1431 case 2: *p = *alpha++; p += 4;
1432 case 1: *p = *alpha++; p += 4;
1440 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1442 // raw video case. The API will change slightly in the near future for that
1444 av_init_packet(&pkt);
1446 pkt.flags |= PKT_FLAG_KEY;
1447 pkt.stream_index= video_st->index;
1448 pkt.data= (uint8_t *)output;
1449 pkt.size= sizeof(AVPicture);
1451 ret = av_write_frame(oc, &pkt);
1452 video_pts += c->frame_size;
1457 output->quality = video_st->quality;
1459 // Set frame interlace hints
1460 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1461 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1462 output->pts = frame_count;
1465 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1467 // If zero size, it means the image was buffered
1471 av_init_packet( &pkt );
1473 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1474 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1475 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "video pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1476 if( c->coded_frame && c->coded_frame->key_frame )
1477 pkt.flags |= PKT_FLAG_KEY;
1478 pkt.stream_index= video_st->index;
1479 pkt.data= video_outbuf;
1482 // write the compressed frame in the media file
1483 ret = av_interleaved_write_frame(oc, &pkt);
1484 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), " frame_size %d\n", c->frame_size );
1485 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1487 // Dual pass logging
1488 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1489 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1491 else if ( out_size < 0 )
1493 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "error with video encode %d\n", frame_count );
1499 mlt_log_fatal( MLT_CONSUMER_SERVICE( this ), "error writing video frame\n" );
1500 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1501 goto on_fatal_error;
1503 mlt_frame_close( frame );
1511 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "audio pts %lld (%f) ", audio_st[0]->pts.val, audio_pts );
1513 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "video pts %lld (%f) ", video_st->pts.val, video_pts );
1514 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "\n" );
1517 if ( real_time_output == 1 && frames % 2 == 0 )
1519 long passed = time_difference( &ante );
1522 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1525 if ( passed < total_time )
1527 long total = ( total_time - passed );
1528 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1529 nanosleep( &t, NULL );
1534 // Flush the encoder buffers
1535 if ( real_time_output <= 0 )
1538 // TODO: flush all audio streams
1539 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1541 AVCodecContext *c = audio_st[0]->codec;
1543 av_init_packet( &pkt );
1546 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1547 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1549 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size );
1550 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1552 if ( pkt.size <= 0 )
1553 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1554 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "flushing audio size %d\n", pkt.size );
1555 if ( pkt.size <= 0 )
1558 // Write the compressed frame in the media file
1559 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1560 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1561 pkt.flags |= PKT_FLAG_KEY;
1562 pkt.stream_index = audio_st[0]->index;
1563 pkt.data = audio_outbuf;
1564 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1566 mlt_log_fatal( MLT_CONSUMER_SERVICE( this ), "error writing flushed audio frame\n" );
1567 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1568 goto on_fatal_error;
1573 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1575 AVCodecContext *c = video_st->codec;
1577 av_init_packet( &pkt );
1580 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1581 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "flushing video size %d\n", pkt.size );
1582 if ( pkt.size <= 0 )
1585 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1586 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1587 if( c->coded_frame && c->coded_frame->key_frame )
1588 pkt.flags |= PKT_FLAG_KEY;
1589 pkt.stream_index = video_st->index;
1590 pkt.data = video_outbuf;
1592 // write the compressed frame in the media file
1593 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1595 mlt_log_fatal( MLT_CONSUMER_SERVICE(this), "error writing flushed video frame\n" );
1596 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1597 goto on_fatal_error;
1599 // Dual pass logging
1600 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1601 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1607 // Write the trailer, if any
1608 av_write_trailer( oc );
1612 close_video(oc, video_st);
1613 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1614 close_audio( oc, audio_st[i] );
1617 for ( i = 0; i < oc->nb_streams; i++ )
1618 av_freep( &oc->streams[i] );
1620 // Close the output file
1621 if ( !( fmt->flags & AVFMT_NOFILE ) )
1622 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1623 url_fclose( oc->pb );
1625 url_fclose( &oc->pb );
1628 // Clean up input and output frames
1630 av_free( output->data[0] );
1632 av_free( input->data[0] );
1634 av_free( video_outbuf );
1635 av_free( audio_buf_1 );
1636 av_free( audio_buf_2 );
1641 // Just in case we terminated on pause
1642 mlt_properties_set_int( properties, "running", 0 );
1644 mlt_consumer_stopped( this );
1645 mlt_properties_close( frame_meta_properties );
1647 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1649 // Remove the dual pass log file
1650 if ( mlt_properties_get( properties, "_logfilename" ) )
1651 remove( mlt_properties_get( properties, "_logfilename" ) );
1653 // Remove the x264 dual pass logs
1654 char *cwd = getcwd( NULL, 0 );
1655 const char *file = "x264_2pass.log";
1656 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1657 sprintf( full, "%s/%s", cwd, file );
1660 file = "x264_2pass.log.temp";
1661 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1662 sprintf( full, "%s/%s", cwd, file );
1665 file = "x264_2pass.log.mbtree";
1666 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1667 sprintf( full, "%s/%s", cwd, file );
1671 remove( "x264_2pass.log.temp" );
1677 /** Close the consumer.
1680 static void consumer_close( mlt_consumer this )
1682 // Stop the consumer
1683 mlt_consumer_stop( this );
1686 mlt_consumer_close( this );