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>
28 // System header files
37 // avformat header files
44 #if LIBAVUTIL_VERSION_INT < (50<<16)
45 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
46 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
49 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2)
52 // This structure should be extended and made globally available in mlt
64 *sample_fifo, sample_fifo_s;
66 sample_fifo sample_fifo_init( int frequency, int channels )
68 sample_fifo this = calloc( 1, sizeof( sample_fifo_s ) );
69 this->frequency = frequency;
70 this->channels = channels;
74 // sample_fifo_clear and check are temporarily aborted (not working as intended)
76 void sample_fifo_clear( sample_fifo this, double time )
78 int words = ( float )( time - this->time ) * this->frequency * this->channels;
79 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) && this->used > words && words > 0 )
81 memmove( this->buffer, &this->buffer[ words ], ( this->used - words ) * sizeof( int16_t ) );
85 else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )this->time * 100 ) )
92 void sample_fifo_check( sample_fifo this, double time )
94 if ( this->used == 0 )
96 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) )
101 void sample_fifo_append( sample_fifo this, int16_t *samples, int count )
103 if ( ( this->size - this->used ) < count )
105 this->size += count * 5;
106 this->buffer = realloc( this->buffer, this->size * sizeof( int16_t ) );
109 memcpy( &this->buffer[ this->used ], samples, count * sizeof( int16_t ) );
113 int sample_fifo_used( sample_fifo this )
118 int sample_fifo_fetch( sample_fifo this, int16_t *samples, int count )
120 if ( count > this->used )
123 memcpy( samples, this->buffer, count * sizeof( int16_t ) );
125 memmove( this->buffer, &this->buffer[ count ], this->used * sizeof( int16_t ) );
127 this->time += ( double )count / this->channels / this->frequency;
132 void sample_fifo_close( sample_fifo this )
134 free( this->buffer );
138 // Forward references.
139 static int consumer_start( mlt_consumer this );
140 static int consumer_stop( mlt_consumer this );
141 static int consumer_is_stopped( mlt_consumer this );
142 static void *consumer_thread( void *arg );
143 static void consumer_close( mlt_consumer this );
145 /** Initialise the dv consumer.
148 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
150 // Allocate the consumer
151 mlt_consumer this = mlt_consumer_new( profile );
153 // If memory allocated and initialises without error
156 // Get properties from the consumer
157 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
159 // Assign close callback
160 this->close = consumer_close;
162 // Interpret the argument
164 mlt_properties_set( properties, "target", arg );
166 // sample and frame queue
167 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
169 // Audio options not fully handled by AVOptions
170 #define QSCALE_NONE (-99999)
171 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
173 // Video options not fully handled by AVOptions
174 mlt_properties_set_int( properties, "dc", 8 );
176 // Muxer options not fully handled by AVOptions
177 mlt_properties_set_double( properties, "muxdelay", 0.7 );
178 mlt_properties_set_double( properties, "muxpreload", 0.5 );
180 // Ensure termination at end of the stream
181 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
183 // Default to separate processing threads for producer and consumer with no frame dropping!
184 mlt_properties_set_int( properties, "real_time", -1 );
185 mlt_properties_set_int( properties, "prefill", 1 );
187 // Set up start/stop/terminated callbacks
188 this->start = consumer_start;
189 this->stop = consumer_stop;
190 this->is_stopped = consumer_is_stopped;
197 /** Start the consumer.
200 static int consumer_start( mlt_consumer this )
202 // Get the properties
203 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
206 // Report information about available muxers and codecs as YAML Tiny
207 char *s = mlt_properties_get( properties, "f" );
208 if ( s && strcmp( s, "list" ) == 0 )
210 fprintf( stderr, "---\nformats:\n" );
211 AVOutputFormat *format = NULL;
212 while ( ( format = av_oformat_next( format ) ) )
213 fprintf( stderr, " - %s\n", format->name );
214 fprintf( stderr, "...\n" );
217 s = mlt_properties_get( properties, "acodec" );
218 if ( s && strcmp( s, "list" ) == 0 )
220 fprintf( stderr, "---\naudio_codecs:\n" );
221 AVCodec *codec = NULL;
222 while ( ( codec = av_codec_next( codec ) ) )
223 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
224 fprintf( stderr, " - %s\n", codec->name );
225 fprintf( stderr, "...\n" );
228 s = mlt_properties_get( properties, "vcodec" );
229 if ( s && strcmp( s, "list" ) == 0 )
231 fprintf( stderr, "---\nvideo_codecs:\n" );
232 AVCodec *codec = NULL;
233 while ( ( codec = av_codec_next( codec ) ) )
234 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
235 fprintf( stderr, " - %s\n", codec->name );
236 fprintf( stderr, "...\n" );
240 // Check that we're not already running
241 if ( !error && !mlt_properties_get_int( properties, "running" ) )
244 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
246 // Get the width and height
247 int width = mlt_properties_get_int( properties, "width" );
248 int height = mlt_properties_get_int( properties, "height" );
250 // Obtain the size property
251 char *size = mlt_properties_get( properties, "s" );
257 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
264 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "Invalid size property %s - ignoring.\n", size );
268 // Now ensure we honour the multiple of two requested by libavformat
269 width = ( width / 2 ) * 2;
270 height = ( height / 2 ) * 2;
271 mlt_properties_set_int( properties, "width", width );
272 mlt_properties_set_int( properties, "height", height );
274 // We need to set these on the profile as well because the s property is
275 // an alias to mlt properties that correspond to profile settings.
276 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
279 profile->width = width;
280 profile->height = height;
283 // Handle the ffmpeg command line "-r" property for frame rate
284 if ( mlt_properties_get( properties, "r" ) )
286 double frame_rate = mlt_properties_get_double( properties, "r" );
287 AVRational rational = av_d2q( frame_rate, 255 );
288 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
289 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
292 profile->frame_rate_num = rational.num;
293 profile->frame_rate_den = rational.den;
294 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
298 // Apply AVOptions that are synonyms for standard mlt_consumer options
299 if ( mlt_properties_get( properties, "ac" ) )
300 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
301 if ( mlt_properties_get( properties, "ar" ) )
302 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
304 // Assign the thread to properties
305 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
307 // Set the running state
308 mlt_properties_set_int( properties, "running", 1 );
311 pthread_create( thread, NULL, consumer_thread, this );
316 /** Stop the consumer.
319 static int consumer_stop( mlt_consumer this )
321 // Get the properties
322 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
324 // Check that we're running
325 if ( mlt_properties_get_int( properties, "running" ) )
328 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
331 mlt_properties_set_int( properties, "running", 0 );
333 // Wait for termination
334 pthread_join( *thread, NULL );
340 /** Determine if the consumer is stopped.
343 static int consumer_is_stopped( mlt_consumer this )
345 // Get the properties
346 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
347 return !mlt_properties_get_int( properties, "running" );
350 /** Process properties as AVOptions and apply to AV context obj
353 static void apply_properties( void *obj, mlt_properties properties, int flags )
356 int count = mlt_properties_count( properties );
357 for ( i = 0; i < count; i++ )
359 const char *opt_name = mlt_properties_get_name( properties, i );
360 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
362 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
363 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
364 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
365 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
367 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
372 /** Add an audio output stream
375 static AVStream *add_audio_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
377 // Get the properties
378 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
380 // Create a new stream
381 AVStream *st = av_new_stream( oc, 1 );
383 // If created, then initialise from properties
386 AVCodecContext *c = st->codec;
388 // Establish defaults from AVOptions
389 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
391 c->codec_id = codec_id;
392 c->codec_type = CODEC_TYPE_AUDIO;
393 c->sample_fmt = SAMPLE_FMT_S16;
395 #if 0 // disabled until some audio codecs are multi-threaded
396 // Setup multi-threading
397 int thread_count = mlt_properties_get_int( properties, "threads" );
398 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
399 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
400 if ( thread_count > 1 )
401 avcodec_thread_init( c, thread_count );
404 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
405 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
407 // Allow the user to override the audio fourcc
408 if ( mlt_properties_get( properties, "atag" ) )
411 char *arg = mlt_properties_get( properties, "atag" );
412 int tag = strtol( arg, &tail, 0);
414 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
418 // Process properties as AVOptions
419 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
421 int audio_qscale = mlt_properties_get_int( properties, "aq" );
422 if ( audio_qscale > QSCALE_NONE )
424 c->flags |= CODEC_FLAG_QSCALE;
425 c->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
428 // Set parameters controlled by MLT
429 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
430 c->time_base = ( AVRational ){ 1, c->sample_rate };
431 c->channels = mlt_properties_get_int( properties, "channels" );
433 if ( mlt_properties_get( properties, "alang" ) != NULL )
434 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
438 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not allocate a stream for audio\n" );
444 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
446 // We will return the audio input size from here
447 int audio_input_frame_size = 0;
450 AVCodecContext *c = st->codec;
453 AVCodec *codec = avcodec_find_encoder( c->codec_id );
455 // Continue if codec found and we can open it
456 if ( codec != NULL && avcodec_open( c, codec ) >= 0 )
458 // ugly hack for PCM codecs (will be removed ASAP with new PCM
459 // support to compute the input frame size in samples
460 if ( c->frame_size <= 1 )
462 audio_input_frame_size = audio_outbuf_size / c->channels;
463 switch(st->codec->codec_id)
465 case CODEC_ID_PCM_S16LE:
466 case CODEC_ID_PCM_S16BE:
467 case CODEC_ID_PCM_U16LE:
468 case CODEC_ID_PCM_U16BE:
469 audio_input_frame_size >>= 1;
477 audio_input_frame_size = c->frame_size;
480 // Some formats want stream headers to be seperate (hmm)
481 if ( !strcmp( oc->oformat->name, "mp4" ) ||
482 !strcmp( oc->oformat->name, "mov" ) ||
483 !strcmp( oc->oformat->name, "3gp" ) )
484 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
488 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
491 return audio_input_frame_size;
494 static void close_audio( AVFormatContext *oc, AVStream *st )
496 if ( st && st->codec )
497 avcodec_close( st->codec );
500 /** Add a video output stream
503 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
505 // Get the properties
506 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
508 // Create a new stream
509 AVStream *st = av_new_stream( oc, 0 );
513 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
514 AVCodecContext *c = st->codec;
516 // Establish defaults from AVOptions
517 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
519 c->codec_id = codec_id;
520 c->codec_type = CODEC_TYPE_VIDEO;
522 // Setup multi-threading
523 int thread_count = mlt_properties_get_int( properties, "threads" );
524 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
525 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
526 if ( thread_count > 1 )
527 avcodec_thread_init( c, thread_count );
529 // Process properties as AVOptions
530 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
532 // Set options controlled by MLT
533 c->width = mlt_properties_get_int( properties, "width" );
534 c->height = mlt_properties_get_int( properties, "height" );
535 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
536 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
537 if ( st->time_base.den == 0 )
538 st->time_base = c->time_base;
539 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
541 if ( mlt_properties_get( properties, "aspect" ) )
543 // "-aspect" on ffmpeg command line is display aspect ratio
544 double ar = mlt_properties_get_double( properties, "aspect" );
545 AVRational rational = av_d2q( ar, 255 );
547 // Update the profile and properties as well since this is an alias
548 // for mlt properties that correspond to profile settings
549 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
550 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
551 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
554 profile->display_aspect_num = rational.num;
555 profile->display_aspect_den = rational.den;
556 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
559 // Now compute the sample aspect ratio
560 rational = av_d2q( ar * c->height / c->width, 255 );
561 c->sample_aspect_ratio = rational;
562 // Update the profile and properties as well since this is an alias
563 // for mlt properties that correspond to profile settings
564 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
565 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
568 profile->sample_aspect_num = rational.num;
569 profile->sample_aspect_den = rational.den;
570 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
575 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
576 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
578 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
579 st->sample_aspect_ratio = c->sample_aspect_ratio;
582 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
584 c->flags |= CODEC_FLAG_QSCALE;
585 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
588 // Allow the user to override the video fourcc
589 if ( mlt_properties_get( properties, "vtag" ) )
592 const char *arg = mlt_properties_get( properties, "vtag" );
593 int tag = strtol( arg, &tail, 0);
595 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
599 // Some formats want stream headers to be seperate
600 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
601 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
603 // Translate these standard mlt consumer properties to ffmpeg
604 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
605 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
607 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
608 c->flags |= CODEC_FLAG_INTERLACED_DCT;
609 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
610 c->flags |= CODEC_FLAG_INTERLACED_ME;
613 // parse the ratecontrol override string
615 char *rc_override = mlt_properties_get( properties, "rc_override" );
616 for ( i = 0; rc_override; i++ )
619 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
621 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "Error parsing rc_override\n" );
622 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
623 c->rc_override[i].start_frame = start;
624 c->rc_override[i].end_frame = end;
627 c->rc_override[i].qscale = q;
628 c->rc_override[i].quality_factor = 1.0;
632 c->rc_override[i].qscale = 0;
633 c->rc_override[i].quality_factor = -q / 100.0;
635 rc_override = strchr( rc_override, '/' );
639 c->rc_override_count = i;
640 if ( !c->rc_initial_buffer_occupancy )
641 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
642 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
645 i = mlt_properties_get_int( properties, "pass" );
647 c->flags |= CODEC_FLAG_PASS1;
649 c->flags |= CODEC_FLAG_PASS2;
650 if ( codec_id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
652 char logfilename[1024];
657 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
658 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
659 if ( c->flags & CODEC_FLAG_PASS1 )
661 f = fopen( logfilename, "w" );
663 perror( logfilename );
665 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
669 /* read the log file */
670 f = fopen( logfilename, "r" );
677 mlt_properties_set( properties, "_logfilename", logfilename );
678 fseek( f, 0, SEEK_END );
680 fseek( f, 0, SEEK_SET );
681 logbuffer = av_malloc( size + 1 );
683 mlt_log_fatal( MLT_CONSUMER_SERVICE( this ), "Could not allocate log buffer\n" );
686 size = fread( logbuffer, 1, size, f );
688 logbuffer[size] = '\0';
689 c->stats_in = logbuffer;
690 mlt_properties_set_data( properties, "_logbuffer", logbuffer, 0, ( mlt_destructor )av_free, NULL );
698 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not allocate a stream for video\n" );
704 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
707 AVFrame *picture = avcodec_alloc_frame();
709 // Determine size of the
710 int size = avpicture_get_size(pix_fmt, width, height);
712 // Allocate the picture buf
713 uint8_t *picture_buf = av_malloc(size);
715 // If we have both, then fill the image
716 if ( picture != NULL && picture_buf != NULL )
718 // Fill the frame with the allocated buffer
719 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
723 // Something failed - clean up what we can
725 av_free( picture_buf );
732 static int open_video(AVFormatContext *oc, AVStream *st)
735 AVCodecContext *video_enc = st->codec;
737 // find the video encoder
738 AVCodec *codec = avcodec_find_encoder( video_enc->codec_id );
740 if( codec && codec->pix_fmts )
742 const enum PixelFormat *p = codec->pix_fmts;
745 if( *p == video_enc->pix_fmt )
749 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
752 // Open the codec safely
753 return codec != NULL && avcodec_open( video_enc, codec ) >= 0;
756 void close_video(AVFormatContext *oc, AVStream *st)
758 if ( st && st->codec )
759 avcodec_close(st->codec);
762 static inline long time_difference( struct timeval *time1 )
764 struct timeval time2;
765 gettimeofday( &time2, NULL );
766 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
769 /** The main thread - the argument is simply the consumer.
772 static void *consumer_thread( void *arg )
774 // Map the argument to the object
775 mlt_consumer this = arg;
777 // Get the properties
778 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
780 // Get the terminate on pause property
781 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
784 // Determine if feed is slow (for realtime stuff)
785 int real_time_output = mlt_properties_get_int( properties, "real_time" );
790 // Get the frame rate
791 double fps = mlt_properties_get_double( properties, "fps" );
793 // Get width and height
794 int width = mlt_properties_get_int( properties, "width" );
795 int height = mlt_properties_get_int( properties, "height" );
796 int img_width = width;
797 int img_height = height;
799 // Get default audio properties
800 mlt_audio_format aud_fmt = mlt_audio_s16;
801 int channels = mlt_properties_get_int( properties, "channels" );
802 int frequency = mlt_properties_get_int( properties, "frequency" );
806 // AVFormat audio buffer and frame size
807 int audio_outbuf_size = ( 1024 * 42 );
808 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
809 int audio_input_frame_size = 0;
811 // AVFormat video buffer and frame count
813 int video_outbuf_size = ( 1024 * 1024 );
814 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
816 // Used for the frame properties
817 mlt_frame frame = NULL;
818 mlt_properties frame_properties = NULL;
821 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
822 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
824 // Need two av pictures for converting
825 AVFrame *output = NULL;
826 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
828 // For receiving images from an mlt_frame
830 mlt_image_format img_fmt = mlt_image_yuv422;
832 // For receiving audio samples back from the fifo
833 int16_t *buffer = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
836 // Allocate the context
837 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
838 AVFormatContext *oc = avformat_alloc_context( );
840 AVFormatContext *oc = av_alloc_format_context( );
844 AVStream *audio_st = NULL;
845 AVStream *video_st = NULL;
848 double audio_pts = 0;
849 double video_pts = 0;
856 long int total_time = 0;
858 // Determine the format
859 AVOutputFormat *fmt = NULL;
860 const char *filename = mlt_properties_get( properties, "target" );
861 char *format = mlt_properties_get( properties, "f" );
862 char *vcodec = mlt_properties_get( properties, "vcodec" );
863 char *acodec = mlt_properties_get( properties, "acodec" );
865 // Used to store and override codec ids
869 // Check for user selected format first
870 if ( format != NULL )
871 fmt = guess_format( format, NULL, NULL );
873 // Otherwise check on the filename
874 if ( fmt == NULL && filename != NULL )
875 fmt = guess_format( NULL, filename, NULL );
877 // Otherwise default to mpeg
879 fmt = guess_format( "mpeg", NULL, NULL );
881 // We need a filename - default to stdout?
882 if ( filename == NULL || !strcmp( filename, "" ) )
885 // Get the codec ids selected
886 audio_codec_id = fmt->audio_codec;
887 video_codec_id = fmt->video_codec;
889 // Check for audio codec overides
890 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
891 audio_codec_id = CODEC_ID_NONE;
894 AVCodec *p = avcodec_find_encoder_by_name( acodec );
896 audio_codec_id = p->id;
898 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "audio codec %s unrecognised - ignoring\n", acodec );
901 // Check for video codec overides
902 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
903 video_codec_id = CODEC_ID_NONE;
906 AVCodec *p = avcodec_find_encoder_by_name( vcodec );
908 video_codec_id = p->id;
910 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "video codec %s unrecognised - ignoring\n", vcodec );
917 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
918 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
920 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
921 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
923 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
924 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
926 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
927 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
929 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
930 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
932 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
933 if (metavalue != 0) oc->year = metavalue;
935 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
936 if (metavalue != 0) oc->track = metavalue;
939 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
941 // Add audio and video streams
942 if ( video_codec_id != CODEC_ID_NONE )
943 video_st = add_video_stream( this, oc, video_codec_id );
944 if ( audio_codec_id != CODEC_ID_NONE )
945 audio_st = add_audio_stream( this, oc, audio_codec_id );
947 // Set the parameters (even though we have none...)
948 if ( av_set_parameters(oc, NULL) >= 0 )
950 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
951 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
953 // Process properties as AVOptions
954 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
956 if ( video_st && !open_video( oc, video_st ) )
960 audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
961 if ( !audio_input_frame_size )
965 // Open the output file, if needed
966 if ( !( fmt->flags & AVFMT_NOFILE ) )
968 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
970 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not open '%s'\n", filename );
971 mlt_properties_set_int( properties, "running", 0 );
975 // Write the stream header, if any
976 if ( mlt_properties_get_int( properties, "running" ) )
977 av_write_header( oc );
981 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Invalid output format parameters\n" );
982 mlt_properties_set_int( properties, "running", 0 );
987 output = alloc_picture( video_st->codec->pix_fmt, width, height );
989 // Last check - need at least one stream
990 if ( audio_st == NULL && video_st == NULL )
991 mlt_properties_set_int( properties, "running", 0 );
993 // Get the starting time (can ignore the times above)
994 gettimeofday( &ante, NULL );
996 // Loop while running
997 while( mlt_properties_get_int( properties, "running" ) &&
998 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1001 frame = mlt_consumer_rt_frame( this );
1003 // Check that we have a frame to work with
1004 if ( frame != NULL )
1006 // Increment frames despatched
1009 // Default audio args
1010 frame_properties = MLT_FRAME_PROPERTIES( frame );
1012 // Check for the terminated condition
1013 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1015 // Get audio and append to the fifo
1016 if ( !terminated && audio_st )
1018 samples = mlt_sample_calculator( fps, frequency, count ++ );
1019 mlt_frame_get_audio( frame, (void**) &pcm, &aud_fmt, &frequency, &channels, &samples );
1021 // Create the fifo if we don't have one
1024 fifo = sample_fifo_init( frequency, channels );
1025 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1028 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1029 memset( pcm, 0, samples * channels * 2 );
1031 // Append the samples
1032 sample_fifo_append( fifo, pcm, samples * channels );
1033 total_time += ( samples * 1000000 ) / frequency;
1037 if ( !terminated && video_st )
1038 mlt_deque_push_back( queue, frame );
1040 mlt_frame_close( frame );
1043 // While we have stuff to process, process...
1046 // Write interleaved audio and video frames
1047 if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
1049 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1051 AVCodecContext *c = audio_st->codec;
1053 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) ), AUDIO_ENCODE_BUFFER_SIZE );
1056 sample_fifo_fetch( fifo, buffer, n );
1058 memset( buffer, 0, AUDIO_ENCODE_BUFFER_SIZE );
1060 av_init_packet( &pkt );
1061 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
1063 // Write the compressed frame in the media file
1064 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1066 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
1067 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "audio pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1069 pkt.flags |= PKT_FLAG_KEY;
1070 pkt.stream_index= audio_st->index;
1071 pkt.data= audio_outbuf;
1074 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1075 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "error writing audio frame\n" );
1077 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), " frame_size %d\n", c->frame_size );
1078 if ( audio_codec_id == CODEC_ID_VORBIS )
1079 audio_pts = (double)c->coded_frame->pts * av_q2d( audio_st->time_base );
1081 audio_pts = (double)audio_st->pts.val * av_q2d( audio_st->time_base );
1088 else if ( video_st )
1090 if ( mlt_deque_count( queue ) )
1095 frame = mlt_deque_pop_front( queue );
1096 frame_properties = MLT_FRAME_PROPERTIES( frame );
1098 c = video_st->codec;
1100 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1107 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1109 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1113 // Convert the mlt frame to an AVPicture
1114 for ( i = 0; i < height; i ++ )
1116 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1125 // Do the colour space conversion
1127 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1128 width, height, video_st->codec->pix_fmt, SWS_FAST_BILINEAR, NULL, NULL, NULL);
1129 sws_scale( context, input->data, input->linesize, 0, height,
1130 output->data, output->linesize);
1131 sws_freeContext( context );
1133 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1136 // Apply the alpha if applicable
1137 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1139 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1142 for ( i = 0; i < height; i ++ )
1144 n = ( width + 7 ) / 8;
1145 p = output->data[ 0 ] + i * output->linesize[ 0 ];
1153 case 0: do { *p = *alpha++; p += 4;
1154 case 7: *p = *alpha++; p += 4;
1155 case 6: *p = *alpha++; p += 4;
1156 case 5: *p = *alpha++; p += 4;
1157 case 4: *p = *alpha++; p += 4;
1158 case 3: *p = *alpha++; p += 4;
1159 case 2: *p = *alpha++; p += 4;
1160 case 1: *p = *alpha++; p += 4;
1168 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1170 // raw video case. The API will change slightly in the near future for that
1172 av_init_packet(&pkt);
1174 pkt.flags |= PKT_FLAG_KEY;
1175 pkt.stream_index= video_st->index;
1176 pkt.data= (uint8_t *)output;
1177 pkt.size= sizeof(AVPicture);
1179 ret = av_write_frame(oc, &pkt);
1180 video_pts += c->frame_size;
1185 output->quality = video_st->quality;
1187 // Set frame interlace hints
1188 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1189 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1192 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1194 // If zero size, it means the image was buffered
1198 av_init_packet( &pkt );
1200 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1201 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1202 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "video pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1203 if( c->coded_frame && c->coded_frame->key_frame )
1204 pkt.flags |= PKT_FLAG_KEY;
1205 pkt.stream_index= video_st->index;
1206 pkt.data= video_outbuf;
1209 // write the compressed frame in the media file
1210 ret = av_interleaved_write_frame(oc, &pkt);
1211 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), " frame_size %d\n", c->frame_size );
1212 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1214 // Dual pass logging
1215 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1216 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1220 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "error with video encode\n" );
1224 mlt_frame_close( frame );
1232 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "audio pts %lld (%f) ", audio_st->pts.val, audio_pts );
1234 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "video pts %lld (%f) ", video_st->pts.val, video_pts );
1235 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "\n" );
1238 if ( real_time_output == 1 && frames % 12 == 0 )
1240 long passed = time_difference( &ante );
1243 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1246 if ( passed < total_time )
1248 long total = ( total_time - passed );
1249 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1250 nanosleep( &t, NULL );
1256 if ( ! real_time_output )
1259 if ( audio_st && audio_st->codec->frame_size > 1 ) for (;;)
1261 AVCodecContext *c = audio_st->codec;
1263 av_init_packet( &pkt );
1266 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1267 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1269 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
1270 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
1272 if ( pkt.size <= 0 )
1273 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1274 if ( pkt.size <= 0 )
1277 // Write the compressed frame in the media file
1278 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1279 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
1280 pkt.flags |= PKT_FLAG_KEY;
1281 pkt.stream_index = audio_st->index;
1282 pkt.data = audio_outbuf;
1283 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1285 fprintf( stderr, "%s: Error while writing flushed audio frame\n", __FILE__ );
1291 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1293 AVCodecContext *c = video_st->codec;
1295 av_init_packet( &pkt );
1298 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1299 if ( pkt.size <= 0 )
1302 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1303 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1304 if( c->coded_frame && c->coded_frame->key_frame )
1305 pkt.flags |= PKT_FLAG_KEY;
1306 pkt.stream_index = video_st->index;
1307 pkt.data = video_outbuf;
1309 // write the compressed frame in the media file
1310 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1312 mlt_log_error( MLT_CONSUMER_SERVICE(this), "error while writing flushing video frame\n" );
1319 // XXX ugly hack to prevent x264 from crashing on second pass of multi-threaded encoding
1320 int pass = mlt_properties_get_int( properties, "pass" );
1321 int thread_count = mlt_properties_get_int( properties, "threads" );
1322 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1323 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1324 int multithreaded_x264 = ( video_codec_id == CODEC_ID_H264 && pass == 2 && thread_count > 1 );
1327 if ( video_st && !multithreaded_x264 )
1328 close_video(oc, video_st);
1330 close_audio(oc, audio_st);
1332 // Write the trailer, if any
1333 av_write_trailer(oc);
1336 for(i = 0; i < oc->nb_streams; i++)
1337 av_freep(&oc->streams[i]);
1339 // Close the output file
1340 if (!(fmt->flags & AVFMT_NOFILE))
1341 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1344 url_fclose(&oc->pb);
1347 // Clean up input and output frames
1349 av_free( output->data[0] );
1351 av_free( input->data[0] );
1353 av_free( video_outbuf );
1359 // Just in case we terminated on pause
1360 mlt_properties_set_int( properties, "running", 0 );
1362 mlt_consumer_stopped( this );
1366 // Remove the dual pass log file
1367 if ( mlt_properties_get( properties, "_logfilename" ) )
1368 remove( mlt_properties_get( properties, "_logfilename" ) );
1370 // Remove the x264 dual pass logs
1371 char *cwd = getcwd( NULL, 0 );
1372 const char *file = "x264_2pass.log";
1373 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1374 sprintf( full, "%s/%s", cwd, file );
1377 file = "x264_2pass.log.temp";
1378 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1379 sprintf( full, "%s/%s", cwd, file );
1382 file = "x264_2pass.log.mbtree";
1383 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1384 sprintf( full, "%s/%s", cwd, file );
1388 remove( "x264_2pass.log.temp" );
1394 /** Close the consumer.
1397 static void consumer_close( mlt_consumer this )
1399 // Stop the consumer
1400 mlt_consumer_stop( this );
1403 mlt_consumer_close( this );