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
50 // This structure should be extended and made globally available in mlt
62 *sample_fifo, sample_fifo_s;
64 sample_fifo sample_fifo_init( int frequency, int channels )
66 sample_fifo this = calloc( 1, sizeof( sample_fifo_s ) );
67 this->frequency = frequency;
68 this->channels = channels;
72 // sample_fifo_clear and check are temporarily aborted (not working as intended)
74 void sample_fifo_clear( sample_fifo this, double time )
76 int words = ( float )( time - this->time ) * this->frequency * this->channels;
77 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) && this->used > words && words > 0 )
79 memmove( this->buffer, &this->buffer[ words ], ( this->used - words ) * sizeof( int16_t ) );
83 else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )this->time * 100 ) )
90 void sample_fifo_check( sample_fifo this, double time )
92 if ( this->used == 0 )
94 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) )
99 void sample_fifo_append( sample_fifo this, int16_t *samples, int count )
101 if ( ( this->size - this->used ) < count )
103 this->size += count * 5;
104 this->buffer = realloc( this->buffer, this->size * sizeof( int16_t ) );
107 memcpy( &this->buffer[ this->used ], samples, count * sizeof( int16_t ) );
111 int sample_fifo_used( sample_fifo this )
116 int sample_fifo_fetch( sample_fifo this, int16_t *samples, int count )
118 if ( count > this->used )
121 memcpy( samples, this->buffer, count * sizeof( int16_t ) );
123 memmove( this->buffer, &this->buffer[ count ], this->used * sizeof( int16_t ) );
125 this->time += ( double )count / this->channels / this->frequency;
130 void sample_fifo_close( sample_fifo this )
132 free( this->buffer );
136 // Forward references.
137 static int consumer_start( mlt_consumer this );
138 static int consumer_stop( mlt_consumer this );
139 static int consumer_is_stopped( mlt_consumer this );
140 static void *consumer_thread( void *arg );
141 static void consumer_close( mlt_consumer this );
143 /** Initialise the dv consumer.
146 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
148 // Allocate the consumer
149 mlt_consumer this = mlt_consumer_new( profile );
151 // If memory allocated and initialises without error
154 // Get properties from the consumer
155 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
157 // Assign close callback
158 this->close = consumer_close;
160 // Interpret the argument
162 mlt_properties_set( properties, "target", arg );
164 // sample and frame queue
165 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
167 // Audio options not fully handled by AVOptions
168 #define QSCALE_NONE (-99999)
169 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
171 // Video options not fully handled by AVOptions
172 mlt_properties_set_int( properties, "dc", 8 );
174 // Muxer options not fully handled by AVOptions
175 mlt_properties_set_double( properties, "muxdelay", 0.7 );
176 mlt_properties_set_double( properties, "muxpreload", 0.5 );
178 // Ensure termination at end of the stream
179 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
181 // Default to separate processing threads for producer and consumer with no frame dropping!
182 mlt_properties_set_int( properties, "real_time", -1 );
183 mlt_properties_set_int( properties, "prefill", 1 );
185 // Set up start/stop/terminated callbacks
186 this->start = consumer_start;
187 this->stop = consumer_stop;
188 this->is_stopped = consumer_is_stopped;
195 /** Start the consumer.
198 static int consumer_start( mlt_consumer this )
200 // Get the properties
201 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
204 // Report information about available muxers and codecs as YAML Tiny
205 char *s = mlt_properties_get( properties, "f" );
206 if ( s && strcmp( s, "list" ) == 0 )
208 fprintf( stderr, "---\nformats:\n" );
209 AVOutputFormat *format = NULL;
210 while ( ( format = av_oformat_next( format ) ) )
211 fprintf( stderr, " - %s\n", format->name );
212 fprintf( stderr, "...\n" );
215 s = mlt_properties_get( properties, "acodec" );
216 if ( s && strcmp( s, "list" ) == 0 )
218 fprintf( stderr, "---\naudio_codecs:\n" );
219 AVCodec *codec = NULL;
220 while ( ( codec = av_codec_next( codec ) ) )
221 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
222 fprintf( stderr, " - %s\n", codec->name );
223 fprintf( stderr, "...\n" );
226 s = mlt_properties_get( properties, "vcodec" );
227 if ( s && strcmp( s, "list" ) == 0 )
229 fprintf( stderr, "---\nvideo_codecs:\n" );
230 AVCodec *codec = NULL;
231 while ( ( codec = av_codec_next( codec ) ) )
232 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
233 fprintf( stderr, " - %s\n", codec->name );
234 fprintf( stderr, "...\n" );
238 // Check that we're not already running
239 if ( !error && !mlt_properties_get_int( properties, "running" ) )
242 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
244 // Get the width and height
245 int width = mlt_properties_get_int( properties, "width" );
246 int height = mlt_properties_get_int( properties, "height" );
248 // Obtain the size property
249 char *size = mlt_properties_get( properties, "s" );
255 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
262 fprintf( stderr, "%s: Invalid size property %s - ignoring.\n", __FILE__, size );
266 // Now ensure we honour the multiple of two requested by libavformat
267 width = ( width / 2 ) * 2;
268 height = ( height / 2 ) * 2;
269 mlt_properties_set_int( properties, "width", width );
270 mlt_properties_set_int( properties, "height", height );
272 // We need to set these on the profile as well because the s property is
273 // an alias to mlt properties that correspond to profile settings.
274 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
277 profile->width = width;
278 profile->height = height;
281 // Handle the ffmpeg command line "-r" property for frame rate
282 if ( mlt_properties_get( properties, "r" ) )
284 double frame_rate = mlt_properties_get_double( properties, "r" );
285 AVRational rational = av_d2q( frame_rate, 255 );
286 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
287 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
290 profile->frame_rate_num = rational.num;
291 profile->frame_rate_den = rational.den;
292 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
296 // Apply AVOptions that are synonyms for standard mlt_consumer options
297 if ( mlt_properties_get( properties, "ac" ) )
298 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
299 if ( mlt_properties_get( properties, "ar" ) )
300 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
302 // Assign the thread to properties
303 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
305 // Set the running state
306 mlt_properties_set_int( properties, "running", 1 );
309 pthread_create( thread, NULL, consumer_thread, this );
314 /** Stop the consumer.
317 static int consumer_stop( mlt_consumer this )
319 // Get the properties
320 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
322 // Check that we're running
323 if ( mlt_properties_get_int( properties, "running" ) )
326 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
329 mlt_properties_set_int( properties, "running", 0 );
331 // Wait for termination
332 pthread_join( *thread, NULL );
338 /** Determine if the consumer is stopped.
341 static int consumer_is_stopped( mlt_consumer this )
343 // Get the properties
344 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
345 return !mlt_properties_get_int( properties, "running" );
348 /** Process properties as AVOptions and apply to AV context obj
351 static void apply_properties( void *obj, mlt_properties properties, int flags )
354 int count = mlt_properties_count( properties );
355 for ( i = 0; i < count; i++ )
357 const char *opt_name = mlt_properties_get_name( properties, i );
358 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
360 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
361 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
362 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
363 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
365 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
370 /** Add an audio output stream
373 static AVStream *add_audio_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
375 // Get the properties
376 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
378 // Create a new stream
379 AVStream *st = av_new_stream( oc, 1 );
381 // If created, then initialise from properties
384 AVCodecContext *c = st->codec;
386 // Establish defaults from AVOptions
387 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
389 c->codec_id = codec_id;
390 c->codec_type = CODEC_TYPE_AUDIO;
392 // Setup multi-threading
393 int thread_count = mlt_properties_get_int( properties, "threads" );
394 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
395 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
396 if ( thread_count > 1 )
397 avcodec_thread_init( c, thread_count );
399 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
400 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
402 // Allow the user to override the audio fourcc
403 if ( mlt_properties_get( properties, "atag" ) )
406 char *arg = mlt_properties_get( properties, "atag" );
407 int tag = strtol( arg, &tail, 0);
409 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
413 // Process properties as AVOptions
414 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
416 int audio_qscale = mlt_properties_get_int( properties, "aq" );
417 if ( audio_qscale > QSCALE_NONE )
419 c->flags |= CODEC_FLAG_QSCALE;
420 c->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
423 // Set parameters controlled by MLT
424 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
425 c->time_base = ( AVRational ){ 1, c->sample_rate };
426 c->channels = mlt_properties_get_int( properties, "channels" );
428 if ( mlt_properties_get( properties, "alang" ) != NULL )
429 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
433 fprintf( stderr, "%s: Could not allocate a stream for audio\n", __FILE__ );
439 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
441 // We will return the audio input size from here
442 int audio_input_frame_size = 0;
445 AVCodecContext *c = st->codec;
448 AVCodec *codec = avcodec_find_encoder( c->codec_id );
450 // Continue if codec found and we can open it
451 if ( codec != NULL && avcodec_open( c, codec ) >= 0 )
453 // ugly hack for PCM codecs (will be removed ASAP with new PCM
454 // support to compute the input frame size in samples
455 if ( c->frame_size <= 1 )
457 audio_input_frame_size = audio_outbuf_size / c->channels;
458 switch(st->codec->codec_id)
460 case CODEC_ID_PCM_S16LE:
461 case CODEC_ID_PCM_S16BE:
462 case CODEC_ID_PCM_U16LE:
463 case CODEC_ID_PCM_U16BE:
464 audio_input_frame_size >>= 1;
472 audio_input_frame_size = c->frame_size;
475 // Some formats want stream headers to be seperate (hmm)
476 if ( !strcmp( oc->oformat->name, "mp4" ) ||
477 !strcmp( oc->oformat->name, "mov" ) ||
478 !strcmp( oc->oformat->name, "3gp" ) )
479 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
483 fprintf( stderr, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
486 return audio_input_frame_size;
489 static void close_audio( AVFormatContext *oc, AVStream *st )
491 avcodec_close( st->codec );
494 /** Add a video output stream
497 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
499 // Get the properties
500 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
502 // Create a new stream
503 AVStream *st = av_new_stream( oc, 0 );
507 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
508 AVCodecContext *c = st->codec;
510 // Establish defaults from AVOptions
511 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
513 c->codec_id = codec_id;
514 c->codec_type = CODEC_TYPE_VIDEO;
516 // Setup multi-threading
517 int thread_count = mlt_properties_get_int( properties, "threads" );
518 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
519 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
520 if ( thread_count > 1 )
521 avcodec_thread_init( c, thread_count );
523 // Process properties as AVOptions
524 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
526 // Set options controlled by MLT
527 c->width = mlt_properties_get_int( properties, "width" );
528 c->height = mlt_properties_get_int( properties, "height" );
529 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
530 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
531 if ( st->time_base.den == 0 )
532 st->time_base = c->time_base;
533 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
535 if ( mlt_properties_get( properties, "aspect" ) )
537 // "-aspect" on ffmpeg command line is display aspect ratio
538 double ar = mlt_properties_get_double( properties, "aspect" );
539 AVRational rational = av_d2q( ar, 255 );
541 // Update the profile and properties as well since this is an alias
542 // for mlt properties that correspond to profile settings
543 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
544 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
545 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
548 profile->display_aspect_num = rational.num;
549 profile->display_aspect_den = rational.den;
550 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
553 // Now compute the sample aspect ratio
554 rational = av_d2q( ar * c->height / c->width, 255 );
555 c->sample_aspect_ratio = rational;
556 // Update the profile and properties as well since this is an alias
557 // for mlt properties that correspond to profile settings
558 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
559 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
562 profile->sample_aspect_num = rational.num;
563 profile->sample_aspect_den = rational.den;
564 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
569 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
570 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
572 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
573 st->sample_aspect_ratio = c->sample_aspect_ratio;
576 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
578 c->flags |= CODEC_FLAG_QSCALE;
579 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
582 // Allow the user to override the video fourcc
583 if ( mlt_properties_get( properties, "vtag" ) )
586 const char *arg = mlt_properties_get( properties, "vtag" );
587 int tag = strtol( arg, &tail, 0);
589 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
593 // Some formats want stream headers to be seperate
594 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
595 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
597 // Translate these standard mlt consumer properties to ffmpeg
598 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
599 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
601 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
602 c->flags |= CODEC_FLAG_INTERLACED_DCT;
603 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
604 c->flags |= CODEC_FLAG_INTERLACED_ME;
607 // parse the ratecontrol override string
609 char *rc_override = mlt_properties_get( properties, "rc_override" );
610 for ( i = 0; rc_override; i++ )
613 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
615 fprintf( stderr, "%s: Error parsing rc_override\n", __FILE__ );
616 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
617 c->rc_override[i].start_frame = start;
618 c->rc_override[i].end_frame = end;
621 c->rc_override[i].qscale = q;
622 c->rc_override[i].quality_factor = 1.0;
626 c->rc_override[i].qscale = 0;
627 c->rc_override[i].quality_factor = -q / 100.0;
629 rc_override = strchr( rc_override, '/' );
633 c->rc_override_count = i;
634 if ( !c->rc_initial_buffer_occupancy )
635 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
636 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
639 i = mlt_properties_get_int( properties, "pass" );
641 c->flags |= CODEC_FLAG_PASS1;
643 c->flags |= CODEC_FLAG_PASS2;
644 if ( codec_id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
646 char logfilename[1024];
651 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
652 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
653 if ( c->flags & CODEC_FLAG_PASS1 )
655 f = fopen( logfilename, "w" );
657 perror( logfilename );
659 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
663 /* read the log file */
664 f = fopen( logfilename, "r" );
671 mlt_properties_set( properties, "_logfilename", logfilename );
672 fseek( f, 0, SEEK_END );
674 fseek( f, 0, SEEK_SET );
675 logbuffer = av_malloc( size + 1 );
677 fprintf( stderr, "%s: Could not allocate log buffer\n", __FILE__ );
680 size = fread( logbuffer, 1, size, f );
682 logbuffer[size] = '\0';
683 c->stats_in = logbuffer;
684 mlt_properties_set_data( properties, "_logbuffer", logbuffer, 0, ( mlt_destructor )av_free, NULL );
692 fprintf( stderr, "%s: Could not allocate a stream for video\n", __FILE__ );
698 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
701 AVFrame *picture = avcodec_alloc_frame();
703 // Determine size of the
704 int size = avpicture_get_size(pix_fmt, width, height);
706 // Allocate the picture buf
707 uint8_t *picture_buf = av_malloc(size);
709 // If we have both, then fill the image
710 if ( picture != NULL && picture_buf != NULL )
712 // Fill the frame with the allocated buffer
713 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
717 // Something failed - clean up what we can
719 av_free( picture_buf );
726 static int open_video(AVFormatContext *oc, AVStream *st)
729 AVCodecContext *video_enc = st->codec;
731 // find the video encoder
732 AVCodec *codec = avcodec_find_encoder( video_enc->codec_id );
734 if( codec && codec->pix_fmts )
736 const enum PixelFormat *p = codec->pix_fmts;
739 if( *p == video_enc->pix_fmt )
743 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
746 // Open the codec safely
747 return codec != NULL && avcodec_open( video_enc, codec ) >= 0;
750 void close_video(AVFormatContext *oc, AVStream *st)
752 avcodec_close(st->codec);
755 static inline long time_difference( struct timeval *time1 )
757 struct timeval time2;
758 gettimeofday( &time2, NULL );
759 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
762 /** The main thread - the argument is simply the consumer.
765 static void *consumer_thread( void *arg )
767 // Map the argument to the object
768 mlt_consumer this = arg;
770 // Get the properties
771 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
773 // Get the terminate on pause property
774 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
777 // Determine if feed is slow (for realtime stuff)
778 int real_time_output = mlt_properties_get_int( properties, "real_time" );
783 // Get the frame rate
784 double fps = mlt_properties_get_double( properties, "fps" );
786 // Get width and height
787 int width = mlt_properties_get_int( properties, "width" );
788 int height = mlt_properties_get_int( properties, "height" );
789 int img_width = width;
790 int img_height = height;
792 // Get default audio properties
793 mlt_audio_format aud_fmt = mlt_audio_pcm;
794 int channels = mlt_properties_get_int( properties, "channels" );
795 int frequency = mlt_properties_get_int( properties, "frequency" );
799 // AVFormat audio buffer and frame size
800 int audio_outbuf_size = ( 1024 * 42 );
801 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
802 int audio_input_frame_size = 0;
804 // AVFormat video buffer and frame count
806 int video_outbuf_size = ( 1024 * 1024 );
807 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
809 // Used for the frame properties
810 mlt_frame frame = NULL;
811 mlt_properties frame_properties = NULL;
814 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
815 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
817 // Need two av pictures for converting
818 AVFrame *output = NULL;
819 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
821 // For receiving images from an mlt_frame
823 mlt_image_format img_fmt = mlt_image_yuv422;
825 // For receiving audio samples back from the fifo
826 int16_t *buffer = av_malloc( 48000 * 2 );
829 // Allocate the context
830 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
831 AVFormatContext *oc = avformat_alloc_context( );
833 AVFormatContext *oc = av_alloc_format_context( );
837 AVStream *audio_st = NULL;
838 AVStream *video_st = NULL;
841 double audio_pts = 0;
842 double video_pts = 0;
849 long int total_time = 0;
851 // Determine the format
852 AVOutputFormat *fmt = NULL;
853 const char *filename = mlt_properties_get( properties, "target" );
854 char *format = mlt_properties_get( properties, "f" );
855 char *vcodec = mlt_properties_get( properties, "vcodec" );
856 char *acodec = mlt_properties_get( properties, "acodec" );
858 // Used to store and override codec ids
862 // Check for user selected format first
863 if ( format != NULL )
864 fmt = guess_format( format, NULL, NULL );
866 // Otherwise check on the filename
867 if ( fmt == NULL && filename != NULL )
868 fmt = guess_format( NULL, filename, NULL );
870 // Otherwise default to mpeg
872 fmt = guess_format( "mpeg", NULL, NULL );
874 // We need a filename - default to stdout?
875 if ( filename == NULL || !strcmp( filename, "" ) )
878 // Get the codec ids selected
879 audio_codec_id = fmt->audio_codec;
880 video_codec_id = fmt->video_codec;
882 // Check for audio codec overides
883 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
884 audio_codec_id = CODEC_ID_NONE;
887 AVCodec *p = avcodec_find_encoder_by_name( acodec );
889 audio_codec_id = p->id;
891 fprintf( stderr, "%s: audio codec %s unrecognised - ignoring\n", __FILE__, acodec );
894 // Check for video codec overides
895 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
896 video_codec_id = CODEC_ID_NONE;
899 AVCodec *p = avcodec_find_encoder_by_name( vcodec );
901 video_codec_id = p->id;
903 fprintf( stderr, "%s: video codec %s unrecognised - ignoring\n", __FILE__, vcodec );
910 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
911 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
913 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
914 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
916 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
917 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
919 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
920 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
922 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
923 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
925 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
926 if (metavalue != 0) oc->year = metavalue;
928 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
929 if (metavalue != 0) oc->track = metavalue;
932 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
934 // Add audio and video streams
935 if ( video_codec_id != CODEC_ID_NONE )
936 video_st = add_video_stream( this, oc, video_codec_id );
937 if ( audio_codec_id != CODEC_ID_NONE )
938 audio_st = add_audio_stream( this, oc, audio_codec_id );
940 // Set the parameters (even though we have none...)
941 if ( av_set_parameters(oc, NULL) >= 0 )
943 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
944 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
946 // Process properties as AVOptions
947 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
949 if ( video_st && !open_video( oc, video_st ) )
952 audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
954 // Open the output file, if needed
955 if ( !( fmt->flags & AVFMT_NOFILE ) )
957 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
959 fprintf( stderr, "%s: Could not open '%s'\n", __FILE__, filename );
960 mlt_properties_set_int( properties, "running", 0 );
964 // Write the stream header, if any
965 if ( mlt_properties_get_int( properties, "running" ) )
966 av_write_header( oc );
970 fprintf( stderr, "%s: Invalid output format parameters\n", __FILE__ );
971 mlt_properties_set_int( properties, "running", 0 );
976 output = alloc_picture( video_st->codec->pix_fmt, width, height );
978 // Last check - need at least one stream
979 if ( audio_st == NULL && video_st == NULL )
980 mlt_properties_set_int( properties, "running", 0 );
982 // Get the starting time (can ignore the times above)
983 gettimeofday( &ante, NULL );
985 // Loop while running
986 while( mlt_properties_get_int( properties, "running" ) && !terminated )
989 frame = mlt_consumer_rt_frame( this );
991 // Check that we have a frame to work with
994 // Increment frames despatched
997 // Default audio args
998 frame_properties = MLT_FRAME_PROPERTIES( frame );
1000 // Check for the terminated condition
1001 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1003 // Get audio and append to the fifo
1004 if ( !terminated && audio_st )
1006 samples = mlt_sample_calculator( fps, frequency, count ++ );
1007 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1009 // Create the fifo if we don't have one
1012 fifo = sample_fifo_init( frequency, channels );
1013 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1016 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1017 memset( pcm, 0, samples * channels * 2 );
1019 // Append the samples
1020 sample_fifo_append( fifo, pcm, samples * channels );
1021 total_time += ( samples * 1000000 ) / frequency;
1025 if ( !terminated && video_st )
1026 mlt_deque_push_back( queue, frame );
1028 mlt_frame_close( frame );
1031 // While we have stuff to process, process...
1034 // Write interleaved audio and video frames
1035 if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
1037 if ( ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1041 av_init_packet( &pkt );
1043 c = audio_st->codec;
1045 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
1047 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
1048 // Write the compressed frame in the media file
1049 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1050 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
1051 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "audio pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1052 pkt.flags |= PKT_FLAG_KEY;
1053 pkt.stream_index= audio_st->index;
1054 pkt.data= audio_outbuf;
1057 if ( av_interleaved_write_frame( oc, &pkt ) != 0)
1058 fprintf( stderr, "%s: Error while writing audio frame\n", __FILE__ );
1060 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), " frame_size %d\n", c->frame_size );
1061 if ( audio_codec_id == CODEC_ID_VORBIS )
1062 audio_pts = (double)c->coded_frame->pts * av_q2d( audio_st->time_base );
1064 audio_pts = (double)audio_st->pts.val * av_q2d( audio_st->time_base );
1071 else if ( video_st )
1073 if ( mlt_deque_count( queue ) )
1078 frame = mlt_deque_pop_front( queue );
1079 frame_properties = MLT_FRAME_PROPERTIES( frame );
1081 c = video_st->codec;
1083 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1090 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1092 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1096 // Convert the mlt frame to an AVPicture
1097 for ( i = 0; i < height; i ++ )
1099 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1108 // Do the colour space conversion
1110 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1111 width, height, video_st->codec->pix_fmt, SWS_FAST_BILINEAR, NULL, NULL, NULL);
1112 sws_scale( context, input->data, input->linesize, 0, height,
1113 output->data, output->linesize);
1114 sws_freeContext( context );
1116 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1119 // Apply the alpha if applicable
1120 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1122 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1125 for ( i = 0; i < height; i ++ )
1127 n = ( width + 7 ) / 8;
1128 p = output->data[ 0 ] + i * output->linesize[ 0 ];
1136 case 0: do { *p = *alpha++; p += 4;
1137 case 7: *p = *alpha++; p += 4;
1138 case 6: *p = *alpha++; p += 4;
1139 case 5: *p = *alpha++; p += 4;
1140 case 4: *p = *alpha++; p += 4;
1141 case 3: *p = *alpha++; p += 4;
1142 case 2: *p = *alpha++; p += 4;
1143 case 1: *p = *alpha++; p += 4;
1151 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1153 // raw video case. The API will change slightly in the near future for that
1155 av_init_packet(&pkt);
1157 pkt.flags |= PKT_FLAG_KEY;
1158 pkt.stream_index= video_st->index;
1159 pkt.data= (uint8_t *)output;
1160 pkt.size= sizeof(AVPicture);
1162 ret = av_write_frame(oc, &pkt);
1163 video_pts += c->frame_size;
1168 output->quality = video_st->quality;
1170 // Set frame interlace hints
1171 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1172 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1175 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1177 // If zero size, it means the image was buffered
1181 av_init_packet( &pkt );
1183 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1184 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1185 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "video pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1186 if( c->coded_frame && c->coded_frame->key_frame )
1187 pkt.flags |= PKT_FLAG_KEY;
1188 pkt.stream_index= video_st->index;
1189 pkt.data= video_outbuf;
1192 // write the compressed frame in the media file
1193 ret = av_interleaved_write_frame(oc, &pkt);
1194 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), " frame_size %d\n", c->frame_size );
1195 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1197 // Dual pass logging
1198 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out)
1199 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1203 fprintf( stderr, "%s: error with video encode\n", __FILE__ );
1207 mlt_frame_close( frame );
1215 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "audio pts %lld (%f) ", audio_st->pts.val, audio_pts );
1217 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "video pts %lld (%f) ", video_st->pts.val, video_pts );
1218 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "\n" );
1221 if ( real_time_output == 1 && frames % 12 == 0 )
1223 long passed = time_difference( &ante );
1226 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1229 if ( passed < total_time )
1231 long total = ( total_time - passed );
1232 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1233 nanosleep( &t, NULL );
1239 if ( ! real_time_output )
1242 if ( audio_st && audio_st->codec->frame_size > 1 ) for (;;)
1244 AVCodecContext *c = audio_st->codec;
1246 av_init_packet( &pkt );
1249 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1250 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1252 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
1253 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
1255 if ( pkt.size <= 0 )
1256 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1257 if ( pkt.size <= 0 )
1260 // Write the compressed frame in the media file
1261 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1262 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
1263 pkt.flags |= PKT_FLAG_KEY;
1264 pkt.stream_index = audio_st->index;
1265 pkt.data = audio_outbuf;
1266 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1268 fprintf( stderr, "%s: Error while writing flushed audio frame\n", __FILE__ );
1274 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1276 AVCodecContext *c = video_st->codec;
1278 av_init_packet( &pkt );
1281 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1282 if ( pkt.size <= 0 )
1285 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1286 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1287 if( c->coded_frame && c->coded_frame->key_frame )
1288 pkt.flags |= PKT_FLAG_KEY;
1289 pkt.stream_index = video_st->index;
1290 pkt.data = video_outbuf;
1292 // write the compressed frame in the media file
1293 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1295 fprintf( stderr, "%s: Error while writing flushed video frame\n". __FILE__ );
1304 close_video(oc, video_st);
1306 close_audio(oc, audio_st);
1308 // Write the trailer, if any
1309 av_write_trailer(oc);
1312 for(i = 0; i < oc->nb_streams; i++)
1313 av_freep(&oc->streams[i]);
1315 // Close the output file
1316 if (!(fmt->flags & AVFMT_NOFILE))
1317 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1320 url_fclose(&oc->pb);
1323 // Clean up input and output frames
1325 av_free( output->data[0] );
1327 av_free( input->data[0] );
1329 av_free( video_outbuf );
1335 // Just in case we terminated on pause
1336 mlt_properties_set_int( properties, "running", 0 );
1338 mlt_consumer_stopped( this );
1340 if ( mlt_properties_get_int( properties, "pass" ) == 2 )
1342 // Remove the dual pass log file
1343 if ( mlt_properties_get( properties, "_logfilename" ) )
1344 remove( mlt_properties_get( properties, "_logfilename" ) );
1346 // Remove the x264 dual pass logs
1347 char *cwd = getcwd( NULL, 0 );
1348 const char *file = "x264_2pass.log";
1349 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1350 sprintf( full, "%s/%s", cwd, file );
1353 file = "x264_2pass.log.temp";
1354 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1355 sprintf( full, "%s/%s", cwd, file );
1359 remove( "x264_2pass.log.temp" );
1365 /** Close the consumer.
1368 static void consumer_close( mlt_consumer this )
1370 // Stop the consumer
1371 mlt_consumer_stop( this );
1374 mlt_consumer_close( this );