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 fifo = calloc( 1, sizeof( sample_fifo_s ) );
79 fifo->frequency = frequency;
80 fifo->channels = channels;
84 // sample_fifo_clear and check are temporarily aborted (not working as intended)
86 void sample_fifo_clear( sample_fifo fifo, double time )
88 int words = ( float )( time - fifo->time ) * fifo->frequency * fifo->channels;
89 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )fifo->time * 100 ) && fifo->used > words && words > 0 )
91 memmove( fifo->buffer, &fifo->buffer[ words ], ( fifo->used - words ) * sizeof( int16_t ) );
95 else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )fifo->time * 100 ) )
102 void sample_fifo_check( sample_fifo fifo, double time )
104 if ( fifo->used == 0 )
106 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )fifo->time * 100 ) )
111 void sample_fifo_append( sample_fifo fifo, int16_t *samples, int count )
113 if ( ( fifo->size - fifo->used ) < count )
115 fifo->size += count * 5;
116 fifo->buffer = realloc( fifo->buffer, fifo->size * sizeof( int16_t ) );
119 memcpy( &fifo->buffer[ fifo->used ], samples, count * sizeof( int16_t ) );
123 int sample_fifo_used( sample_fifo fifo )
128 int sample_fifo_fetch( sample_fifo fifo, int16_t *samples, int count )
130 if ( count > fifo->used )
133 memcpy( samples, fifo->buffer, count * sizeof( int16_t ) );
135 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used * sizeof( int16_t ) );
137 fifo->time += ( double )count / fifo->channels / fifo->frequency;
142 void sample_fifo_close( sample_fifo fifo )
144 free( fifo->buffer );
148 // Forward references.
149 static int consumer_start( mlt_consumer consumer );
150 static int consumer_stop( mlt_consumer consumer );
151 static int consumer_is_stopped( mlt_consumer consumer );
152 static void *consumer_thread( void *arg );
153 static void consumer_close( mlt_consumer consumer );
155 /** Initialise the consumer.
158 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
160 // Allocate the consumer
161 mlt_consumer consumer = mlt_consumer_new( profile );
163 // If memory allocated and initialises without error
164 if ( consumer != NULL )
166 // Get properties from the consumer
167 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
169 // Assign close callback
170 consumer->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 consumer->start = consumer_start;
199 consumer->stop = consumer_stop;
200 consumer->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 consumer )
214 // Get the properties
215 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
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( consumer ), "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( consumer ) );
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, consumer );
355 /** Stop the consumer.
358 static int consumer_stop( mlt_consumer consumer )
360 // Get the properties
361 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
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 consumer )
384 // Get the properties
385 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
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 consumer, AVFormatContext *oc, int codec_id, int channels )
416 // Get the properties
417 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
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( consumer ), "Could not allocate a stream for audio\n" );
490 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
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_by_name( codec_name );
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 consumer, AVFormatContext *oc, int codec_id )
559 // Get the properties
560 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
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( consumer ) );
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( consumer ), "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( consumer ), "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( consumer ), "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 consumer = arg;
898 // Get the properties
899 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
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 );
1038 audio_codec_id = p->id;
1039 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1041 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1042 acodec = mlt_properties_get( properties, "_acodec" );
1046 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1049 // Check for video codec overides
1050 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1051 video_codec_id = CODEC_ID_NONE;
1054 AVCodec *p = avcodec_find_encoder_by_name( vcodec );
1056 video_codec_id = p->id;
1058 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1062 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1063 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1065 char *name = mlt_properties_get_name( properties, i );
1066 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1068 char *key = strdup( name + 10 );
1069 char *markup = strrchr( key, '.' );
1070 if ( markup && !strcmp( markup, ".markup") )
1073 if ( !strstr( key, ".stream." ) )
1074 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1075 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1077 av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1087 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1088 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1090 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1091 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1093 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1094 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1096 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1097 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1099 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1100 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1102 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1103 if (metavalue != 0) oc->year = metavalue;
1105 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1106 if (metavalue != 0) oc->track = metavalue;
1110 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1112 // Add audio and video streams
1113 if ( video_codec_id != CODEC_ID_NONE )
1114 video_st = add_video_stream( consumer, oc, video_codec_id );
1115 if ( audio_codec_id != CODEC_ID_NONE )
1121 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1123 sprintf( key, "channels.%d", i );
1124 int j = mlt_properties_get_int( properties, key );
1128 total_channels += j;
1129 audio_st[i] = add_audio_stream( consumer, oc, audio_codec_id, j );
1135 audio_st[0] = add_audio_stream( consumer, oc, audio_codec_id, channels );
1136 total_channels = channels;
1140 // Set the parameters (even though we have none...)
1141 if ( av_set_parameters(oc, NULL) >= 0 )
1143 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1144 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1146 // Process properties as AVOptions
1147 char *fpre = mlt_properties_get( properties, "fpre" );
1150 mlt_properties p = mlt_properties_load( fpre );
1151 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM, 1 );
1152 mlt_properties_close( p );
1154 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM, 0 );
1156 if ( video_st && !open_video( oc, video_st ) )
1158 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1160 audio_input_frame_size = open_audio( oc, audio_st[i], audio_outbuf_size, acodec );
1161 if ( !audio_input_frame_size )
1165 // Open the output file, if needed
1166 if ( !( fmt->flags & AVFMT_NOFILE ) )
1168 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1170 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1171 mlt_properties_set_int( properties, "running", 0 );
1175 // Write the stream header.
1176 if ( mlt_properties_get_int( properties, "running" ) )
1177 av_write_header( oc );
1181 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1182 mlt_properties_set_int( properties, "running", 0 );
1187 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1189 // Last check - need at least one stream
1190 if ( !audio_st[0] && !video_st )
1191 mlt_properties_set_int( properties, "running", 0 );
1193 // Get the starting time (can ignore the times above)
1194 gettimeofday( &ante, NULL );
1196 // Loop while running
1197 while( mlt_properties_get_int( properties, "running" ) &&
1198 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1200 frame = mlt_consumer_rt_frame( consumer );
1202 // Check that we have a frame to work with
1203 if ( frame != NULL )
1205 // Increment frames dispatched
1208 // Default audio args
1209 frame_properties = MLT_FRAME_PROPERTIES( frame );
1211 // Check for the terminated condition
1212 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1214 // Get audio and append to the fifo
1215 if ( !terminated && audio_st[0] )
1217 samples = mlt_sample_calculator( fps, frequency, count ++ );
1218 mlt_frame_get_audio( frame, (void**) &pcm, &aud_fmt, &frequency, &channels, &samples );
1220 // Save the audio channel remap properties for later
1221 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1223 // Create the fifo if we don't have one
1226 fifo = sample_fifo_init( frequency, channels );
1227 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1230 // Silence if not normal forward speed
1231 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1232 memset( pcm, 0, samples * channels * 2 );
1234 // Append the samples
1235 sample_fifo_append( fifo, pcm, samples * channels );
1236 total_time += ( samples * 1000000 ) / frequency;
1239 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1243 if ( !terminated && video_st )
1244 mlt_deque_push_back( queue, frame );
1246 mlt_frame_close( frame );
1249 // While we have stuff to process, process...
1252 // Write interleaved audio and video frames
1253 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1256 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1258 int j = 0; // channel offset into interleaved source buffer
1259 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) ), AUDIO_ENCODE_BUFFER_SIZE );
1261 // Get the audio samples
1264 sample_fifo_fetch( fifo, audio_buf_1, n );
1266 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1268 // This prevents an infinite loop when some versions of vorbis do not
1269 // increment pts when encoding silence.
1270 audio_pts = video_pts;
1275 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1277 samples = n / channels;
1279 // For each output stream
1280 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1282 AVStream *stream = audio_st[i];
1283 AVCodecContext *codec = stream->codec;
1286 av_init_packet( &pkt );
1288 // Optimized for single track and no channel remap
1289 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1291 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1295 // Extract the audio channels according to channel mapping
1296 int dest_offset = 0; // channel offset into interleaved dest buffer
1298 // Get the number of channels for this stream
1299 sprintf( key, "channels.%d", i );
1300 int current_channels = mlt_properties_get_int( properties, key );
1302 // Clear the destination audio buffer.
1304 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1306 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1308 // For each output channel
1309 while ( dest_offset < current_channels && j < total_channels )
1311 int map_start = -1, map_channels = 0;
1312 int source_offset = 0;
1315 // Look for a mapping that starts at j
1316 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1318 sprintf( key, "%d.channels", k );
1319 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1320 sprintf( key, "%d.start", k );
1321 if ( mlt_properties_get( frame_meta_properties, key ) )
1322 map_start = mlt_properties_get_int( frame_meta_properties, key );
1323 if ( map_start != j )
1324 source_offset += map_channels;
1328 if ( map_start != j )
1330 map_channels = current_channels;
1334 // Copy samples if source offset valid
1335 if ( source_offset < channels )
1337 // Interleave the audio buffer with the # channels for this stream/mapping.
1338 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1340 int16_t *src = audio_buf_1 + source_offset;
1341 int16_t *dest = audio_buf_2 + dest_offset;
1342 int s = samples + 1;
1346 dest += current_channels;
1351 // Otherwise silence
1354 j += current_channels;
1355 dest_offset += current_channels;
1358 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_2 );
1361 // Write the compressed frame in the media file
1362 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1364 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1365 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %lld frame pts %lld",
1366 stream->index, pkt.pts, codec->coded_frame->pts );
1368 pkt.flags |= PKT_FLAG_KEY;
1369 pkt.stream_index = stream->index;
1370 pkt.data = audio_outbuf;
1374 if ( av_interleaved_write_frame( oc, &pkt ) )
1376 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1377 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1378 goto on_fatal_error;
1382 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1385 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1394 else if ( video_st )
1397 if ( mlt_deque_count( queue ) )
1399 int out_size, ret = 0;
1402 frame = mlt_deque_pop_front( queue );
1403 frame_properties = MLT_FRAME_PROPERTIES( frame );
1405 c = video_st->codec;
1407 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1413 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1417 // Convert the mlt frame to an AVPicture
1418 for ( i = 0; i < height; i ++ )
1420 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1421 memcpy( p, q, width * 2 );
1425 // Do the colour space conversion
1427 int flags = SWS_BILINEAR;
1429 flags |= SWS_CPU_CAPS_MMX;
1432 flags |= SWS_CPU_CAPS_MMX2;
1434 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1435 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1436 sws_scale( context, input->data, input->linesize, 0, height,
1437 output->data, output->linesize);
1438 sws_freeContext( context );
1440 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1443 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1445 // Apply the alpha if applicable
1446 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1448 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1451 for ( i = 0; i < height; i ++ )
1453 n = ( width + 7 ) / 8;
1454 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1458 case 0: do { *p = *alpha++; p += 4;
1459 case 7: *p = *alpha++; p += 4;
1460 case 6: *p = *alpha++; p += 4;
1461 case 5: *p = *alpha++; p += 4;
1462 case 4: *p = *alpha++; p += 4;
1463 case 3: *p = *alpha++; p += 4;
1464 case 2: *p = *alpha++; p += 4;
1465 case 1: *p = *alpha++; p += 4;
1473 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1475 // raw video case. The API will change slightly in the near future for that
1477 av_init_packet(&pkt);
1479 pkt.flags |= PKT_FLAG_KEY;
1480 pkt.stream_index= video_st->index;
1481 pkt.data= (uint8_t *)output;
1482 pkt.size= sizeof(AVPicture);
1484 ret = av_write_frame(oc, &pkt);
1485 video_pts += c->frame_size;
1490 output->quality = video_st->quality;
1492 // Set frame interlace hints
1493 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1494 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1495 output->pts = frame_count;
1498 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1500 // If zero size, it means the image was buffered
1504 av_init_packet( &pkt );
1506 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1507 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1508 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1509 if( c->coded_frame && c->coded_frame->key_frame )
1510 pkt.flags |= PKT_FLAG_KEY;
1511 pkt.stream_index= video_st->index;
1512 pkt.data= video_outbuf;
1515 // write the compressed frame in the media file
1516 ret = av_interleaved_write_frame(oc, &pkt);
1517 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1518 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1520 // Dual pass logging
1521 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1522 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1524 else if ( out_size < 0 )
1526 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1532 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1533 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1534 goto on_fatal_error;
1536 mlt_frame_close( frame );
1544 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %lld (%f) ", audio_st[0]->pts.val, audio_pts );
1546 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %lld (%f) ", video_st->pts.val, video_pts );
1547 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1550 if ( real_time_output == 1 && frames % 2 == 0 )
1552 long passed = time_difference( &ante );
1555 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1558 if ( passed < total_time )
1560 long total = ( total_time - passed );
1561 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1562 nanosleep( &t, NULL );
1567 // Flush the encoder buffers
1568 if ( real_time_output <= 0 )
1571 // TODO: flush all audio streams
1572 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1574 AVCodecContext *c = audio_st[0]->codec;
1576 av_init_packet( &pkt );
1579 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1580 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1582 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size );
1583 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1585 if ( pkt.size <= 0 )
1586 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1587 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1588 if ( pkt.size <= 0 )
1591 // Write the compressed frame in the media file
1592 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1593 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1594 pkt.flags |= PKT_FLAG_KEY;
1595 pkt.stream_index = audio_st[0]->index;
1596 pkt.data = audio_outbuf;
1597 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1599 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1600 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1601 goto on_fatal_error;
1606 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1608 AVCodecContext *c = video_st->codec;
1610 av_init_packet( &pkt );
1613 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1614 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1615 if ( pkt.size <= 0 )
1618 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1619 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1620 if( c->coded_frame && c->coded_frame->key_frame )
1621 pkt.flags |= PKT_FLAG_KEY;
1622 pkt.stream_index = video_st->index;
1623 pkt.data = video_outbuf;
1625 // write the compressed frame in the media file
1626 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1628 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1629 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1630 goto on_fatal_error;
1632 // Dual pass logging
1633 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1634 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1640 // Write the trailer, if any
1641 av_write_trailer( oc );
1645 close_video(oc, video_st);
1646 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1647 close_audio( oc, audio_st[i] );
1650 for ( i = 0; i < oc->nb_streams; i++ )
1651 av_freep( &oc->streams[i] );
1653 // Close the output file
1654 if ( !( fmt->flags & AVFMT_NOFILE ) )
1655 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1656 url_fclose( oc->pb );
1658 url_fclose( &oc->pb );
1661 // Clean up input and output frames
1663 av_free( output->data[0] );
1665 av_free( input->data[0] );
1667 av_free( video_outbuf );
1668 av_free( audio_buf_1 );
1669 av_free( audio_buf_2 );
1674 // Just in case we terminated on pause
1675 mlt_properties_set_int( properties, "running", 0 );
1677 mlt_consumer_stopped( consumer );
1678 mlt_properties_close( frame_meta_properties );
1680 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1682 // Remove the dual pass log file
1683 if ( mlt_properties_get( properties, "_logfilename" ) )
1684 remove( mlt_properties_get( properties, "_logfilename" ) );
1686 // Remove the x264 dual pass logs
1687 char *cwd = getcwd( NULL, 0 );
1688 const char *file = "x264_2pass.log";
1689 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1690 sprintf( full, "%s/%s", cwd, file );
1693 file = "x264_2pass.log.temp";
1694 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1695 sprintf( full, "%s/%s", cwd, file );
1698 file = "x264_2pass.log.mbtree";
1699 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1700 sprintf( full, "%s/%s", cwd, file );
1704 remove( "x264_2pass.log.temp" );
1710 /** Close the consumer.
1713 static void consumer_close( mlt_consumer consumer )
1715 // Stop the consumer
1716 mlt_consumer_stop( consumer );
1719 mlt_consumer_close( consumer );