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_value( properties, i), alloc, NULL );
403 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
404 av_set_string2( obj, opt_name, mlt_properties_get_value( properties, i), alloc );
406 av_set_string( obj, opt_name, mlt_properties_get_value( properties, i) );
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;
501 codec = avcodec_find_encoder_by_name( codec_name );
503 codec = avcodec_find_encoder( c->codec_id );
507 // Continue if codec found and we can open it
508 if ( codec != NULL && avcodec_open( c, codec ) >= 0 )
510 // ugly hack for PCM codecs (will be removed ASAP with new PCM
511 // support to compute the input frame size in samples
512 if ( c->frame_size <= 1 )
514 audio_input_frame_size = audio_outbuf_size / c->channels;
515 switch(st->codec->codec_id)
517 case CODEC_ID_PCM_S16LE:
518 case CODEC_ID_PCM_S16BE:
519 case CODEC_ID_PCM_U16LE:
520 case CODEC_ID_PCM_U16BE:
521 audio_input_frame_size >>= 1;
529 audio_input_frame_size = c->frame_size;
532 // Some formats want stream headers to be seperate (hmm)
533 if ( !strcmp( oc->oformat->name, "mp4" ) ||
534 !strcmp( oc->oformat->name, "mov" ) ||
535 !strcmp( oc->oformat->name, "3gp" ) )
536 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
540 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
545 return audio_input_frame_size;
548 static void close_audio( AVFormatContext *oc, AVStream *st )
550 if ( st && st->codec )
553 avcodec_close( st->codec );
558 /** Add a video output stream
561 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, int codec_id )
563 // Get the properties
564 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
566 // Create a new stream
567 AVStream *st = av_new_stream( oc, oc->nb_streams );
571 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
572 AVCodecContext *c = st->codec;
574 // Establish defaults from AVOptions
575 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
577 c->codec_id = codec_id;
578 c->codec_type = CODEC_TYPE_VIDEO;
580 // Setup multi-threading
581 int thread_count = mlt_properties_get_int( properties, "threads" );
582 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
583 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
584 if ( thread_count > 1 )
585 avcodec_thread_init( c, thread_count );
587 // Process properties as AVOptions
588 char *vpre = mlt_properties_get( properties, "vpre" );
591 mlt_properties p = mlt_properties_load( vpre );
593 if ( mlt_properties_count( p ) < 1 )
595 AVCodec *codec = avcodec_find_encoder( c->codec_id );
598 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
599 strcpy( path, AVDATADIR );
600 strcat( path, codec->name );
602 strcat( path, vpre );
603 strcat( path, ".ffpreset" );
605 mlt_properties_close( p );
606 p = mlt_properties_load( path );
607 mlt_properties_debug( p, path, stderr );
613 mlt_properties_debug( p, vpre, stderr );
616 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
617 mlt_properties_close( p );
619 int colorspace = mlt_properties_get_int( properties, "colorspace" );
620 mlt_properties_set( properties, "colorspace", NULL );
621 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
622 mlt_properties_set_int( properties, "colorspace", colorspace );
624 // Set options controlled by MLT
625 c->width = mlt_properties_get_int( properties, "width" );
626 c->height = mlt_properties_get_int( properties, "height" );
627 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
628 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
629 if ( st->time_base.den == 0 )
630 st->time_base = c->time_base;
631 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
632 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
634 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
637 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
638 switch ( colorspace )
641 c->colorspace = AVCOL_SPC_SMPTE170M;
644 c->colorspace = AVCOL_SPC_SMPTE240M;
647 c->colorspace = AVCOL_SPC_BT470BG;
650 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
653 c->colorspace = AVCOL_SPC_BT709;
658 if ( mlt_properties_get( properties, "aspect" ) )
660 // "-aspect" on ffmpeg command line is display aspect ratio
661 double ar = mlt_properties_get_double( properties, "aspect" );
662 AVRational rational = av_d2q( ar, 255 );
664 // Update the profile and properties as well since this is an alias
665 // for mlt properties that correspond to profile settings
666 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
667 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
668 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
671 profile->display_aspect_num = rational.num;
672 profile->display_aspect_den = rational.den;
673 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
676 // Now compute the sample aspect ratio
677 rational = av_d2q( ar * c->height / c->width, 255 );
678 c->sample_aspect_ratio = rational;
679 // Update the profile and properties as well since this is an alias
680 // for mlt properties that correspond to profile settings
681 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
682 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
685 profile->sample_aspect_num = rational.num;
686 profile->sample_aspect_den = rational.den;
687 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
692 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
693 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
695 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
696 st->sample_aspect_ratio = c->sample_aspect_ratio;
699 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
701 c->flags |= CODEC_FLAG_QSCALE;
702 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
705 // Allow the user to override the video fourcc
706 if ( mlt_properties_get( properties, "vtag" ) )
709 const char *arg = mlt_properties_get( properties, "vtag" );
710 int tag = strtol( arg, &tail, 0);
712 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
716 // Some formats want stream headers to be seperate
717 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
718 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
720 // Translate these standard mlt consumer properties to ffmpeg
721 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
722 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
724 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
725 c->flags |= CODEC_FLAG_INTERLACED_DCT;
726 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
727 c->flags |= CODEC_FLAG_INTERLACED_ME;
730 // parse the ratecontrol override string
732 char *rc_override = mlt_properties_get( properties, "rc_override" );
733 for ( i = 0; rc_override; i++ )
736 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
738 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
739 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
740 c->rc_override[i].start_frame = start;
741 c->rc_override[i].end_frame = end;
744 c->rc_override[i].qscale = q;
745 c->rc_override[i].quality_factor = 1.0;
749 c->rc_override[i].qscale = 0;
750 c->rc_override[i].quality_factor = -q / 100.0;
752 rc_override = strchr( rc_override, '/' );
756 c->rc_override_count = i;
757 if ( !c->rc_initial_buffer_occupancy )
758 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
759 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
762 i = mlt_properties_get_int( properties, "pass" );
764 c->flags |= CODEC_FLAG_PASS1;
766 c->flags |= CODEC_FLAG_PASS2;
767 if ( codec_id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
769 char logfilename[1024];
774 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
775 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
776 if ( c->flags & CODEC_FLAG_PASS1 )
778 f = fopen( logfilename, "w" );
780 perror( logfilename );
782 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
786 /* read the log file */
787 f = fopen( logfilename, "r" );
794 mlt_properties_set( properties, "_logfilename", logfilename );
795 fseek( f, 0, SEEK_END );
797 fseek( f, 0, SEEK_SET );
798 logbuffer = av_malloc( size + 1 );
800 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
803 size = fread( logbuffer, 1, size, f );
805 logbuffer[size] = '\0';
806 c->stats_in = logbuffer;
807 mlt_properties_set_data( properties, "_logbuffer", logbuffer, 0, ( mlt_destructor )av_free, NULL );
815 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
821 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
824 AVFrame *picture = avcodec_alloc_frame();
826 // Determine size of the
827 int size = avpicture_get_size(pix_fmt, width, height);
829 // Allocate the picture buf
830 uint8_t *picture_buf = av_malloc(size);
832 // If we have both, then fill the image
833 if ( picture != NULL && picture_buf != NULL )
835 // Fill the frame with the allocated buffer
836 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
840 // Something failed - clean up what we can
842 av_free( picture_buf );
849 static int open_video(AVFormatContext *oc, AVStream *st, const char *codec_name)
852 AVCodecContext *video_enc = st->codec;
854 // find the video encoder
857 codec = avcodec_find_encoder_by_name( codec_name );
859 codec = avcodec_find_encoder( video_enc->codec_id );
861 if( codec && codec->pix_fmts )
863 const enum PixelFormat *p = codec->pix_fmts;
866 if( *p == video_enc->pix_fmt )
870 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
873 // Open the codec safely
875 int result = codec != NULL && avcodec_open( video_enc, codec ) >= 0;
881 void close_video(AVFormatContext *oc, AVStream *st)
883 if ( st && st->codec )
886 avcodec_close(st->codec);
891 static inline long time_difference( struct timeval *time1 )
893 struct timeval time2;
894 gettimeofday( &time2, NULL );
895 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
898 /** The main thread - the argument is simply the consumer.
901 static void *consumer_thread( void *arg )
903 // Map the argument to the object
904 mlt_consumer consumer = arg;
906 // Get the properties
907 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
909 // Get the terminate on pause property
910 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
913 // Determine if feed is slow (for realtime stuff)
914 int real_time_output = mlt_properties_get_int( properties, "real_time" );
919 // Get the frame rate
920 double fps = mlt_properties_get_double( properties, "fps" );
922 // Get width and height
923 int width = mlt_properties_get_int( properties, "width" );
924 int height = mlt_properties_get_int( properties, "height" );
925 int img_width = width;
926 int img_height = height;
928 // Get default audio properties
929 mlt_audio_format aud_fmt = mlt_audio_s16;
930 int channels = mlt_properties_get_int( properties, "channels" );
931 int total_channels = channels;
932 int frequency = mlt_properties_get_int( properties, "frequency" );
936 // AVFormat audio buffer and frame size
937 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
938 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
939 int audio_input_frame_size = 0;
941 // AVFormat video buffer and frame count
943 int video_outbuf_size = VIDEO_BUFFER_SIZE;
944 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
946 // Used for the frame properties
947 mlt_frame frame = NULL;
948 mlt_properties frame_properties = NULL;
951 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
952 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
954 // Need two av pictures for converting
955 AVFrame *output = NULL;
956 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
958 // For receiving images from an mlt_frame
960 mlt_image_format img_fmt = mlt_image_yuv422;
962 // For receiving audio samples back from the fifo
963 int16_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
964 int16_t *audio_buf_2 = NULL;
967 // Allocate the context
968 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
969 AVFormatContext *oc = avformat_alloc_context( );
971 AVFormatContext *oc = av_alloc_format_context( );
975 AVStream *video_st = NULL;
976 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
979 double audio_pts = 0;
980 double video_pts = 0;
984 long int total_time = 0;
986 // Determine the format
987 AVOutputFormat *fmt = NULL;
988 const char *filename = mlt_properties_get( properties, "target" );
989 char *format = mlt_properties_get( properties, "f" );
990 char *vcodec = mlt_properties_get( properties, "vcodec" );
991 char *acodec = mlt_properties_get( properties, "acodec" );
993 // Used to store and override codec ids
999 mlt_properties frame_meta_properties = mlt_properties_new();
1001 // Initialize audio_st
1002 int i = MAX_AUDIO_STREAMS;
1006 // Check for user selected format first
1007 if ( format != NULL )
1008 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1009 fmt = guess_format( format, NULL, NULL );
1011 fmt = av_guess_format( format, NULL, NULL );
1014 // Otherwise check on the filename
1015 if ( fmt == NULL && filename != NULL )
1016 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1017 fmt = guess_format( NULL, filename, NULL );
1019 fmt = av_guess_format( NULL, filename, NULL );
1022 // Otherwise default to mpeg
1024 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1025 fmt = guess_format( "mpeg", NULL, NULL );
1027 fmt = av_guess_format( "mpeg", NULL, NULL );
1030 // We need a filename - default to stdout?
1031 if ( filename == NULL || !strcmp( filename, "" ) )
1034 // Get the codec ids selected
1035 audio_codec_id = fmt->audio_codec;
1036 video_codec_id = fmt->video_codec;
1038 // Check for audio codec overides
1039 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1040 audio_codec_id = CODEC_ID_NONE;
1043 AVCodec *p = avcodec_find_encoder_by_name( acodec );
1046 audio_codec_id = p->id;
1047 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1049 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1050 acodec = mlt_properties_get( properties, "_acodec" );
1055 audio_codec_id = CODEC_ID_NONE;
1056 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1060 // Check for video codec overides
1061 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1062 video_codec_id = CODEC_ID_NONE;
1065 AVCodec *p = avcodec_find_encoder_by_name( vcodec );
1068 video_codec_id = p->id;
1072 video_codec_id = CODEC_ID_NONE;
1073 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1078 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1079 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1081 char *name = mlt_properties_get_name( properties, i );
1082 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1084 char *key = strdup( name + 10 );
1085 char *markup = strrchr( key, '.' );
1086 if ( markup && !strcmp( markup, ".markup") )
1089 if ( !strstr( key, ".stream." ) )
1090 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1091 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1093 av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1103 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1104 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1106 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1107 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1109 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1110 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1112 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1113 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1115 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1116 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1118 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1119 if (metavalue != 0) oc->year = metavalue;
1121 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1122 if (metavalue != 0) oc->track = metavalue;
1126 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1128 // Add audio and video streams
1129 if ( video_codec_id != CODEC_ID_NONE )
1130 video_st = add_video_stream( consumer, oc, video_codec_id );
1131 if ( audio_codec_id != CODEC_ID_NONE )
1137 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1139 sprintf( key, "channels.%d", i );
1140 int j = mlt_properties_get_int( properties, key );
1144 total_channels += j;
1145 audio_st[i] = add_audio_stream( consumer, oc, audio_codec_id, j );
1151 audio_st[0] = add_audio_stream( consumer, oc, audio_codec_id, channels );
1152 total_channels = channels;
1156 // Set the parameters (even though we have none...)
1157 if ( av_set_parameters(oc, NULL) >= 0 )
1159 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1160 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1162 // Process properties as AVOptions
1163 char *fpre = mlt_properties_get( properties, "fpre" );
1166 mlt_properties p = mlt_properties_load( fpre );
1167 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM, 1 );
1168 mlt_properties_close( p );
1170 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM, 0 );
1172 if ( video_st && !open_video( oc, video_st, vcodec? vcodec : NULL ) )
1174 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1176 audio_input_frame_size = open_audio( oc, audio_st[i], audio_outbuf_size,
1177 acodec? acodec : NULL );
1178 if ( !audio_input_frame_size )
1182 // Open the output file, if needed
1183 if ( !( fmt->flags & AVFMT_NOFILE ) )
1185 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1187 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1188 mlt_properties_set_int( properties, "running", 0 );
1192 // Write the stream header.
1193 if ( mlt_properties_get_int( properties, "running" ) )
1194 av_write_header( oc );
1198 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1199 mlt_properties_set_int( properties, "running", 0 );
1204 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1206 // Last check - need at least one stream
1207 if ( !audio_st[0] && !video_st )
1208 mlt_properties_set_int( properties, "running", 0 );
1210 // Get the starting time (can ignore the times above)
1211 gettimeofday( &ante, NULL );
1213 // Loop while running
1214 while( mlt_properties_get_int( properties, "running" ) &&
1215 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1217 frame = mlt_consumer_rt_frame( consumer );
1219 // Check that we have a frame to work with
1220 if ( frame != NULL )
1222 // Increment frames dispatched
1225 // Default audio args
1226 frame_properties = MLT_FRAME_PROPERTIES( frame );
1228 // Check for the terminated condition
1229 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1231 // Get audio and append to the fifo
1232 if ( !terminated && audio_st[0] )
1234 samples = mlt_sample_calculator( fps, frequency, count ++ );
1235 mlt_frame_get_audio( frame, (void**) &pcm, &aud_fmt, &frequency, &channels, &samples );
1237 // Save the audio channel remap properties for later
1238 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1240 // Create the fifo if we don't have one
1243 fifo = sample_fifo_init( frequency, channels );
1244 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1247 // Silence if not normal forward speed
1248 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1249 memset( pcm, 0, samples * channels * 2 );
1251 // Append the samples
1252 sample_fifo_append( fifo, pcm, samples * channels );
1253 total_time += ( samples * 1000000 ) / frequency;
1256 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1260 if ( !terminated && video_st )
1261 mlt_deque_push_back( queue, frame );
1263 mlt_frame_close( frame );
1266 // While we have stuff to process, process...
1269 // Write interleaved audio and video frames
1270 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1273 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1275 int j = 0; // channel offset into interleaved source buffer
1276 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) ), AUDIO_ENCODE_BUFFER_SIZE );
1278 // Get the audio samples
1281 sample_fifo_fetch( fifo, audio_buf_1, n );
1283 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1285 // This prevents an infinite loop when some versions of vorbis do not
1286 // increment pts when encoding silence.
1287 audio_pts = video_pts;
1292 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1294 samples = n / channels;
1296 // For each output stream
1297 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1299 AVStream *stream = audio_st[i];
1300 AVCodecContext *codec = stream->codec;
1303 av_init_packet( &pkt );
1305 // Optimized for single track and no channel remap
1306 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1308 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1312 // Extract the audio channels according to channel mapping
1313 int dest_offset = 0; // channel offset into interleaved dest buffer
1315 // Get the number of channels for this stream
1316 sprintf( key, "channels.%d", i );
1317 int current_channels = mlt_properties_get_int( properties, key );
1319 // Clear the destination audio buffer.
1321 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1323 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1325 // For each output channel
1326 while ( dest_offset < current_channels && j < total_channels )
1328 int map_start = -1, map_channels = 0;
1329 int source_offset = 0;
1332 // Look for a mapping that starts at j
1333 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1335 sprintf( key, "%d.channels", k );
1336 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1337 sprintf( key, "%d.start", k );
1338 if ( mlt_properties_get( frame_meta_properties, key ) )
1339 map_start = mlt_properties_get_int( frame_meta_properties, key );
1340 if ( map_start != j )
1341 source_offset += map_channels;
1345 if ( map_start != j )
1347 map_channels = current_channels;
1351 // Copy samples if source offset valid
1352 if ( source_offset < channels )
1354 // Interleave the audio buffer with the # channels for this stream/mapping.
1355 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1357 int16_t *src = audio_buf_1 + source_offset;
1358 int16_t *dest = audio_buf_2 + dest_offset;
1359 int s = samples + 1;
1363 dest += current_channels;
1368 // Otherwise silence
1371 j += current_channels;
1372 dest_offset += current_channels;
1375 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_2 );
1378 // Write the compressed frame in the media file
1379 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1381 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1382 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %lld frame pts %lld",
1383 stream->index, pkt.pts, codec->coded_frame->pts );
1385 pkt.flags |= PKT_FLAG_KEY;
1386 pkt.stream_index = stream->index;
1387 pkt.data = audio_outbuf;
1391 if ( av_interleaved_write_frame( oc, &pkt ) )
1393 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1394 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1395 goto on_fatal_error;
1399 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1402 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1411 else if ( video_st )
1414 if ( mlt_deque_count( queue ) )
1416 int out_size, ret = 0;
1419 frame = mlt_deque_pop_front( queue );
1420 frame_properties = MLT_FRAME_PROPERTIES( frame );
1422 c = video_st->codec;
1424 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1430 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1434 // Convert the mlt frame to an AVPicture
1435 for ( i = 0; i < height; i ++ )
1437 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1438 memcpy( p, q, width * 2 );
1442 // Do the colour space conversion
1444 int flags = SWS_BILINEAR;
1446 flags |= SWS_CPU_CAPS_MMX;
1449 flags |= SWS_CPU_CAPS_MMX2;
1451 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1452 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1453 sws_scale( context, input->data, input->linesize, 0, height,
1454 output->data, output->linesize);
1455 sws_freeContext( context );
1457 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1460 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1462 // Apply the alpha if applicable
1463 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1465 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1468 for ( i = 0; i < height; i ++ )
1470 n = ( width + 7 ) / 8;
1471 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1475 case 0: do { *p = *alpha++; p += 4;
1476 case 7: *p = *alpha++; p += 4;
1477 case 6: *p = *alpha++; p += 4;
1478 case 5: *p = *alpha++; p += 4;
1479 case 4: *p = *alpha++; p += 4;
1480 case 3: *p = *alpha++; p += 4;
1481 case 2: *p = *alpha++; p += 4;
1482 case 1: *p = *alpha++; p += 4;
1490 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1492 // raw video case. The API will change slightly in the near future for that
1494 av_init_packet(&pkt);
1496 pkt.flags |= PKT_FLAG_KEY;
1497 pkt.stream_index= video_st->index;
1498 pkt.data= (uint8_t *)output;
1499 pkt.size= sizeof(AVPicture);
1501 ret = av_write_frame(oc, &pkt);
1502 video_pts += c->frame_size;
1507 output->quality = video_st->quality;
1509 // Set frame interlace hints
1510 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1511 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1512 output->pts = frame_count;
1515 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1517 // If zero size, it means the image was buffered
1521 av_init_packet( &pkt );
1523 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1524 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1525 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1526 if( c->coded_frame && c->coded_frame->key_frame )
1527 pkt.flags |= PKT_FLAG_KEY;
1528 pkt.stream_index= video_st->index;
1529 pkt.data= video_outbuf;
1532 // write the compressed frame in the media file
1533 ret = av_interleaved_write_frame(oc, &pkt);
1534 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1535 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1537 // Dual pass logging
1538 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1539 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1541 else if ( out_size < 0 )
1543 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1549 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1550 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1551 goto on_fatal_error;
1553 mlt_frame_close( frame );
1561 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %lld (%f) ", audio_st[0]->pts.val, audio_pts );
1563 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %lld (%f) ", video_st->pts.val, video_pts );
1564 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1567 if ( real_time_output == 1 && frames % 2 == 0 )
1569 long passed = time_difference( &ante );
1572 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1575 if ( passed < total_time )
1577 long total = ( total_time - passed );
1578 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1579 nanosleep( &t, NULL );
1584 // Flush the encoder buffers
1585 if ( real_time_output <= 0 )
1588 // TODO: flush all audio streams
1589 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1591 AVCodecContext *c = audio_st[0]->codec;
1593 av_init_packet( &pkt );
1596 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1597 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1599 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size );
1600 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1602 if ( pkt.size <= 0 )
1603 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1604 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1605 if ( pkt.size <= 0 )
1608 // Write the compressed frame in the media file
1609 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1610 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1611 pkt.flags |= PKT_FLAG_KEY;
1612 pkt.stream_index = audio_st[0]->index;
1613 pkt.data = audio_outbuf;
1614 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1616 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1617 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1618 goto on_fatal_error;
1623 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1625 AVCodecContext *c = video_st->codec;
1627 av_init_packet( &pkt );
1630 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1631 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1632 if ( pkt.size <= 0 )
1635 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1636 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1637 if( c->coded_frame && c->coded_frame->key_frame )
1638 pkt.flags |= PKT_FLAG_KEY;
1639 pkt.stream_index = video_st->index;
1640 pkt.data = video_outbuf;
1642 // write the compressed frame in the media file
1643 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1645 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1646 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1647 goto on_fatal_error;
1649 // Dual pass logging
1650 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1651 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1657 // Write the trailer, if any
1658 av_write_trailer( oc );
1662 close_video(oc, video_st);
1663 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1664 close_audio( oc, audio_st[i] );
1667 for ( i = 0; i < oc->nb_streams; i++ )
1668 av_freep( &oc->streams[i] );
1670 // Close the output file
1671 if ( !( fmt->flags & AVFMT_NOFILE ) )
1672 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1673 url_fclose( oc->pb );
1675 url_fclose( &oc->pb );
1678 // Clean up input and output frames
1680 av_free( output->data[0] );
1682 av_free( input->data[0] );
1684 av_free( video_outbuf );
1685 av_free( audio_buf_1 );
1686 av_free( audio_buf_2 );
1691 // Just in case we terminated on pause
1692 mlt_properties_set_int( properties, "running", 0 );
1694 mlt_consumer_stopped( consumer );
1695 mlt_properties_close( frame_meta_properties );
1697 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1699 // Remove the dual pass log file
1700 if ( mlt_properties_get( properties, "_logfilename" ) )
1701 remove( mlt_properties_get( properties, "_logfilename" ) );
1703 // Remove the x264 dual pass logs
1704 char *cwd = getcwd( NULL, 0 );
1705 const char *file = "x264_2pass.log";
1706 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1707 sprintf( full, "%s/%s", cwd, file );
1710 file = "x264_2pass.log.temp";
1711 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1712 sprintf( full, "%s/%s", cwd, file );
1715 file = "x264_2pass.log.mbtree";
1716 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1717 sprintf( full, "%s/%s", cwd, file );
1721 remove( "x264_2pass.log.temp" );
1727 /** Close the consumer.
1730 static void consumer_close( mlt_consumer consumer )
1732 // Stop the consumer
1733 mlt_consumer_stop( consumer );
1736 mlt_consumer_close( consumer );