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>
26 // System header files
36 // avformat header files
44 // This structure should be extended and made globally available in mlt
56 *sample_fifo, sample_fifo_s;
58 sample_fifo sample_fifo_init( int frequency, int channels )
60 sample_fifo this = calloc( 1, sizeof( sample_fifo_s ) );
61 this->frequency = frequency;
62 this->channels = channels;
66 // sample_fifo_clear and check are temporarily aborted (not working as intended)
68 void sample_fifo_clear( sample_fifo this, double time )
70 int words = ( float )( time - this->time ) * this->frequency * this->channels;
71 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) && this->used > words && words > 0 )
73 memmove( this->buffer, &this->buffer[ words ], ( this->used - words ) * sizeof( int16_t ) );
77 else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )this->time * 100 ) )
84 void sample_fifo_check( sample_fifo this, double time )
86 if ( this->used == 0 )
88 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) )
93 void sample_fifo_append( sample_fifo this, int16_t *samples, int count )
95 if ( ( this->size - this->used ) < count )
97 this->size += count * 5;
98 this->buffer = realloc( this->buffer, this->size * sizeof( int16_t ) );
101 memcpy( &this->buffer[ this->used ], samples, count * sizeof( int16_t ) );
105 int sample_fifo_used( sample_fifo this )
110 int sample_fifo_fetch( sample_fifo this, int16_t *samples, int count )
112 if ( count > this->used )
115 memcpy( samples, this->buffer, count * sizeof( int16_t ) );
117 memmove( this->buffer, &this->buffer[ count ], this->used * sizeof( int16_t ) );
119 this->time += ( double )count / this->channels / this->frequency;
124 void sample_fifo_close( sample_fifo this )
126 free( this->buffer );
130 // Forward references.
131 static int consumer_start( mlt_consumer this );
132 static int consumer_stop( mlt_consumer this );
133 static int consumer_is_stopped( mlt_consumer this );
134 static void *consumer_thread( void *arg );
135 static void consumer_close( mlt_consumer this );
137 /** Initialise the dv consumer.
140 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
142 // Allocate the consumer
143 mlt_consumer this = mlt_consumer_new( profile );
145 // If memory allocated and initialises without error
148 // Get properties from the consumer
149 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
151 // Assign close callback
152 this->close = consumer_close;
154 // Interpret the argument
156 mlt_properties_set( properties, "target", arg );
158 // sample and frame queue
159 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
161 // Audio options not fully handled by AVOptions
162 #define QSCALE_NONE (-99999)
163 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
165 // Video options not fully handled by AVOptions
166 mlt_properties_set_int( properties, "dc", 8 );
168 // Muxer options not fully handled by AVOptions
169 mlt_properties_set_double( properties, "muxdelay", 0.7 );
170 mlt_properties_set_double( properties, "muxpreload", 0.5 );
172 // Ensure termination at end of the stream
173 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
175 // Default to separate processing threads for producer and consumer with no frame dropping!
176 mlt_properties_set_int( properties, "real_time", -1 );
178 // Set up start/stop/terminated callbacks
179 this->start = consumer_start;
180 this->stop = consumer_stop;
181 this->is_stopped = consumer_is_stopped;
188 /** Start the consumer.
191 static int consumer_start( mlt_consumer this )
193 // Get the properties
194 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
196 // Check that we're not already running
197 if ( !mlt_properties_get_int( properties, "running" ) )
200 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
202 // Get the width and height
203 int width = mlt_properties_get_int( properties, "width" );
204 int height = mlt_properties_get_int( properties, "height" );
206 // Obtain the size property
207 char *size = mlt_properties_get( properties, "s" );
213 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
220 fprintf( stderr, "%s: Invalid size property %s - ignoring.\n", __FILE__, size );
224 // Now ensure we honour the multiple of two requested by libavformat
225 width = ( width / 2 ) * 2;
226 height = ( height / 2 ) * 2;
227 mlt_properties_set_int( properties, "width", width );
228 mlt_properties_set_int( properties, "height", height );
230 // We need to set these on the profile as well because the s property is
231 // an alias to mlt properties that correspond to profile settings.
232 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
235 profile->width = width;
236 profile->height = height;
239 // Handle the ffmpeg command line "-r" property for frame rate
240 if ( mlt_properties_get( properties, "r" ) )
242 double frame_rate = mlt_properties_get_double( properties, "r" );
243 AVRational rational = av_d2q( frame_rate, 255 );
244 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
245 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
248 profile->frame_rate_num = rational.num;
249 profile->frame_rate_den = rational.den;
250 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
254 // Apply AVOptions that are synonyms for standard mlt_consumer options
255 if ( mlt_properties_get( properties, "ac" ) )
256 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
257 if ( mlt_properties_get( properties, "ar" ) )
258 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
260 // Assign the thread to properties
261 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
263 // Set the running state
264 mlt_properties_set_int( properties, "running", 1 );
267 pthread_create( thread, NULL, consumer_thread, this );
272 /** Stop the consumer.
275 static int consumer_stop( mlt_consumer this )
277 // Get the properties
278 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
280 // Check that we're running
281 if ( mlt_properties_get_int( properties, "running" ) )
284 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
287 mlt_properties_set_int( properties, "running", 0 );
289 // Wait for termination
290 pthread_join( *thread, NULL );
296 /** Determine if the consumer is stopped.
299 static int consumer_is_stopped( mlt_consumer this )
301 // Get the properties
302 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
303 return !mlt_properties_get_int( properties, "running" );
306 /** Process properties as AVOptions and apply to AV context obj
309 static void apply_properties( void *obj, mlt_properties properties, int flags )
312 int count = mlt_properties_count( properties );
313 for ( i = 0; i < count; i++ )
315 const char *opt_name = mlt_properties_get_name( properties, i );
316 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
318 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
319 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
320 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
321 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
323 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
328 /** Add an audio output stream
331 static AVStream *add_audio_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
333 // Get the properties
334 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
336 // Create a new stream
337 AVStream *st = av_new_stream( oc, 1 );
339 // If created, then initialise from properties
342 AVCodecContext *c = st->codec;
344 // Establish defaults from AVOptions
345 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
347 c->codec_id = codec_id;
348 c->codec_type = CODEC_TYPE_AUDIO;
350 // Setup multi-threading
351 int thread_count = mlt_properties_get_int( properties, "threads" );
352 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
353 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
354 if ( thread_count > 1 )
355 avcodec_thread_init( c, thread_count );
357 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
358 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
360 // Allow the user to override the audio fourcc
361 if ( mlt_properties_get( properties, "atag" ) )
364 char *arg = mlt_properties_get( properties, "atag" );
365 int tag = strtol( arg, &tail, 0);
367 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
371 // Process properties as AVOptions
372 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
374 int audio_qscale = mlt_properties_get_int( properties, "aq" );
375 if ( audio_qscale > QSCALE_NONE )
377 c->flags |= CODEC_FLAG_QSCALE;
378 c->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
381 // Set parameters controlled by MLT
382 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
383 c->channels = mlt_properties_get_int( properties, "channels" );
385 if ( mlt_properties_get( properties, "alang" ) != NULL )
386 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
390 fprintf( stderr, "%s: Could not allocate a stream for audio\n", __FILE__ );
396 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
398 // We will return the audio input size from here
399 int audio_input_frame_size = 0;
402 AVCodecContext *c = st->codec;
405 AVCodec *codec = avcodec_find_encoder( c->codec_id );
407 // Continue if codec found and we can open it
408 if ( codec != NULL && avcodec_open( c, codec ) >= 0 )
410 // ugly hack for PCM codecs (will be removed ASAP with new PCM
411 // support to compute the input frame size in samples
412 if ( c->frame_size <= 1 )
414 audio_input_frame_size = audio_outbuf_size / c->channels;
415 switch(st->codec->codec_id)
417 case CODEC_ID_PCM_S16LE:
418 case CODEC_ID_PCM_S16BE:
419 case CODEC_ID_PCM_U16LE:
420 case CODEC_ID_PCM_U16BE:
421 audio_input_frame_size >>= 1;
429 audio_input_frame_size = c->frame_size;
432 // Some formats want stream headers to be seperate (hmm)
433 if( !strcmp( oc->oformat->name, "mp4" ) ||
434 !strcmp( oc->oformat->name, "mov" ) ||
435 !strcmp( oc->oformat->name, "3gp" ) )
436 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
440 fprintf( stderr, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
443 return audio_input_frame_size;
446 static void close_audio( AVFormatContext *oc, AVStream *st )
448 avcodec_close( st->codec );
451 /** Add a video output stream
454 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
456 // Get the properties
457 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
459 // Create a new stream
460 AVStream *st = av_new_stream( oc, 0 );
464 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
465 AVCodecContext *c = st->codec;
467 // Establish defaults from AVOptions
468 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
470 c->codec_id = codec_id;
471 c->codec_type = CODEC_TYPE_VIDEO;
473 // Setup multi-threading
474 int thread_count = mlt_properties_get_int( properties, "threads" );
475 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
476 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
477 if ( thread_count > 1 )
478 avcodec_thread_init( c, thread_count );
480 // Process properties as AVOptions
481 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
483 // Set options controlled by MLT
484 c->width = mlt_properties_get_int( properties, "width" );
485 c->height = mlt_properties_get_int( properties, "height" );
486 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
487 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
488 st->time_base = c->time_base;
489 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
491 if ( mlt_properties_get( properties, "aspect" ) )
493 // "-aspect" on ffmpeg command line is display aspect ratio
494 double ar = mlt_properties_get_double( properties, "aspect" );
495 AVRational rational = av_d2q( ar, 255 );
497 // Update the profile and properties as well since this is an alias
498 // for mlt properties that correspond to profile settings
499 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
500 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
501 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
504 profile->display_aspect_num = rational.num;
505 profile->display_aspect_den = rational.den;
506 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
509 // Now compute the sample aspect ratio
510 rational = av_d2q( ar * c->height / c->width, 255 );
511 c->sample_aspect_ratio = rational;
512 // Update the profile and properties as well since this is an alias
513 // for mlt properties that correspond to profile settings
514 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
515 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
518 profile->sample_aspect_num = rational.num;
519 profile->sample_aspect_den = rational.den;
520 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
525 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
526 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
528 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
529 st->sample_aspect_ratio = c->sample_aspect_ratio;
532 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
534 c->flags |= CODEC_FLAG_QSCALE;
535 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
538 // Allow the user to override the video fourcc
539 if ( mlt_properties_get( properties, "vtag" ) )
542 const char *arg = mlt_properties_get( properties, "vtag" );
543 int tag = strtol( arg, &tail, 0);
545 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
549 // Some formats want stream headers to be seperate
550 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
551 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
553 // Translate these standard mlt consumer properties to ffmpeg
554 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
555 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
557 if ( mlt_properties_get_int( properties, "ildct" ) )
558 c->flags |= CODEC_FLAG_INTERLACED_DCT;
559 if ( mlt_properties_get_int( properties, "ilme" ) )
560 c->flags |= CODEC_FLAG_INTERLACED_ME;
563 // parse the ratecontrol override string
565 char *rc_override = mlt_properties_get( properties, "rc_override" );
566 for ( i = 0; rc_override; i++ )
569 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
571 fprintf( stderr, "%s: Error parsing rc_override\n", __FILE__ );
572 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
573 c->rc_override[i].start_frame = start;
574 c->rc_override[i].end_frame = end;
577 c->rc_override[i].qscale = q;
578 c->rc_override[i].quality_factor = 1.0;
582 c->rc_override[i].qscale = 0;
583 c->rc_override[i].quality_factor = -q / 100.0;
585 rc_override = strchr( rc_override, '/' );
589 c->rc_override_count = i;
590 if ( !c->rc_initial_buffer_occupancy )
591 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
592 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
595 i = mlt_properties_get_int( properties, "pass" );
597 c->flags |= CODEC_FLAG_PASS1;
599 c->flags |= CODEC_FLAG_PASS2;
600 if ( codec_id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
602 char logfilename[1024];
607 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
608 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
609 if ( c->flags & CODEC_FLAG_PASS1 )
611 f = fopen( logfilename, "w" );
613 perror( logfilename );
615 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
619 /* read the log file */
620 f = fopen( logfilename, "r" );
627 mlt_properties_set( properties, "_logfilename", logfilename );
628 fseek( f, 0, SEEK_END );
630 fseek( f, 0, SEEK_SET );
631 logbuffer = av_malloc( size + 1 );
633 fprintf( stderr, "%s: Could not allocate log buffer\n", __FILE__ );
636 size = fread( logbuffer, 1, size, f );
638 logbuffer[size] = '\0';
639 c->stats_in = logbuffer;
640 mlt_properties_set_data( properties, "_logbuffer", logbuffer, 0, ( mlt_destructor )av_free, NULL );
648 fprintf( stderr, "%s: Could not allocate a stream for video\n", __FILE__ );
654 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
657 AVFrame *picture = avcodec_alloc_frame();
659 // Determine size of the
660 int size = avpicture_get_size(pix_fmt, width, height);
662 // Allocate the picture buf
663 uint8_t *picture_buf = av_malloc(size);
665 // If we have both, then fill the image
666 if ( picture != NULL && picture_buf != NULL )
668 // Fill the frame with the allocated buffer
669 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
673 // Something failed - clean up what we can
675 av_free( picture_buf );
682 static int open_video(AVFormatContext *oc, AVStream *st)
685 AVCodecContext *video_enc = st->codec;
687 // find the video encoder
688 AVCodec *codec = avcodec_find_encoder( video_enc->codec_id );
690 if( codec && codec->pix_fmts )
692 const enum PixelFormat *p = codec->pix_fmts;
695 if( *p == video_enc->pix_fmt )
699 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
702 // Open the codec safely
703 return codec != NULL && avcodec_open( video_enc, codec ) >= 0;
706 void close_video(AVFormatContext *oc, AVStream *st)
708 avcodec_close(st->codec);
711 static inline long time_difference( struct timeval *time1 )
713 struct timeval time2;
714 gettimeofday( &time2, NULL );
715 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
718 /** The main thread - the argument is simply the consumer.
721 static void *consumer_thread( void *arg )
723 // Map the argument to the object
724 mlt_consumer this = arg;
726 // Get the properties
727 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
729 // Get the terminate on pause property
730 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
733 // Determine if feed is slow (for realtime stuff)
734 int real_time_output = mlt_properties_get_int( properties, "real_time" );
739 // Get the frame rate
740 double fps = mlt_properties_get_double( properties, "fps" );
742 // Get width and height
743 int width = mlt_properties_get_int( properties, "width" );
744 int height = mlt_properties_get_int( properties, "height" );
745 int img_width = width;
746 int img_height = height;
748 // Get default audio properties
749 mlt_audio_format aud_fmt = mlt_audio_pcm;
750 int channels = mlt_properties_get_int( properties, "channels" );
751 int frequency = mlt_properties_get_int( properties, "frequency" );
755 // AVFormat audio buffer and frame size
756 int audio_outbuf_size = 10000;
757 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
758 int audio_input_frame_size = 0;
760 // AVFormat video buffer and frame count
762 int video_outbuf_size = ( 1024 * 1024 );
763 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
765 // Used for the frame properties
766 mlt_frame frame = NULL;
767 mlt_properties frame_properties = NULL;
770 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
771 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
773 // Need two av pictures for converting
774 AVFrame *output = NULL;
775 AVFrame *input = alloc_picture( PIX_FMT_YUV422, width, height );
777 // For receiving images from an mlt_frame
779 mlt_image_format img_fmt = mlt_image_yuv422;
781 // For receiving audio samples back from the fifo
782 int16_t *buffer = av_malloc( 48000 * 2 );
785 // Allocate the context
786 AVFormatContext *oc = av_alloc_format_context( );
789 AVStream *audio_st = NULL;
790 AVStream *video_st = NULL;
793 double audio_pts = 0;
794 double video_pts = 0;
801 long int total_time = 0;
803 // Determine the format
804 AVOutputFormat *fmt = NULL;
805 char *filename = mlt_properties_get( properties, "target" );
806 char *format = mlt_properties_get( properties, "f" );
807 char *vcodec = mlt_properties_get( properties, "vcodec" );
808 char *acodec = mlt_properties_get( properties, "acodec" );
810 // Used to store and override codec ids
814 // Check for user selected format first
815 if ( format != NULL )
816 fmt = guess_format( format, NULL, NULL );
818 // Otherwise check on the filename
819 if ( fmt == NULL && filename != NULL )
820 fmt = guess_format( NULL, filename, NULL );
822 // Otherwise default to mpeg
824 fmt = guess_format( "mpeg", NULL, NULL );
826 // We need a filename - default to stdout?
827 if ( filename == NULL || !strcmp( filename, "" ) )
830 // Get the codec ids selected
831 audio_codec_id = fmt->audio_codec;
832 video_codec_id = fmt->video_codec;
834 // Check for audio codec overides
835 if ( acodec != NULL )
837 AVCodec *p = avcodec_find_encoder_by_name( acodec );
839 audio_codec_id = p->id;
841 fprintf( stderr, "%s: audio codec %s unrecognised - ignoring\n", __FILE__, acodec );
844 // Check for video codec overides
845 if ( vcodec != NULL )
847 AVCodec *p = avcodec_find_encoder_by_name( vcodec );
849 video_codec_id = p->id;
851 fprintf( stderr, "%s: video codec %s unrecognised - ignoring\n", __FILE__, vcodec );
858 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
859 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
861 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
862 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
864 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
865 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
867 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
868 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
870 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
871 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
873 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
874 if (metavalue != 0) oc->year = metavalue;
876 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
877 if (metavalue != 0) oc->track = metavalue;
880 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
882 // Add audio and video streams
883 if ( fmt->video_codec != CODEC_ID_NONE )
884 video_st = add_video_stream( this, oc, video_codec_id );
885 if ( fmt->audio_codec != CODEC_ID_NONE )
886 audio_st = add_audio_stream( this, oc, audio_codec_id );
888 // Set the parameters (even though we have none...)
889 if ( av_set_parameters(oc, NULL) >= 0 )
891 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
892 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
894 // Process properties as AVOptions
895 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
897 if ( video_st && !open_video( oc, video_st ) )
900 audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
902 // Open the output file, if needed
903 if ( !( fmt->flags & AVFMT_NOFILE ) )
905 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
907 fprintf( stderr, "%s: Could not open '%s'\n", __FILE__, filename );
908 mlt_properties_set_int( properties, "running", 0 );
912 // Write the stream header, if any
913 if ( mlt_properties_get_int( properties, "running" ) )
914 av_write_header( oc );
918 fprintf( stderr, "%s: Invalid output format parameters\n", __FILE__ );
919 mlt_properties_set_int( properties, "running", 0 );
924 output = alloc_picture( video_st->codec->pix_fmt, width, height );
926 // Last check - need at least one stream
927 if ( audio_st == NULL && video_st == NULL )
928 mlt_properties_set_int( properties, "running", 0 );
930 // Get the starting time (can ignore the times above)
931 gettimeofday( &ante, NULL );
933 // Loop while running
934 while( mlt_properties_get_int( properties, "running" ) && !terminated )
937 frame = mlt_consumer_rt_frame( this );
939 // Check that we have a frame to work with
942 // Increment frames despatched
945 // Default audio args
946 frame_properties = MLT_FRAME_PROPERTIES( frame );
948 // Check for the terminated condition
949 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
951 // Get audio and append to the fifo
952 if ( !terminated && audio_st )
954 samples = mlt_sample_calculator( fps, frequency, count ++ );
955 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
957 // Create the fifo if we don't have one
960 fifo = sample_fifo_init( frequency, channels );
961 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
964 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
965 memset( pcm, 0, samples * channels * 2 );
967 // Append the samples
968 sample_fifo_append( fifo, pcm, samples * channels );
969 total_time += ( samples * 1000000 ) / frequency;
973 if ( !terminated && video_st )
974 mlt_deque_push_back( queue, frame );
976 mlt_frame_close( frame );
979 // While we have stuff to process, process...
983 audio_pts = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;
988 video_pts = (double)video_st->pts.val * video_st->time_base.num / video_st->time_base.den;
992 // Write interleaved audio and video frames
993 if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
995 if ( channels * audio_input_frame_size < sample_fifo_used( fifo ) )
999 av_init_packet( &pkt );
1001 c = audio_st->codec;
1003 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
1005 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
1006 // Write the compressed frame in the media file
1007 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1008 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
1009 pkt.flags |= PKT_FLAG_KEY;
1010 pkt.stream_index= audio_st->index;
1011 pkt.data= audio_outbuf;
1014 if ( av_interleaved_write_frame( oc, &pkt ) != 0)
1015 fprintf( stderr, "%s: Error while writing audio frame\n", __FILE__ );
1017 audio_pts += c->frame_size;
1024 else if ( video_st )
1026 if ( mlt_deque_count( queue ) )
1031 frame = mlt_deque_pop_front( queue );
1032 frame_properties = MLT_FRAME_PROPERTIES( frame );
1034 c = video_st->codec;
1036 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1043 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1045 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1049 // Convert the mlt frame to an AVPicture
1050 for ( i = 0; i < height; i ++ )
1052 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1061 // Do the colour space conversion
1063 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUV422,
1064 width, height, video_st->codec->pix_fmt, SWS_FAST_BILINEAR, NULL, NULL, NULL);
1065 sws_scale( context, input->data, input->linesize, 0, height,
1066 output->data, output->linesize);
1067 sws_freeContext( context );
1069 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUV422, width, height );
1072 // Apply the alpha if applicable
1073 if ( video_st->codec->pix_fmt == PIX_FMT_RGBA32 )
1075 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1078 for ( i = 0; i < height; i ++ )
1080 n = ( width + 7 ) / 8;
1081 p = output->data[ 0 ] + i * output->linesize[ 0 ];
1089 case 0: do { *p = *alpha++; p += 4;
1090 case 7: *p = *alpha++; p += 4;
1091 case 6: *p = *alpha++; p += 4;
1092 case 5: *p = *alpha++; p += 4;
1093 case 4: *p = *alpha++; p += 4;
1094 case 3: *p = *alpha++; p += 4;
1095 case 2: *p = *alpha++; p += 4;
1096 case 1: *p = *alpha++; p += 4;
1104 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1106 // raw video case. The API will change slightly in the near future for that
1108 av_init_packet(&pkt);
1110 pkt.flags |= PKT_FLAG_KEY;
1111 pkt.stream_index= video_st->index;
1112 pkt.data= (uint8_t *)output;
1113 pkt.size= sizeof(AVPicture);
1115 ret = av_write_frame(oc, &pkt);
1116 video_pts += c->frame_size;
1121 output->quality = video_st->quality;
1123 // Set frame interlace hints
1124 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1125 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1128 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1130 // If zero size, it means the image was buffered
1134 av_init_packet( &pkt );
1136 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1137 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1138 if( c->coded_frame && c->coded_frame->key_frame )
1139 pkt.flags |= PKT_FLAG_KEY;
1140 pkt.stream_index= video_st->index;
1141 pkt.data= video_outbuf;
1144 // write the compressed frame in the media file
1145 ret = av_interleaved_write_frame(oc, &pkt);
1146 video_pts += c->frame_size;
1148 // Dual pass logging
1149 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out)
1150 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1154 fprintf( stderr, "%s: error with video encode\n", __FILE__ );
1158 mlt_frame_close( frame );
1167 if ( real_time_output == 1 && frames % 12 == 0 )
1169 long passed = time_difference( &ante );
1172 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1175 if ( passed < total_time )
1177 long total = ( total_time - passed );
1178 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1179 nanosleep( &t, NULL );
1185 if ( ! real_time_output )
1188 if ( audio_st && audio_st->codec->frame_size > 1 ) for (;;)
1190 AVCodecContext *c = audio_st->codec;
1192 av_init_packet( &pkt );
1195 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1196 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1198 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
1199 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
1201 if ( pkt.size <= 0 )
1202 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1203 if ( pkt.size <= 0 )
1206 // Write the compressed frame in the media file
1207 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1208 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
1209 pkt.flags |= PKT_FLAG_KEY;
1210 pkt.stream_index = audio_st->index;
1211 pkt.data = audio_outbuf;
1212 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1214 fprintf( stderr, "%s: Error while writing flushed audio frame\n", __FILE__ );
1220 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1222 AVCodecContext *c = video_st->codec;
1224 av_init_packet( &pkt );
1227 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1228 if ( pkt.size <= 0 )
1231 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1232 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1233 if( c->coded_frame && c->coded_frame->key_frame )
1234 pkt.flags |= PKT_FLAG_KEY;
1235 pkt.stream_index = video_st->index;
1236 pkt.data = video_outbuf;
1238 // write the compressed frame in the media file
1239 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1241 fprintf( stderr, "%s: Error while writing flushed video frame\n". __FILE__ );
1250 close_video(oc, video_st);
1252 close_audio(oc, audio_st);
1254 // Write the trailer, if any
1255 av_write_trailer(oc);
1258 for(i = 0; i < oc->nb_streams; i++)
1259 av_freep(&oc->streams[i]);
1261 // Close the output file
1262 if (!(fmt->flags & AVFMT_NOFILE))
1263 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1266 url_fclose(&oc->pb);
1269 // Clean up input and output frames
1271 av_free( output->data[0] );
1273 av_free( input->data[0] );
1275 av_free( video_outbuf );
1281 // Just in case we terminated on pause
1282 mlt_properties_set_int( properties, "running", 0 );
1284 mlt_consumer_stopped( this );
1286 if ( mlt_properties_get_int( properties, "pass" ) == 2 )
1288 // Remove the dual pass log file
1289 if ( mlt_properties_get( properties, "_logfilename" ) )
1290 remove( mlt_properties_get( properties, "_logfilename" ) );
1292 // Remove the x264 dual pass logs
1293 char *cwd = getcwd( NULL, 0 );
1294 char *file = "x264_2pass.log";
1295 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1296 sprintf( full, "%s/%s", cwd, file );
1299 file = "x264_2pass.log.temp";
1300 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1301 sprintf( full, "%s/%s", cwd, file );
1305 remove( "x264_2pass.log.temp" );
1311 /** Close the consumer.
1314 static void consumer_close( mlt_consumer this )
1316 // Stop the consumer
1317 mlt_consumer_stop( this );
1320 mlt_consumer_close( this );