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, int alloc )
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), alloc, NULL );
364 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
365 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), alloc );
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 char *apre = mlt_properties_get( properties, "apre" );
422 mlt_properties p = mlt_properties_load( apre );
423 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
424 mlt_properties_close( p );
426 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
428 int audio_qscale = mlt_properties_get_int( properties, "aq" );
429 if ( audio_qscale > QSCALE_NONE )
431 c->flags |= CODEC_FLAG_QSCALE;
432 c->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
435 // Set parameters controlled by MLT
436 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
437 c->time_base = ( AVRational ){ 1, c->sample_rate };
438 c->channels = mlt_properties_get_int( properties, "channels" );
440 if ( mlt_properties_get( properties, "alang" ) != NULL )
441 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
445 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not allocate a stream for audio\n" );
451 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
453 // We will return the audio input size from here
454 int audio_input_frame_size = 0;
457 AVCodecContext *c = st->codec;
460 AVCodec *codec = avcodec_find_encoder( c->codec_id );
462 // Continue if codec found and we can open it
463 if ( codec != NULL && avcodec_open( c, codec ) >= 0 )
465 // ugly hack for PCM codecs (will be removed ASAP with new PCM
466 // support to compute the input frame size in samples
467 if ( c->frame_size <= 1 )
469 audio_input_frame_size = audio_outbuf_size / c->channels;
470 switch(st->codec->codec_id)
472 case CODEC_ID_PCM_S16LE:
473 case CODEC_ID_PCM_S16BE:
474 case CODEC_ID_PCM_U16LE:
475 case CODEC_ID_PCM_U16BE:
476 audio_input_frame_size >>= 1;
484 audio_input_frame_size = c->frame_size;
487 // Some formats want stream headers to be seperate (hmm)
488 if ( !strcmp( oc->oformat->name, "mp4" ) ||
489 !strcmp( oc->oformat->name, "mov" ) ||
490 !strcmp( oc->oformat->name, "3gp" ) )
491 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
495 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
498 return audio_input_frame_size;
501 static void close_audio( AVFormatContext *oc, AVStream *st )
503 if ( st && st->codec )
504 avcodec_close( st->codec );
507 /** Add a video output stream
510 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
512 // Get the properties
513 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
515 // Create a new stream
516 AVStream *st = av_new_stream( oc, 0 );
520 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
521 AVCodecContext *c = st->codec;
523 // Establish defaults from AVOptions
524 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
526 c->codec_id = codec_id;
527 c->codec_type = CODEC_TYPE_VIDEO;
529 // Setup multi-threading
530 int thread_count = mlt_properties_get_int( properties, "threads" );
531 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
532 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
533 if ( thread_count > 1 )
534 avcodec_thread_init( c, thread_count );
536 // Process properties as AVOptions
537 char *vpre = mlt_properties_get( properties, "vpre" );
540 mlt_properties p = mlt_properties_load( vpre );
541 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
542 mlt_properties_close( p );
544 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
546 // Set options controlled by MLT
547 c->width = mlt_properties_get_int( properties, "width" );
548 c->height = mlt_properties_get_int( properties, "height" );
549 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
550 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
551 if ( st->time_base.den == 0 )
552 st->time_base = c->time_base;
553 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
555 if ( mlt_properties_get( properties, "aspect" ) )
557 // "-aspect" on ffmpeg command line is display aspect ratio
558 double ar = mlt_properties_get_double( properties, "aspect" );
559 AVRational rational = av_d2q( ar, 255 );
561 // Update the profile and properties as well since this is an alias
562 // for mlt properties that correspond to profile settings
563 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
564 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
565 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
568 profile->display_aspect_num = rational.num;
569 profile->display_aspect_den = rational.den;
570 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
573 // Now compute the sample aspect ratio
574 rational = av_d2q( ar * c->height / c->width, 255 );
575 c->sample_aspect_ratio = rational;
576 // Update the profile and properties as well since this is an alias
577 // for mlt properties that correspond to profile settings
578 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
579 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
582 profile->sample_aspect_num = rational.num;
583 profile->sample_aspect_den = rational.den;
584 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
589 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
590 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
592 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
593 st->sample_aspect_ratio = c->sample_aspect_ratio;
596 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
598 c->flags |= CODEC_FLAG_QSCALE;
599 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
602 // Allow the user to override the video fourcc
603 if ( mlt_properties_get( properties, "vtag" ) )
606 const char *arg = mlt_properties_get( properties, "vtag" );
607 int tag = strtol( arg, &tail, 0);
609 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
613 // Some formats want stream headers to be seperate
614 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
615 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
617 // Translate these standard mlt consumer properties to ffmpeg
618 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
619 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
621 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
622 c->flags |= CODEC_FLAG_INTERLACED_DCT;
623 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
624 c->flags |= CODEC_FLAG_INTERLACED_ME;
627 // parse the ratecontrol override string
629 char *rc_override = mlt_properties_get( properties, "rc_override" );
630 for ( i = 0; rc_override; i++ )
633 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
635 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "Error parsing rc_override\n" );
636 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
637 c->rc_override[i].start_frame = start;
638 c->rc_override[i].end_frame = end;
641 c->rc_override[i].qscale = q;
642 c->rc_override[i].quality_factor = 1.0;
646 c->rc_override[i].qscale = 0;
647 c->rc_override[i].quality_factor = -q / 100.0;
649 rc_override = strchr( rc_override, '/' );
653 c->rc_override_count = i;
654 if ( !c->rc_initial_buffer_occupancy )
655 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
656 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
659 i = mlt_properties_get_int( properties, "pass" );
661 c->flags |= CODEC_FLAG_PASS1;
663 c->flags |= CODEC_FLAG_PASS2;
664 if ( codec_id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
666 char logfilename[1024];
671 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
672 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
673 if ( c->flags & CODEC_FLAG_PASS1 )
675 f = fopen( logfilename, "w" );
677 perror( logfilename );
679 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
683 /* read the log file */
684 f = fopen( logfilename, "r" );
691 mlt_properties_set( properties, "_logfilename", logfilename );
692 fseek( f, 0, SEEK_END );
694 fseek( f, 0, SEEK_SET );
695 logbuffer = av_malloc( size + 1 );
697 mlt_log_fatal( MLT_CONSUMER_SERVICE( this ), "Could not allocate log buffer\n" );
700 size = fread( logbuffer, 1, size, f );
702 logbuffer[size] = '\0';
703 c->stats_in = logbuffer;
704 mlt_properties_set_data( properties, "_logbuffer", logbuffer, 0, ( mlt_destructor )av_free, NULL );
712 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not allocate a stream for video\n" );
718 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
721 AVFrame *picture = avcodec_alloc_frame();
723 // Determine size of the
724 int size = avpicture_get_size(pix_fmt, width, height);
726 // Allocate the picture buf
727 uint8_t *picture_buf = av_malloc(size);
729 // If we have both, then fill the image
730 if ( picture != NULL && picture_buf != NULL )
732 // Fill the frame with the allocated buffer
733 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
737 // Something failed - clean up what we can
739 av_free( picture_buf );
746 static int open_video(AVFormatContext *oc, AVStream *st)
749 AVCodecContext *video_enc = st->codec;
751 // find the video encoder
752 AVCodec *codec = avcodec_find_encoder( video_enc->codec_id );
754 if( codec && codec->pix_fmts )
756 const enum PixelFormat *p = codec->pix_fmts;
759 if( *p == video_enc->pix_fmt )
763 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
766 // Open the codec safely
767 return codec != NULL && avcodec_open( video_enc, codec ) >= 0;
770 void close_video(AVFormatContext *oc, AVStream *st)
772 if ( st && st->codec )
773 avcodec_close(st->codec);
776 static inline long time_difference( struct timeval *time1 )
778 struct timeval time2;
779 gettimeofday( &time2, NULL );
780 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
783 /** The main thread - the argument is simply the consumer.
786 static void *consumer_thread( void *arg )
788 // Map the argument to the object
789 mlt_consumer this = arg;
791 // Get the properties
792 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
794 // Get the terminate on pause property
795 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
798 // Determine if feed is slow (for realtime stuff)
799 int real_time_output = mlt_properties_get_int( properties, "real_time" );
804 // Get the frame rate
805 double fps = mlt_properties_get_double( properties, "fps" );
807 // Get width and height
808 int width = mlt_properties_get_int( properties, "width" );
809 int height = mlt_properties_get_int( properties, "height" );
810 int img_width = width;
811 int img_height = height;
813 // Get default audio properties
814 mlt_audio_format aud_fmt = mlt_audio_s16;
815 int channels = mlt_properties_get_int( properties, "channels" );
816 int frequency = mlt_properties_get_int( properties, "frequency" );
820 // AVFormat audio buffer and frame size
821 int audio_outbuf_size = ( 1024 * 42 );
822 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
823 int audio_input_frame_size = 0;
825 // AVFormat video buffer and frame count
827 int video_outbuf_size = ( 1024 * 1024 );
828 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
830 // Used for the frame properties
831 mlt_frame frame = NULL;
832 mlt_properties frame_properties = NULL;
835 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
836 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
838 // Need two av pictures for converting
839 AVFrame *output = NULL;
840 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
842 // For receiving images from an mlt_frame
844 mlt_image_format img_fmt = mlt_image_yuv422;
846 // For receiving audio samples back from the fifo
847 int16_t *buffer = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
850 // Allocate the context
851 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
852 AVFormatContext *oc = avformat_alloc_context( );
854 AVFormatContext *oc = av_alloc_format_context( );
858 AVStream *audio_st = NULL;
859 AVStream *video_st = NULL;
862 double audio_pts = 0;
863 double video_pts = 0;
870 long int total_time = 0;
872 // Determine the format
873 AVOutputFormat *fmt = NULL;
874 const char *filename = mlt_properties_get( properties, "target" );
875 char *format = mlt_properties_get( properties, "f" );
876 char *vcodec = mlt_properties_get( properties, "vcodec" );
877 char *acodec = mlt_properties_get( properties, "acodec" );
879 // Used to store and override codec ids
883 // Check for user selected format first
884 if ( format != NULL )
885 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
886 fmt = guess_format( format, NULL, NULL );
888 fmt = av_guess_format( format, NULL, NULL );
891 // Otherwise check on the filename
892 if ( fmt == NULL && filename != NULL )
893 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
894 fmt = guess_format( NULL, filename, NULL );
896 fmt = av_guess_format( NULL, filename, NULL );
899 // Otherwise default to mpeg
901 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
902 fmt = guess_format( "mpeg", NULL, NULL );
904 fmt = av_guess_format( "mpeg", NULL, NULL );
907 // We need a filename - default to stdout?
908 if ( filename == NULL || !strcmp( filename, "" ) )
911 // Get the codec ids selected
912 audio_codec_id = fmt->audio_codec;
913 video_codec_id = fmt->video_codec;
915 // Check for audio codec overides
916 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
917 audio_codec_id = CODEC_ID_NONE;
920 AVCodec *p = avcodec_find_encoder_by_name( acodec );
922 audio_codec_id = p->id;
924 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "audio codec %s unrecognised - ignoring\n", acodec );
927 // Check for video codec overides
928 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
929 video_codec_id = CODEC_ID_NONE;
932 AVCodec *p = avcodec_find_encoder_by_name( vcodec );
934 video_codec_id = p->id;
936 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "video codec %s unrecognised - ignoring\n", vcodec );
943 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
944 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
946 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
947 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
949 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
950 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
952 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
953 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
955 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
956 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
958 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
959 if (metavalue != 0) oc->year = metavalue;
961 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
962 if (metavalue != 0) oc->track = metavalue;
965 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
967 // Add audio and video streams
968 if ( video_codec_id != CODEC_ID_NONE )
969 video_st = add_video_stream( this, oc, video_codec_id );
970 if ( audio_codec_id != CODEC_ID_NONE )
971 audio_st = add_audio_stream( this, oc, audio_codec_id );
973 // Set the parameters (even though we have none...)
974 if ( av_set_parameters(oc, NULL) >= 0 )
976 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
977 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
979 // Process properties as AVOptions
980 char *fpre = mlt_properties_get( properties, "fpre" );
983 mlt_properties p = mlt_properties_load( fpre );
984 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM, 1 );
985 mlt_properties_close( p );
987 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM, 0 );
989 if ( video_st && !open_video( oc, video_st ) )
993 audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
994 if ( !audio_input_frame_size )
998 // Open the output file, if needed
999 if ( !( fmt->flags & AVFMT_NOFILE ) )
1001 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1003 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Could not open '%s'\n", filename );
1004 mlt_properties_set_int( properties, "running", 0 );
1008 // Write the stream header, if any
1009 if ( mlt_properties_get_int( properties, "running" ) )
1010 av_write_header( oc );
1014 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "Invalid output format parameters\n" );
1015 mlt_properties_set_int( properties, "running", 0 );
1020 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1022 // Last check - need at least one stream
1023 if ( audio_st == NULL && video_st == NULL )
1024 mlt_properties_set_int( properties, "running", 0 );
1026 // Get the starting time (can ignore the times above)
1027 gettimeofday( &ante, NULL );
1029 // Loop while running
1030 while( mlt_properties_get_int( properties, "running" ) &&
1031 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1034 frame = mlt_consumer_rt_frame( this );
1036 // Check that we have a frame to work with
1037 if ( frame != NULL )
1039 // Increment frames despatched
1042 // Default audio args
1043 frame_properties = MLT_FRAME_PROPERTIES( frame );
1045 // Check for the terminated condition
1046 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1048 // Get audio and append to the fifo
1049 if ( !terminated && audio_st )
1051 samples = mlt_sample_calculator( fps, frequency, count ++ );
1052 mlt_frame_get_audio( frame, (void**) &pcm, &aud_fmt, &frequency, &channels, &samples );
1054 // Create the fifo if we don't have one
1057 fifo = sample_fifo_init( frequency, channels );
1058 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1061 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1062 memset( pcm, 0, samples * channels * 2 );
1064 // Append the samples
1065 sample_fifo_append( fifo, pcm, samples * channels );
1066 total_time += ( samples * 1000000 ) / frequency;
1070 if ( !terminated && video_st )
1071 mlt_deque_push_back( queue, frame );
1073 mlt_frame_close( frame );
1076 // While we have stuff to process, process...
1079 // Write interleaved audio and video frames
1080 if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
1082 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1084 AVCodecContext *c = audio_st->codec;
1086 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) ), AUDIO_ENCODE_BUFFER_SIZE );
1089 sample_fifo_fetch( fifo, buffer, n );
1091 memset( buffer, 0, AUDIO_ENCODE_BUFFER_SIZE );
1093 av_init_packet( &pkt );
1094 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
1096 // Write the compressed frame in the media file
1097 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1099 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
1100 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "audio pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1102 pkt.flags |= PKT_FLAG_KEY;
1103 pkt.stream_index= audio_st->index;
1104 pkt.data= audio_outbuf;
1107 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1108 mlt_log_error( MLT_CONSUMER_SERVICE( this ), "error writing audio frame\n" );
1110 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), " frame_size %d\n", c->frame_size );
1111 if ( audio_codec_id == CODEC_ID_VORBIS )
1112 audio_pts = (double)c->coded_frame->pts * av_q2d( audio_st->time_base );
1114 audio_pts = (double)audio_st->pts.val * av_q2d( audio_st->time_base );
1121 else if ( video_st )
1123 if ( mlt_deque_count( queue ) )
1128 frame = mlt_deque_pop_front( queue );
1129 frame_properties = MLT_FRAME_PROPERTIES( frame );
1131 c = video_st->codec;
1133 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1140 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1142 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1146 // Convert the mlt frame to an AVPicture
1147 for ( i = 0; i < height; i ++ )
1149 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1158 // Do the colour space conversion
1160 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1161 width, height, video_st->codec->pix_fmt, SWS_FAST_BILINEAR, NULL, NULL, NULL);
1162 sws_scale( context, input->data, input->linesize, 0, height,
1163 output->data, output->linesize);
1164 sws_freeContext( context );
1166 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1169 // Apply the alpha if applicable
1170 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1172 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1175 for ( i = 0; i < height; i ++ )
1177 n = ( width + 7 ) / 8;
1178 p = output->data[ 0 ] + i * output->linesize[ 0 ];
1186 case 0: do { *p = *alpha++; p += 4;
1187 case 7: *p = *alpha++; p += 4;
1188 case 6: *p = *alpha++; p += 4;
1189 case 5: *p = *alpha++; p += 4;
1190 case 4: *p = *alpha++; p += 4;
1191 case 3: *p = *alpha++; p += 4;
1192 case 2: *p = *alpha++; p += 4;
1193 case 1: *p = *alpha++; p += 4;
1201 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1203 // raw video case. The API will change slightly in the near future for that
1205 av_init_packet(&pkt);
1207 pkt.flags |= PKT_FLAG_KEY;
1208 pkt.stream_index= video_st->index;
1209 pkt.data= (uint8_t *)output;
1210 pkt.size= sizeof(AVPicture);
1212 ret = av_write_frame(oc, &pkt);
1213 video_pts += c->frame_size;
1218 output->quality = video_st->quality;
1220 // Set frame interlace hints
1221 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1222 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1223 output->pts = frame_count;
1226 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1228 // If zero size, it means the image was buffered
1232 av_init_packet( &pkt );
1234 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1235 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1236 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "video pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1237 if( c->coded_frame && c->coded_frame->key_frame )
1238 pkt.flags |= PKT_FLAG_KEY;
1239 pkt.stream_index= video_st->index;
1240 pkt.data= video_outbuf;
1243 // write the compressed frame in the media file
1244 ret = av_interleaved_write_frame(oc, &pkt);
1245 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), " frame_size %d\n", c->frame_size );
1246 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1248 // Dual pass logging
1249 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1250 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1252 else if ( out_size < 0 )
1254 mlt_log_warning( MLT_CONSUMER_SERVICE( this ), "error with video encode %d\n", frame_count );
1258 mlt_frame_close( frame );
1266 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "audio pts %lld (%f) ", audio_st->pts.val, audio_pts );
1268 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "video pts %lld (%f) ", video_st->pts.val, video_pts );
1269 mlt_log_debug( MLT_CONSUMER_SERVICE( this ), "\n" );
1272 if ( real_time_output == 1 && frames % 2 == 0 )
1274 long passed = time_difference( &ante );
1277 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1280 if ( passed < total_time )
1282 long total = ( total_time - passed );
1283 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1284 nanosleep( &t, NULL );
1290 if ( ! real_time_output )
1293 if ( audio_st && audio_st->codec->frame_size > 1 ) for (;;)
1295 AVCodecContext *c = audio_st->codec;
1297 av_init_packet( &pkt );
1300 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1301 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1303 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
1304 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
1306 if ( pkt.size <= 0 )
1307 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1308 if ( pkt.size <= 0 )
1311 // Write the compressed frame in the media file
1312 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1313 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
1314 pkt.flags |= PKT_FLAG_KEY;
1315 pkt.stream_index = audio_st->index;
1316 pkt.data = audio_outbuf;
1317 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1319 fprintf( stderr, "%s: Error while writing flushed audio frame\n", __FILE__ );
1325 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1327 AVCodecContext *c = video_st->codec;
1329 av_init_packet( &pkt );
1332 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1333 if ( pkt.size <= 0 )
1336 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1337 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1338 if( c->coded_frame && c->coded_frame->key_frame )
1339 pkt.flags |= PKT_FLAG_KEY;
1340 pkt.stream_index = video_st->index;
1341 pkt.data = video_outbuf;
1343 // write the compressed frame in the media file
1344 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1346 mlt_log_error( MLT_CONSUMER_SERVICE(this), "error while writing flushing video frame\n" );
1353 // XXX ugly hack to prevent x264 from crashing on multi-threaded encoding
1354 int pass = mlt_properties_get_int( properties, "pass" );
1355 int thread_count = mlt_properties_get_int( properties, "threads" );
1356 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1357 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1358 int multithreaded_x264 = ( video_codec_id == CODEC_ID_H264 && thread_count > 1 );
1361 if ( video_st && !multithreaded_x264 )
1362 close_video(oc, video_st);
1364 close_audio(oc, audio_st);
1366 // Write the trailer, if any
1367 av_write_trailer(oc);
1370 for(i = 0; i < oc->nb_streams; i++)
1371 av_freep(&oc->streams[i]);
1373 // Close the output file
1374 if (!(fmt->flags & AVFMT_NOFILE))
1375 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1378 url_fclose(&oc->pb);
1381 // Clean up input and output frames
1383 av_free( output->data[0] );
1385 av_free( input->data[0] );
1387 av_free( video_outbuf );
1393 // Just in case we terminated on pause
1394 mlt_properties_set_int( properties, "running", 0 );
1396 mlt_consumer_stopped( this );
1400 // Remove the dual pass log file
1401 if ( mlt_properties_get( properties, "_logfilename" ) )
1402 remove( mlt_properties_get( properties, "_logfilename" ) );
1404 // Remove the x264 dual pass logs
1405 char *cwd = getcwd( NULL, 0 );
1406 const char *file = "x264_2pass.log";
1407 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1408 sprintf( full, "%s/%s", cwd, file );
1411 file = "x264_2pass.log.temp";
1412 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1413 sprintf( full, "%s/%s", cwd, file );
1416 file = "x264_2pass.log.mbtree";
1417 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1418 sprintf( full, "%s/%s", cwd, file );
1422 remove( "x264_2pass.log.temp" );
1428 /** Close the consumer.
1431 static void consumer_close( mlt_consumer this )
1433 // Stop the consumer
1434 mlt_consumer_stop( this );
1437 mlt_consumer_close( this );