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)
56 void avformat_lock( );
57 void avformat_unlock( );
60 // This structure should be extended and made globally available in mlt
72 *sample_fifo, sample_fifo_s;
74 sample_fifo sample_fifo_init( int frequency, int channels )
76 sample_fifo this = calloc( 1, sizeof( sample_fifo_s ) );
77 this->frequency = frequency;
78 this->channels = channels;
82 // sample_fifo_clear and check are temporarily aborted (not working as intended)
84 void sample_fifo_clear( sample_fifo this, double time )
86 int words = ( float )( time - this->time ) * this->frequency * this->channels;
87 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) && this->used > words && words > 0 )
89 memmove( this->buffer, &this->buffer[ words ], ( this->used - words ) * sizeof( int16_t ) );
93 else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )this->time * 100 ) )
100 void sample_fifo_check( sample_fifo this, double time )
102 if ( this->used == 0 )
104 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) )
109 void sample_fifo_append( sample_fifo this, int16_t *samples, int count )
111 if ( ( this->size - this->used ) < count )
113 this->size += count * 5;
114 this->buffer = realloc( this->buffer, this->size * sizeof( int16_t ) );
117 memcpy( &this->buffer[ this->used ], samples, count * sizeof( int16_t ) );
121 int sample_fifo_used( sample_fifo this )
126 int sample_fifo_fetch( sample_fifo this, int16_t *samples, int count )
128 if ( count > this->used )
131 memcpy( samples, this->buffer, count * sizeof( int16_t ) );
133 memmove( this->buffer, &this->buffer[ count ], this->used * sizeof( int16_t ) );
135 this->time += ( double )count / this->channels / this->frequency;
140 void sample_fifo_close( sample_fifo this )
142 free( this->buffer );
146 // Forward references.
147 static int consumer_start( mlt_consumer this );
148 static int consumer_stop( mlt_consumer this );
149 static int consumer_is_stopped( mlt_consumer this );
150 static void *consumer_thread( void *arg );
151 static void consumer_close( mlt_consumer this );
153 /** Initialise the consumer.
156 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
158 // Allocate the consumer
159 mlt_consumer this = mlt_consumer_new( profile );
161 // If memory allocated and initialises without error
164 // Get properties from the consumer
165 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
167 // Assign close callback
168 this->close = consumer_close;
170 // Interpret the argument
172 mlt_properties_set( properties, "target", arg );
174 // sample and frame queue
175 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
177 // Audio options not fully handled by AVOptions
178 #define QSCALE_NONE (-99999)
179 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
181 // Video options not fully handled by AVOptions
182 mlt_properties_set_int( properties, "dc", 8 );
184 // Muxer options not fully handled by AVOptions
185 mlt_properties_set_double( properties, "muxdelay", 0.7 );
186 mlt_properties_set_double( properties, "muxpreload", 0.5 );
188 // Ensure termination at end of the stream
189 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
191 // Default to separate processing threads for producer and consumer with no frame dropping!
192 mlt_properties_set_int( properties, "real_time", -1 );
193 mlt_properties_set_int( properties, "prefill", 1 );
195 // Set up start/stop/terminated callbacks
196 this->start = consumer_start;
197 this->stop = consumer_stop;
198 this->is_stopped = consumer_is_stopped;
200 mlt_events_register( properties, "consumer-fatal-error", NULL );
207 /** Start the consumer.
210 static int consumer_start( mlt_consumer this )
212 // Get the properties
213 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
216 // Report information about available muxers and codecs as YAML Tiny
217 char *s = mlt_properties_get( properties, "f" );
218 if ( s && strcmp( s, "list" ) == 0 )
220 mlt_properties doc = mlt_properties_new();
221 mlt_properties formats = mlt_properties_new();
223 AVOutputFormat *format = NULL;
225 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
226 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
227 while ( ( format = av_oformat_next( format ) ) )
229 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
230 mlt_properties_set( formats, key, format->name );
232 fprintf( stderr, "%s", mlt_properties_serialise_yaml( doc ) );
233 mlt_properties_close( doc );
236 s = mlt_properties_get( properties, "acodec" );
237 if ( s && strcmp( s, "list" ) == 0 )
239 mlt_properties doc = mlt_properties_new();
240 mlt_properties codecs = mlt_properties_new();
242 AVCodec *codec = NULL;
244 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
245 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
246 while ( ( codec = av_codec_next( codec ) ) )
247 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
249 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
250 mlt_properties_set( codecs, key, codec->name );
252 fprintf( stderr, "%s", mlt_properties_serialise_yaml( doc ) );
253 mlt_properties_close( doc );
256 s = mlt_properties_get( properties, "vcodec" );
257 if ( s && strcmp( s, "list" ) == 0 )
259 mlt_properties doc = mlt_properties_new();
260 mlt_properties codecs = mlt_properties_new();
262 AVCodec *codec = NULL;
264 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
265 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
266 while ( ( codec = av_codec_next( codec ) ) )
267 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
269 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
270 mlt_properties_set( codecs, key, codec->name );
272 fprintf( stderr, "%s", mlt_properties_serialise_yaml( doc ) );
273 mlt_properties_close( doc );
277 // Check that we're not already running
278 if ( !error && !mlt_properties_get_int( properties, "running" ) )
281 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
283 // Get the width and height
284 int width = mlt_properties_get_int( properties, "width" );
285 int height = mlt_properties_get_int( properties, "height" );
287 // Obtain the size property
288 char *size = mlt_properties_get( properties, "s" );
294 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
301 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "Invalid size property %s - ignoring.\n", size );
305 // Now ensure we honour the multiple of two requested by libavformat
306 width = ( width / 2 ) * 2;
307 height = ( height / 2 ) * 2;
308 mlt_properties_set_int( properties, "width", width );
309 mlt_properties_set_int( properties, "height", height );
311 // We need to set these on the profile as well because the s property is
312 // an alias to mlt properties that correspond to profile settings.
313 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
316 profile->width = width;
317 profile->height = height;
320 // Handle the ffmpeg command line "-r" property for frame rate
321 if ( mlt_properties_get( properties, "r" ) )
323 double frame_rate = mlt_properties_get_double( properties, "r" );
324 AVRational rational = av_d2q( frame_rate, 255 );
325 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
326 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
329 profile->frame_rate_num = rational.num;
330 profile->frame_rate_den = rational.den;
331 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
335 // Apply AVOptions that are synonyms for standard mlt_consumer options
336 if ( mlt_properties_get( properties, "ac" ) )
337 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
338 if ( mlt_properties_get( properties, "ar" ) )
339 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
341 // Assign the thread to properties
342 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
344 // Set the running state
345 mlt_properties_set_int( properties, "running", 1 );
348 pthread_create( thread, NULL, consumer_thread, this );
353 /** Stop the consumer.
356 static int consumer_stop( mlt_consumer this )
358 // Get the properties
359 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
361 // Check that we're running
362 if ( mlt_properties_get_int( properties, "running" ) )
365 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
368 mlt_properties_set_int( properties, "running", 0 );
370 // Wait for termination
371 pthread_join( *thread, NULL );
377 /** Determine if the consumer is stopped.
380 static int consumer_is_stopped( mlt_consumer this )
382 // Get the properties
383 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
384 return !mlt_properties_get_int( properties, "running" );
387 /** Process properties as AVOptions and apply to AV context obj
390 static void apply_properties( void *obj, mlt_properties properties, int flags, int alloc )
393 int count = mlt_properties_count( properties );
394 for ( i = 0; i < count; i++ )
396 const char *opt_name = mlt_properties_get_name( properties, i );
397 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
399 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
400 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), alloc, NULL );
401 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
402 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), alloc );
404 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
409 /** Add an audio output stream
412 static AVStream *add_audio_stream( mlt_consumer this, AVFormatContext *oc, int codec_id, int channels )
414 // Get the properties
415 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
417 // Create a new stream
418 AVStream *st = av_new_stream( oc, oc->nb_streams );
420 // If created, then initialise from properties
423 AVCodecContext *c = st->codec;
425 // Establish defaults from AVOptions
426 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
428 c->codec_id = codec_id;
429 c->codec_type = CODEC_TYPE_AUDIO;
430 c->sample_fmt = SAMPLE_FMT_S16;
432 #if 0 // disabled until some audio codecs are multi-threaded
433 // Setup multi-threading
434 int thread_count = mlt_properties_get_int( properties, "threads" );
435 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
436 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
437 if ( thread_count > 1 )
438 avcodec_thread_init( c, thread_count );
441 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
442 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
444 // Allow the user to override the audio fourcc
445 if ( mlt_properties_get( properties, "atag" ) )
448 char *arg = mlt_properties_get( properties, "atag" );
449 int tag = strtol( arg, &tail, 0);
451 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
455 // Process properties as AVOptions
456 char *apre = mlt_properties_get( properties, "apre" );
459 mlt_properties p = mlt_properties_load( apre );
460 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
461 mlt_properties_close( p );
463 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
465 int audio_qscale = mlt_properties_get_int( properties, "aq" );
466 if ( audio_qscale > QSCALE_NONE )
468 c->flags |= CODEC_FLAG_QSCALE;
469 c->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
472 // Set parameters controlled by MLT
473 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
474 c->time_base = ( AVRational ){ 1, c->sample_rate };
475 c->channels = channels;
477 if ( mlt_properties_get( properties, "alang" ) != NULL )
478 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
482 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not allocate a stream for audio\n" );
488 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
490 // We will return the audio input size from here
491 int audio_input_frame_size = 0;
494 AVCodecContext *c = st->codec;
497 AVCodec *codec = avcodec_find_encoder( c->codec_id );
501 // Continue if codec found and we can open it
502 if ( codec != NULL && avcodec_open( c, codec ) >= 0 )
504 // ugly hack for PCM codecs (will be removed ASAP with new PCM
505 // support to compute the input frame size in samples
506 if ( c->frame_size <= 1 )
508 audio_input_frame_size = audio_outbuf_size / c->channels;
509 switch(st->codec->codec_id)
511 case CODEC_ID_PCM_S16LE:
512 case CODEC_ID_PCM_S16BE:
513 case CODEC_ID_PCM_U16LE:
514 case CODEC_ID_PCM_U16BE:
515 audio_input_frame_size >>= 1;
523 audio_input_frame_size = c->frame_size;
526 // Some formats want stream headers to be seperate (hmm)
527 if ( !strcmp( oc->oformat->name, "mp4" ) ||
528 !strcmp( oc->oformat->name, "mov" ) ||
529 !strcmp( oc->oformat->name, "3gp" ) )
530 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
534 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
539 return audio_input_frame_size;
542 static void close_audio( AVFormatContext *oc, AVStream *st )
544 if ( st && st->codec )
547 avcodec_close( st->codec );
552 /** Add a video output stream
555 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
557 // Get the properties
558 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
560 // Create a new stream
561 AVStream *st = av_new_stream( oc, oc->nb_streams );
565 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
566 AVCodecContext *c = st->codec;
568 // Establish defaults from AVOptions
569 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
571 c->codec_id = codec_id;
572 c->codec_type = CODEC_TYPE_VIDEO;
574 // Setup multi-threading
575 int thread_count = mlt_properties_get_int( properties, "threads" );
576 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
577 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
578 if ( thread_count > 1 )
579 avcodec_thread_init( c, thread_count );
581 // Process properties as AVOptions
582 char *vpre = mlt_properties_get( properties, "vpre" );
585 mlt_properties p = mlt_properties_load( vpre );
587 if ( mlt_properties_count( p ) < 1 )
589 AVCodec *codec = avcodec_find_encoder( c->codec_id );
592 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
593 strcpy( path, AVDATADIR );
594 strcat( path, codec->name );
596 strcat( path, vpre );
597 strcat( path, ".ffpreset" );
599 mlt_properties_close( p );
600 p = mlt_properties_load( path );
601 mlt_properties_debug( p, path, stderr );
607 mlt_properties_debug( p, vpre, stderr );
610 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
611 mlt_properties_close( p );
613 int colorspace = mlt_properties_get_int( properties, "colorspace" );
614 mlt_properties_set( properties, "colorspace", NULL );
615 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
616 mlt_properties_set_int( properties, "colorspace", colorspace );
618 // Set options controlled by MLT
619 c->width = mlt_properties_get_int( properties, "width" );
620 c->height = mlt_properties_get_int( properties, "height" );
621 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
622 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
623 if ( st->time_base.den == 0 )
624 st->time_base = c->time_base;
625 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
626 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
628 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
631 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
632 switch ( colorspace )
635 c->colorspace = AVCOL_SPC_SMPTE170M;
638 c->colorspace = AVCOL_SPC_SMPTE240M;
641 c->colorspace = AVCOL_SPC_BT470BG;
644 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
647 c->colorspace = AVCOL_SPC_BT709;
652 if ( mlt_properties_get( properties, "aspect" ) )
654 // "-aspect" on ffmpeg command line is display aspect ratio
655 double ar = mlt_properties_get_double( properties, "aspect" );
656 AVRational rational = av_d2q( ar, 255 );
658 // Update the profile and properties as well since this is an alias
659 // for mlt properties that correspond to profile settings
660 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
661 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
662 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
665 profile->display_aspect_num = rational.num;
666 profile->display_aspect_den = rational.den;
667 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
670 // Now compute the sample aspect ratio
671 rational = av_d2q( ar * c->height / c->width, 255 );
672 c->sample_aspect_ratio = rational;
673 // Update the profile and properties as well since this is an alias
674 // for mlt properties that correspond to profile settings
675 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
676 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
679 profile->sample_aspect_num = rational.num;
680 profile->sample_aspect_den = rational.den;
681 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
686 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
687 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
689 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
690 st->sample_aspect_ratio = c->sample_aspect_ratio;
693 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
695 c->flags |= CODEC_FLAG_QSCALE;
696 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
699 // Allow the user to override the video fourcc
700 if ( mlt_properties_get( properties, "vtag" ) )
703 const char *arg = mlt_properties_get( properties, "vtag" );
704 int tag = strtol( arg, &tail, 0);
706 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
710 // Some formats want stream headers to be seperate
711 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
712 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
714 // Translate these standard mlt consumer properties to ffmpeg
715 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
716 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
718 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
719 c->flags |= CODEC_FLAG_INTERLACED_DCT;
720 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
721 c->flags |= CODEC_FLAG_INTERLACED_ME;
724 // parse the ratecontrol override string
726 char *rc_override = mlt_properties_get( properties, "rc_override" );
727 for ( i = 0; rc_override; i++ )
730 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
732 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "Error parsing rc_override\n" );
733 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
734 c->rc_override[i].start_frame = start;
735 c->rc_override[i].end_frame = end;
738 c->rc_override[i].qscale = q;
739 c->rc_override[i].quality_factor = 1.0;
743 c->rc_override[i].qscale = 0;
744 c->rc_override[i].quality_factor = -q / 100.0;
746 rc_override = strchr( rc_override, '/' );
750 c->rc_override_count = i;
751 if ( !c->rc_initial_buffer_occupancy )
752 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
753 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
756 i = mlt_properties_get_int( properties, "pass" );
758 c->flags |= CODEC_FLAG_PASS1;
760 c->flags |= CODEC_FLAG_PASS2;
761 if ( codec_id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
763 char logfilename[1024];
768 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
769 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
770 if ( c->flags & CODEC_FLAG_PASS1 )
772 f = fopen( logfilename, "w" );
774 perror( logfilename );
776 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
780 /* read the log file */
781 f = fopen( logfilename, "r" );
788 mlt_properties_set( properties, "_logfilename", logfilename );
789 fseek( f, 0, SEEK_END );
791 fseek( f, 0, SEEK_SET );
792 logbuffer = av_malloc( size + 1 );
794 mlt_log_fatal( MLT_CONSUMER_SERVICE( this ), "Could not allocate log buffer\n" );
797 size = fread( logbuffer, 1, size, f );
799 logbuffer[size] = '\0';
800 c->stats_in = logbuffer;
801 mlt_properties_set_data( properties, "_logbuffer", logbuffer, 0, ( mlt_destructor )av_free, NULL );
809 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not allocate a stream for video\n" );
815 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
818 AVFrame *picture = avcodec_alloc_frame();
820 // Determine size of the
821 int size = avpicture_get_size(pix_fmt, width, height);
823 // Allocate the picture buf
824 uint8_t *picture_buf = av_malloc(size);
826 // If we have both, then fill the image
827 if ( picture != NULL && picture_buf != NULL )
829 // Fill the frame with the allocated buffer
830 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
834 // Something failed - clean up what we can
836 av_free( picture_buf );
843 static int open_video(AVFormatContext *oc, AVStream *st)
846 AVCodecContext *video_enc = st->codec;
848 // find the video encoder
849 AVCodec *codec = avcodec_find_encoder( video_enc->codec_id );
851 if( codec && codec->pix_fmts )
853 const enum PixelFormat *p = codec->pix_fmts;
856 if( *p == video_enc->pix_fmt )
860 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
863 // Open the codec safely
865 int result = codec != NULL && avcodec_open( video_enc, codec ) >= 0;
871 void close_video(AVFormatContext *oc, AVStream *st)
873 if ( st && st->codec )
876 avcodec_close(st->codec);
881 static inline long time_difference( struct timeval *time1 )
883 struct timeval time2;
884 gettimeofday( &time2, NULL );
885 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
888 /** The main thread - the argument is simply the consumer.
891 static void *consumer_thread( void *arg )
893 // Map the argument to the object
894 mlt_consumer this = arg;
896 // Get the properties
897 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
899 // Get the terminate on pause property
900 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
903 // Determine if feed is slow (for realtime stuff)
904 int real_time_output = mlt_properties_get_int( properties, "real_time" );
909 // Get the frame rate
910 double fps = mlt_properties_get_double( properties, "fps" );
912 // Get width and height
913 int width = mlt_properties_get_int( properties, "width" );
914 int height = mlt_properties_get_int( properties, "height" );
915 int img_width = width;
916 int img_height = height;
918 // Get default audio properties
919 mlt_audio_format aud_fmt = mlt_audio_s16;
920 int channels = mlt_properties_get_int( properties, "channels" );
921 int total_channels = channels;
922 int frequency = mlt_properties_get_int( properties, "frequency" );
926 // AVFormat audio buffer and frame size
927 int audio_outbuf_size = ( 1024 * 42 );
928 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
929 int audio_input_frame_size = 0;
931 // AVFormat video buffer and frame count
933 int video_outbuf_size = ( 1024 * 1024 );
934 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
936 // Used for the frame properties
937 mlt_frame frame = NULL;
938 mlt_properties frame_properties = NULL;
941 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
942 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
944 // Need two av pictures for converting
945 AVFrame *output = NULL;
946 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
948 // For receiving images from an mlt_frame
950 mlt_image_format img_fmt = mlt_image_yuv422;
952 // For receiving audio samples back from the fifo
953 int16_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
954 int16_t *audio_buf_2 = NULL;
957 // Allocate the context
958 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
959 AVFormatContext *oc = avformat_alloc_context( );
961 AVFormatContext *oc = av_alloc_format_context( );
965 AVStream *video_st = NULL;
966 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
969 double audio_pts = 0;
970 double video_pts = 0;
974 long int total_time = 0;
976 // Determine the format
977 AVOutputFormat *fmt = NULL;
978 const char *filename = mlt_properties_get( properties, "target" );
979 char *format = mlt_properties_get( properties, "f" );
980 char *vcodec = mlt_properties_get( properties, "vcodec" );
981 char *acodec = mlt_properties_get( properties, "acodec" );
983 // Used to store and override codec ids
989 mlt_properties frame_meta_properties = mlt_properties_new();
991 // Initialize audio_st
992 int i = MAX_AUDIO_STREAMS;
996 // Check for user selected format first
997 if ( format != NULL )
998 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
999 fmt = guess_format( format, NULL, NULL );
1001 fmt = av_guess_format( format, NULL, NULL );
1004 // Otherwise check on the filename
1005 if ( fmt == NULL && filename != NULL )
1006 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1007 fmt = guess_format( NULL, filename, NULL );
1009 fmt = av_guess_format( NULL, filename, NULL );
1012 // Otherwise default to mpeg
1014 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1015 fmt = guess_format( "mpeg", NULL, NULL );
1017 fmt = av_guess_format( "mpeg", NULL, NULL );
1020 // We need a filename - default to stdout?
1021 if ( filename == NULL || !strcmp( filename, "" ) )
1024 // Get the codec ids selected
1025 audio_codec_id = fmt->audio_codec;
1026 video_codec_id = fmt->video_codec;
1028 // Check for audio codec overides
1029 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1030 audio_codec_id = CODEC_ID_NONE;
1033 AVCodec *p = avcodec_find_encoder_by_name( acodec );
1035 audio_codec_id = p->id;
1037 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "audio codec %s unrecognised - ignoring\n", acodec );
1040 // Check for video codec overides
1041 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1042 video_codec_id = CODEC_ID_NONE;
1045 AVCodec *p = avcodec_find_encoder_by_name( vcodec );
1047 video_codec_id = p->id;
1049 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "video codec %s unrecognised - ignoring\n", vcodec );
1056 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1057 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1059 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1060 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1062 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1063 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1065 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1066 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1068 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1069 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1071 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1072 if (metavalue != 0) oc->year = metavalue;
1074 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1075 if (metavalue != 0) oc->track = metavalue;
1078 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1080 // Add audio and video streams
1081 if ( video_codec_id != CODEC_ID_NONE )
1082 video_st = add_video_stream( this, oc, video_codec_id );
1083 if ( audio_codec_id != CODEC_ID_NONE )
1089 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1091 sprintf( key, "channels.%d", i );
1092 int j = mlt_properties_get_int( properties, key );
1096 total_channels += j;
1097 audio_st[i] = add_audio_stream( this, oc, audio_codec_id, j );
1103 audio_st[0] = add_audio_stream( this, oc, audio_codec_id, channels );
1104 total_channels = channels;
1108 // Set the parameters (even though we have none...)
1109 if ( av_set_parameters(oc, NULL) >= 0 )
1111 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1112 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1114 // Process properties as AVOptions
1115 char *fpre = mlt_properties_get( properties, "fpre" );
1118 mlt_properties p = mlt_properties_load( fpre );
1119 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM, 1 );
1120 mlt_properties_close( p );
1122 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM, 0 );
1124 if ( video_st && !open_video( oc, video_st ) )
1126 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1128 audio_input_frame_size = open_audio( oc, audio_st[i], audio_outbuf_size );
1129 if ( !audio_input_frame_size )
1133 // Open the output file, if needed
1134 if ( !( fmt->flags & AVFMT_NOFILE ) )
1136 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1138 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not open '%s'\n", filename );
1139 mlt_properties_set_int( properties, "running", 0 );
1143 // Write the stream header.
1144 if ( mlt_properties_get_int( properties, "running" ) )
1145 av_write_header( oc );
1149 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Invalid output format parameters\n" );
1150 mlt_properties_set_int( properties, "running", 0 );
1155 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1157 // Last check - need at least one stream
1158 if ( !audio_st[0] && !video_st )
1159 mlt_properties_set_int( properties, "running", 0 );
1161 // Get the starting time (can ignore the times above)
1162 gettimeofday( &ante, NULL );
1164 // Loop while running
1165 while( mlt_properties_get_int( properties, "running" ) &&
1166 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1168 frame = mlt_consumer_rt_frame( this );
1170 // Check that we have a frame to work with
1171 if ( frame != NULL )
1173 // Increment frames dispatched
1176 // Default audio args
1177 frame_properties = MLT_FRAME_PROPERTIES( frame );
1179 // Check for the terminated condition
1180 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1182 // Get audio and append to the fifo
1183 if ( !terminated && audio_st[0] )
1185 samples = mlt_sample_calculator( fps, frequency, count ++ );
1186 mlt_frame_get_audio( frame, (void**) &pcm, &aud_fmt, &frequency, &channels, &samples );
1188 // Save the audio channel remap properties for later
1189 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1191 // Create the fifo if we don't have one
1194 fifo = sample_fifo_init( frequency, channels );
1195 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1198 // Silence if not normal forward speed
1199 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1200 memset( pcm, 0, samples * channels * 2 );
1202 // Append the samples
1203 sample_fifo_append( fifo, pcm, samples * channels );
1204 total_time += ( samples * 1000000 ) / frequency;
1208 if ( !terminated && video_st )
1209 mlt_deque_push_back( queue, frame );
1211 mlt_frame_close( frame );
1214 // While we have stuff to process, process...
1217 // Write interleaved audio and video frames
1218 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1221 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1223 int j = 0; // channel offset into interleaved source buffer
1224 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) ), AUDIO_ENCODE_BUFFER_SIZE );
1226 // Get the audio samples
1229 sample_fifo_fetch( fifo, audio_buf_1, n );
1231 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1233 // This prevents an infinite loop when some versions of vorbis do not
1234 // increment pts when encoding silence.
1235 audio_pts = video_pts;
1240 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1242 samples = n / channels;
1244 // For each output stream
1245 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1247 AVStream *stream = audio_st[i];
1248 AVCodecContext *codec = stream->codec;
1251 av_init_packet( &pkt );
1253 // Optimized for single track and no channel remap
1254 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1256 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1260 // Extract the audio channels according to channel mapping
1261 int dest_offset = 0; // channel offset into interleaved dest buffer
1263 // Get the number of channels for this stream
1264 sprintf( key, "channels.%d", i );
1265 int current_channels = mlt_properties_get_int( properties, key );
1267 // Clear the destination audio buffer.
1269 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1271 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1273 // For each output channel
1274 while ( dest_offset < current_channels && j < total_channels )
1276 int map_start = -1, map_channels = 0;
1277 int source_offset = 0;
1280 // Look for a mapping that starts at j
1281 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1283 sprintf( key, "%d.channels", k );
1284 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1285 sprintf( key, "%d.start", k );
1286 if ( mlt_properties_get( frame_meta_properties, key ) )
1287 map_start = mlt_properties_get_int( frame_meta_properties, key );
1288 if ( map_start != j )
1289 source_offset += map_channels;
1293 if ( map_start != j )
1295 map_channels = current_channels;
1299 // Copy samples if source offset valid
1300 if ( source_offset < channels )
1302 // Interleave the audio buffer with the # channels for this stream/mapping.
1303 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1305 int16_t *src = audio_buf_1 + source_offset;
1306 int16_t *dest = audio_buf_2 + dest_offset;
1307 int s = samples + 1;
1311 dest += current_channels;
1316 // Otherwise silence
1319 j += current_channels;
1320 dest_offset += current_channels;
1323 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_2 );
1326 // Write the compressed frame in the media file
1327 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1329 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1330 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "audio stream %d pkt pts %lld frame pts %lld",
1331 stream->index, pkt.pts, codec->coded_frame->pts );
1333 pkt.flags |= PKT_FLAG_KEY;
1334 pkt.stream_index = stream->index;
1335 pkt.data = audio_outbuf;
1339 if ( av_interleaved_write_frame( oc, &pkt ) )
1341 mlt_log_fatal( MLT_CONSUMER_SERVICE( this ), "error writing audio frame\n" );
1342 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1343 goto on_fatal_error;
1347 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), " frame_size %d\n", codec->frame_size );
1350 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1359 else if ( video_st )
1362 if ( mlt_deque_count( queue ) )
1364 int out_size, ret = 0;
1367 frame = mlt_deque_pop_front( queue );
1368 frame_properties = MLT_FRAME_PROPERTIES( frame );
1370 c = video_st->codec;
1372 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1379 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1383 // Convert the mlt frame to an AVPicture
1384 for ( i = 0; i < height; i ++ )
1386 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1395 // Do the colour space conversion
1397 int flags = SWS_BILINEAR;
1399 flags |= SWS_CPU_CAPS_MMX;
1402 flags |= SWS_CPU_CAPS_MMX2;
1404 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1405 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1406 sws_scale( context, input->data, input->linesize, 0, height,
1407 output->data, output->linesize);
1408 sws_freeContext( context );
1410 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1413 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1415 // Apply the alpha if applicable
1416 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1418 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1421 for ( i = 0; i < height; i ++ )
1423 n = ( width + 7 ) / 8;
1424 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1428 case 0: do { *p = *alpha++; p += 4;
1429 case 7: *p = *alpha++; p += 4;
1430 case 6: *p = *alpha++; p += 4;
1431 case 5: *p = *alpha++; p += 4;
1432 case 4: *p = *alpha++; p += 4;
1433 case 3: *p = *alpha++; p += 4;
1434 case 2: *p = *alpha++; p += 4;
1435 case 1: *p = *alpha++; p += 4;
1443 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1445 // raw video case. The API will change slightly in the near future for that
1447 av_init_packet(&pkt);
1449 pkt.flags |= PKT_FLAG_KEY;
1450 pkt.stream_index= video_st->index;
1451 pkt.data= (uint8_t *)output;
1452 pkt.size= sizeof(AVPicture);
1454 ret = av_write_frame(oc, &pkt);
1455 video_pts += c->frame_size;
1460 output->quality = video_st->quality;
1462 // Set frame interlace hints
1463 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1464 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1465 output->pts = frame_count;
1468 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1470 // If zero size, it means the image was buffered
1474 av_init_packet( &pkt );
1476 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1477 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1478 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "video pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1479 if( c->coded_frame && c->coded_frame->key_frame )
1480 pkt.flags |= PKT_FLAG_KEY;
1481 pkt.stream_index= video_st->index;
1482 pkt.data= video_outbuf;
1485 // write the compressed frame in the media file
1486 ret = av_interleaved_write_frame(oc, &pkt);
1487 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), " frame_size %d\n", c->frame_size );
1488 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1490 // Dual pass logging
1491 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1492 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1494 else if ( out_size < 0 )
1496 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "error with video encode %d\n", frame_count );
1502 mlt_log_fatal( MLT_CONSUMER_SERVICE( this ), "error writing video frame\n" );
1503 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1504 goto on_fatal_error;
1506 mlt_frame_close( frame );
1514 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "audio pts %lld (%f) ", audio_st[0]->pts.val, audio_pts );
1516 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "video pts %lld (%f) ", video_st->pts.val, video_pts );
1517 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "\n" );
1520 if ( real_time_output == 1 && frames % 2 == 0 )
1522 long passed = time_difference( &ante );
1525 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1528 if ( passed < total_time )
1530 long total = ( total_time - passed );
1531 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1532 nanosleep( &t, NULL );
1537 // Flush the encoder buffers
1538 if ( real_time_output <= 0 )
1541 // TODO: flush all audio streams
1542 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1544 AVCodecContext *c = audio_st[0]->codec;
1546 av_init_packet( &pkt );
1549 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1550 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1552 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size );
1553 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1555 if ( pkt.size <= 0 )
1556 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1557 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "flushing audio size %d\n", pkt.size );
1558 if ( pkt.size <= 0 )
1561 // Write the compressed frame in the media file
1562 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1563 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1564 pkt.flags |= PKT_FLAG_KEY;
1565 pkt.stream_index = audio_st[0]->index;
1566 pkt.data = audio_outbuf;
1567 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1569 mlt_log_fatal( MLT_CONSUMER_SERVICE( this ), "error writing flushed audio frame\n" );
1570 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1571 goto on_fatal_error;
1576 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1578 AVCodecContext *c = video_st->codec;
1580 av_init_packet( &pkt );
1583 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1584 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "flushing video size %d\n", pkt.size );
1585 if ( pkt.size <= 0 )
1588 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1589 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1590 if( c->coded_frame && c->coded_frame->key_frame )
1591 pkt.flags |= PKT_FLAG_KEY;
1592 pkt.stream_index = video_st->index;
1593 pkt.data = video_outbuf;
1595 // write the compressed frame in the media file
1596 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1598 mlt_log_fatal( MLT_CONSUMER_SERVICE(this), "error writing flushed video frame\n" );
1599 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1600 goto on_fatal_error;
1602 // Dual pass logging
1603 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1604 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1610 // Write the trailer, if any
1611 av_write_trailer( oc );
1615 close_video(oc, video_st);
1616 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1617 close_audio( oc, audio_st[i] );
1620 for ( i = 0; i < oc->nb_streams; i++ )
1621 av_freep( &oc->streams[i] );
1623 // Close the output file
1624 if ( !( fmt->flags & AVFMT_NOFILE ) )
1625 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1626 url_fclose( oc->pb );
1628 url_fclose( &oc->pb );
1631 // Clean up input and output frames
1633 av_free( output->data[0] );
1635 av_free( input->data[0] );
1637 av_free( video_outbuf );
1638 av_free( audio_buf_1 );
1639 av_free( audio_buf_2 );
1644 // Just in case we terminated on pause
1645 mlt_properties_set_int( properties, "running", 0 );
1647 mlt_consumer_stopped( this );
1648 mlt_properties_close( frame_meta_properties );
1650 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1652 // Remove the dual pass log file
1653 if ( mlt_properties_get( properties, "_logfilename" ) )
1654 remove( mlt_properties_get( properties, "_logfilename" ) );
1656 // Remove the x264 dual pass logs
1657 char *cwd = getcwd( NULL, 0 );
1658 const char *file = "x264_2pass.log";
1659 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1660 sprintf( full, "%s/%s", cwd, file );
1663 file = "x264_2pass.log.temp";
1664 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1665 sprintf( full, "%s/%s", cwd, file );
1668 file = "x264_2pass.log.mbtree";
1669 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1670 sprintf( full, "%s/%s", cwd, file );
1674 remove( "x264_2pass.log.temp" );
1680 /** Close the consumer.
1683 static void consumer_close( mlt_consumer this )
1685 // Stop the consumer
1686 mlt_consumer_stop( this );
1689 mlt_consumer_close( this );