2 * consumer_avformat.c -- an encoder based on avformat
3 * Copyright (C) 2003-2012 Ushodaya Enterprises Limited
4 * Author: Charles Yates <charles.yates@pandora.be>
5 * Author: Dan Dennedy <dan@dennedy.org>
6 * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include <framework/mlt_consumer.h>
25 #include <framework/mlt_frame.h>
26 #include <framework/mlt_profile.h>
27 #include <framework/mlt_log.h>
28 #include <framework/mlt_events.h>
30 // System header files
39 // avformat header files
40 #include <libavformat/avformat.h>
41 #include <libavformat/avio.h>
43 #include <libswscale/swscale.h>
45 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
46 #include <libavutil/pixdesc.h>
48 #include <libavutil/mathematics.h>
50 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
51 # include <libavutil/samplefmt.h>
53 # define AV_SAMPLE_FMT_NONE SAMPLE_FMT_NONE
54 # define AV_SAMPLE_FMT_S16 SAMPLE_FMT_S16
55 # define AV_SAMPLE_FMT_S32 SAMPLE_FMT_S32
56 # define AV_SAMPLE_FMT_FLT SAMPLE_FMT_FLT
59 #if LIBAVUTIL_VERSION_INT < (50<<16)
60 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
61 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
64 #if LIBAVCODEC_VERSION_MAJOR >= 53
65 #include <libavutil/opt.h>
66 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
67 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
68 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
70 #include <libavcodec/opt.h>
73 #define MAX_AUDIO_STREAMS (8)
74 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
75 #define AUDIO_BUFFER_SIZE (1024 * 42)
76 #define VIDEO_BUFFER_SIZE (2048 * 1024)
79 // This structure should be extended and made globally available in mlt
91 *sample_fifo, sample_fifo_s;
93 sample_fifo sample_fifo_init( int frequency, int channels )
95 sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
96 fifo->frequency = frequency;
97 fifo->channels = channels;
101 // count is the number of samples multiplied by the number of bytes per sample
102 void sample_fifo_append( sample_fifo fifo, uint8_t *samples, int count )
104 if ( ( fifo->size - fifo->used ) < count )
106 fifo->size += count * 5;
107 fifo->buffer = realloc( fifo->buffer, fifo->size );
110 memcpy( &fifo->buffer[ fifo->used ], samples, count );
114 int sample_fifo_used( sample_fifo fifo )
119 int sample_fifo_fetch( sample_fifo fifo, uint8_t *samples, int count )
121 if ( count > fifo->used )
124 memcpy( samples, fifo->buffer, count );
126 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used );
128 fifo->time += ( double )count / fifo->channels / fifo->frequency;
133 void sample_fifo_close( sample_fifo fifo )
135 free( fifo->buffer );
139 // Forward references.
140 static int consumer_start( mlt_consumer consumer );
141 static int consumer_stop( mlt_consumer consumer );
142 static int consumer_is_stopped( mlt_consumer consumer );
143 static void *consumer_thread( void *arg );
144 static void consumer_close( mlt_consumer consumer );
146 /** Initialise the consumer.
149 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
151 // Allocate the consumer
152 mlt_consumer consumer = mlt_consumer_new( profile );
154 // If memory allocated and initialises without error
155 if ( consumer != NULL )
157 // Get properties from the consumer
158 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
160 // Assign close callback
161 consumer->close = consumer_close;
163 // Interpret the argument
165 mlt_properties_set( properties, "target", arg );
167 // sample and frame queue
168 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
170 // Audio options not fully handled by AVOptions
171 #define QSCALE_NONE (-99999)
172 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
174 // Video options not fully handled by AVOptions
175 mlt_properties_set_int( properties, "dc", 8 );
177 // Muxer options not fully handled by AVOptions
178 mlt_properties_set_double( properties, "muxdelay", 0.7 );
179 mlt_properties_set_double( properties, "muxpreload", 0.5 );
181 // Ensure termination at end of the stream
182 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
184 // Default to separate processing threads for producer and consumer with no frame dropping!
185 mlt_properties_set_int( properties, "real_time", -1 );
186 mlt_properties_set_int( properties, "prefill", 1 );
188 // Set up start/stop/terminated callbacks
189 consumer->start = consumer_start;
190 consumer->stop = consumer_stop;
191 consumer->is_stopped = consumer_is_stopped;
193 mlt_events_register( properties, "consumer-fatal-error", NULL );
200 /** Start the consumer.
203 static int consumer_start( mlt_consumer consumer )
205 // Get the properties
206 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
209 // Report information about available muxers and codecs as YAML Tiny
210 char *s = mlt_properties_get( properties, "f" );
211 if ( s && strcmp( s, "list" ) == 0 )
213 mlt_properties doc = mlt_properties_new();
214 mlt_properties formats = mlt_properties_new();
216 AVOutputFormat *format = NULL;
218 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
219 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
220 while ( ( format = av_oformat_next( format ) ) )
222 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
223 mlt_properties_set( formats, key, format->name );
225 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
226 mlt_properties_close( doc );
229 s = mlt_properties_get( properties, "acodec" );
230 if ( s && strcmp( s, "list" ) == 0 )
232 mlt_properties doc = mlt_properties_new();
233 mlt_properties codecs = mlt_properties_new();
235 AVCodec *codec = NULL;
237 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
238 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
239 while ( ( codec = av_codec_next( codec ) ) )
240 #if (defined(FFUDIV) && LIBAVCODEC_VERSION_INT >= ((54<<16)+(56<<8)+100)) || (LIBAVCODEC_VERSION_INT >= ((54<<16)+(27<<8)+0))
241 if ( codec->encode2 && codec->type == CODEC_TYPE_AUDIO )
242 #elif LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
243 if ( ( codec->encode || codec->encode2 ) && codec->type == CODEC_TYPE_AUDIO )
245 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
248 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
249 mlt_properties_set( codecs, key, codec->name );
251 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
252 mlt_properties_close( doc );
255 s = mlt_properties_get( properties, "vcodec" );
256 if ( s && strcmp( s, "list" ) == 0 )
258 mlt_properties doc = mlt_properties_new();
259 mlt_properties codecs = mlt_properties_new();
261 AVCodec *codec = NULL;
263 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
264 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
265 while ( ( codec = av_codec_next( codec ) ) )
266 #if (defined(FFUDIV) && LIBAVCODEC_VERSION_INT >= ((54<<16)+(56<<8)+100)) || (LIBAVCODEC_VERSION_INT >= ((54<<16)+(27<<8)+0))
267 if ( codec->encode2 && codec->type == CODEC_TYPE_VIDEO )
268 #elif LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
269 if ( (codec->encode || codec->encode2) && codec->type == CODEC_TYPE_VIDEO )
271 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
274 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
275 mlt_properties_set( codecs, key, codec->name );
277 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
278 mlt_properties_close( doc );
282 // Check that we're not already running
283 if ( !error && !mlt_properties_get_int( properties, "running" ) )
286 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
288 // Get the width and height
289 int width = mlt_properties_get_int( properties, "width" );
290 int height = mlt_properties_get_int( properties, "height" );
292 // Obtain the size property
293 char *size = mlt_properties_get( properties, "s" );
299 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
306 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Invalid size property %s - ignoring.\n", size );
310 // Now ensure we honour the multiple of two requested by libavformat
311 width = ( width / 2 ) * 2;
312 height = ( height / 2 ) * 2;
313 mlt_properties_set_int( properties, "width", width );
314 mlt_properties_set_int( properties, "height", height );
316 // We need to set these on the profile as well because the s property is
317 // an alias to mlt properties that correspond to profile settings.
318 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
321 profile->width = width;
322 profile->height = height;
325 if ( mlt_properties_get( properties, "aspect" ) )
327 // "-aspect" on ffmpeg command line is display aspect ratio
328 double ar = mlt_properties_get_double( properties, "aspect" );
329 AVRational rational = av_d2q( ar, 255 );
331 // Update the profile and properties as well since this is an alias
332 // for mlt properties that correspond to profile settings
333 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
334 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
337 profile->display_aspect_num = rational.num;
338 profile->display_aspect_den = rational.den;
339 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
342 // Now compute the sample aspect ratio
343 rational = av_d2q( ar * height / width, 255 );
345 // Update the profile and properties as well since this is an alias
346 // for mlt properties that correspond to profile settings
347 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
348 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
351 profile->sample_aspect_num = rational.num;
352 profile->sample_aspect_den = rational.den;
353 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
357 // Handle the ffmpeg command line "-r" property for frame rate
358 if ( mlt_properties_get( properties, "r" ) )
360 double frame_rate = mlt_properties_get_double( properties, "r" );
361 AVRational rational = av_d2q( frame_rate, 255 );
362 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
363 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
366 profile->frame_rate_num = rational.num;
367 profile->frame_rate_den = rational.den;
368 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
372 // Apply AVOptions that are synonyms for standard mlt_consumer options
373 if ( mlt_properties_get( properties, "ac" ) )
374 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
375 if ( mlt_properties_get( properties, "ar" ) )
376 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
378 // Assign the thread to properties
379 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
382 pthread_create( thread, NULL, consumer_thread, consumer );
384 // Set the running state
385 mlt_properties_set_int( properties, "running", 1 );
390 /** Stop the consumer.
393 static int consumer_stop( mlt_consumer consumer )
395 // Get the properties
396 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
397 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
399 // Check that we're running
403 mlt_properties_set_int( properties, "running", 0 );
405 // Wait for termination
406 pthread_join( *thread, NULL );
408 mlt_properties_set_data( properties, "thread", NULL, 0, NULL, NULL );
414 /** Determine if the consumer is stopped.
417 static int consumer_is_stopped( mlt_consumer consumer )
419 // Get the properties
420 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
421 return !mlt_properties_get_int( properties, "running" );
424 /** Process properties as AVOptions and apply to AV context obj
427 static void apply_properties( void *obj, mlt_properties properties, int flags )
430 int count = mlt_properties_count( properties );
431 #if LIBAVUTIL_VERSION_INT < ((51<<16)+(12<<8)+0)
435 for ( i = 0; i < count; i++ )
437 const char *opt_name = mlt_properties_get_name( properties, i );
438 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
439 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
441 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
444 // If option not found, see if it was prefixed with a or v (-vb)
446 ( opt_name[0] == 'v' && ( flags & AV_OPT_FLAG_VIDEO_PARAM ) ) ||
447 ( opt_name[0] == 'a' && ( flags & AV_OPT_FLAG_AUDIO_PARAM ) ) ) )
448 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
449 opt = av_opt_find( obj, ++opt_name, NULL, flags, flags );
451 opt = av_find_opt( obj, ++opt_name, NULL, flags, flags );
453 // Apply option if found
455 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
456 av_opt_set( obj, opt_name, mlt_properties_get_value( properties, i), 0 );
457 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
458 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
459 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
460 av_set_string2( obj, opt_name, mlt_properties_get_value( properties, i), alloc );
462 av_set_string( obj, opt_name, mlt_properties_get_value( properties, i) );
467 static int get_mlt_audio_format( int av_sample_fmt )
469 switch ( av_sample_fmt )
471 case AV_SAMPLE_FMT_S32:
472 return mlt_audio_s32le;
473 case AV_SAMPLE_FMT_FLT:
474 return mlt_audio_f32le;
475 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
476 case AV_SAMPLE_FMT_S32P:
477 return mlt_audio_s32le;
478 case AV_SAMPLE_FMT_FLTP:
479 return mlt_audio_f32le;
482 return mlt_audio_s16;
486 static int pick_sample_fmt( mlt_properties properties, AVCodec *codec )
488 int sample_fmt = AV_SAMPLE_FMT_S16;
489 const char *format = mlt_properties_get( properties, "mlt_audio_format" );
490 const int *p = codec->sample_fmts;
492 // get default av_sample_fmt from mlt_audio_format
495 if ( !strcmp( format, "s32le" ) )
496 sample_fmt = AV_SAMPLE_FMT_S32;
497 else if ( !strcmp( format, "f32le" ) )
498 sample_fmt = AV_SAMPLE_FMT_FLT;
499 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
500 else if ( !strcmp( format, "s32" ) )
501 sample_fmt = AV_SAMPLE_FMT_S32P;
502 else if ( !strcmp( format, "float" ) )
503 sample_fmt = AV_SAMPLE_FMT_FLTP;
506 // check if codec supports our mlt_audio_format
507 for ( ; *p != -1; p++ )
509 if ( *p == sample_fmt )
512 // no match - pick first one we support
513 for ( p = codec->sample_fmts; *p != -1; p++ )
517 case AV_SAMPLE_FMT_S16:
518 case AV_SAMPLE_FMT_S32:
519 case AV_SAMPLE_FMT_FLT:
520 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
521 case AV_SAMPLE_FMT_S16P:
522 case AV_SAMPLE_FMT_S32P:
523 case AV_SAMPLE_FMT_FLTP:
530 mlt_log_error( properties, "audio codec sample_fmt not compatible" );
532 return AV_SAMPLE_FMT_NONE;
535 static uint8_t* interleaved_to_planar( int samples, int channels, uint8_t* audio, int bytes_per_sample )
537 int size = samples * channels * bytes_per_sample;
538 uint8_t *buffer = mlt_pool_alloc( AUDIO_ENCODE_BUFFER_SIZE );
542 memset( buffer, 0, AUDIO_ENCODE_BUFFER_SIZE );
543 for ( c = 0; c < channels; c++ )
545 uint8_t *q = audio + c * bytes_per_sample;
549 memcpy( p, q, bytes_per_sample );
550 p += bytes_per_sample;
551 q += channels * bytes_per_sample;
557 /** Add an audio output stream
560 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec, int channels )
562 // Get the properties
563 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
565 // Create a new stream
566 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
567 AVStream *st = avformat_new_stream( oc, codec );
569 AVStream *st = av_new_stream( oc, oc->nb_streams );
572 // If created, then initialise from properties
575 AVCodecContext *c = st->codec;
577 // Establish defaults from AVOptions
578 #if LIBAVCODEC_VERSION_MAJOR >= 53
579 avcodec_get_context_defaults3( c, codec );
581 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
584 c->codec_id = codec->id;
585 c->codec_type = CODEC_TYPE_AUDIO;
586 c->sample_fmt = pick_sample_fmt( properties, codec );
588 #if 0 // disabled until some audio codecs are multi-threaded
589 // Setup multi-threading
590 int thread_count = mlt_properties_get_int( properties, "threads" );
591 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
592 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
593 if ( thread_count > 1 )
594 c->thread_count = thread_count;
597 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
598 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
600 // Allow the user to override the audio fourcc
601 if ( mlt_properties_get( properties, "atag" ) )
604 char *arg = mlt_properties_get( properties, "atag" );
605 int tag = strtol( arg, &tail, 0);
607 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
611 // Process properties as AVOptions
612 char *apre = mlt_properties_get( properties, "apre" );
615 mlt_properties p = mlt_properties_load( apre );
616 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
617 mlt_properties_close( p );
619 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
621 int audio_qscale = mlt_properties_get_int( properties, "aq" );
622 if ( audio_qscale > QSCALE_NONE )
624 c->flags |= CODEC_FLAG_QSCALE;
625 c->global_quality = FF_QP2LAMBDA * audio_qscale;
626 #if LIBAVFORMAT_VERSION_MAJOR < 53
627 st->quality = c->global_quality;
631 // Set parameters controlled by MLT
632 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
633 c->time_base = ( AVRational ){ 1, c->sample_rate };
634 c->channels = channels;
636 if ( mlt_properties_get( properties, "alang" ) != NULL )
637 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
638 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
639 av_dict_set( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
641 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
645 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
650 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
656 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
658 // We will return the audio input size from here
659 int audio_input_frame_size = 0;
662 AVCodecContext *c = st->codec;
667 codec = avcodec_find_encoder_by_name( codec_name );
669 codec = avcodec_find_encoder( c->codec_id );
671 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
672 // Process properties as AVOptions on the AVCodec
673 if ( codec && codec->priv_class )
675 char *apre = mlt_properties_get( properties, "apre" );
676 if ( !c->priv_data && codec->priv_data_size )
678 c->priv_data = av_mallocz( codec->priv_data_size );
679 *(const AVClass **) c->priv_data = codec->priv_class;
680 // av_opt_set_defaults( c );
684 mlt_properties p = mlt_properties_load( apre );
685 apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
686 mlt_properties_close( p );
688 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
692 // Continue if codec found and we can open it
693 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
694 if ( codec && avcodec_open2( c, codec, NULL ) >= 0 )
696 if ( codec && avcodec_open( c, codec ) >= 0 )
699 // ugly hack for PCM codecs (will be removed ASAP with new PCM
700 // support to compute the input frame size in samples
701 if ( c->frame_size <= 1 )
703 audio_input_frame_size = audio_outbuf_size / c->channels;
704 switch(st->codec->codec_id)
706 case CODEC_ID_PCM_S16LE:
707 case CODEC_ID_PCM_S16BE:
708 case CODEC_ID_PCM_U16LE:
709 case CODEC_ID_PCM_U16BE:
710 audio_input_frame_size >>= 1;
718 audio_input_frame_size = c->frame_size;
721 // Some formats want stream headers to be seperate (hmm)
722 if ( !strcmp( oc->oformat->name, "mp4" ) ||
723 !strcmp( oc->oformat->name, "mov" ) ||
724 !strcmp( oc->oformat->name, "3gp" ) )
725 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
729 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
730 audio_input_frame_size = 0;
733 return audio_input_frame_size;
736 static void close_audio( AVFormatContext *oc, AVStream *st )
738 if ( st && st->codec )
739 avcodec_close( st->codec );
742 /** Add a video output stream
745 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
747 // Get the properties
748 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
750 // Create a new stream
751 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
752 AVStream *st = avformat_new_stream( oc, codec );
754 AVStream *st = av_new_stream( oc, oc->nb_streams );
759 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
760 AVCodecContext *c = st->codec;
762 // Establish defaults from AVOptions
763 #if LIBAVCODEC_VERSION_MAJOR >= 53
764 avcodec_get_context_defaults3( c, codec );
766 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
769 c->codec_id = codec->id;
770 c->codec_type = CODEC_TYPE_VIDEO;
772 // Setup multi-threading
773 int thread_count = mlt_properties_get_int( properties, "threads" );
774 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
775 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
776 if ( thread_count > 1 )
777 #if LIBAVCODEC_VERSION_MAJOR >= 53
778 c->thread_count = thread_count;
780 avcodec_thread_init( c, thread_count );
783 // Process properties as AVOptions
784 char *vpre = mlt_properties_get( properties, "vpre" );
787 mlt_properties p = mlt_properties_load( vpre );
789 if ( mlt_properties_count( p ) < 1 )
791 AVCodec *codec = avcodec_find_encoder( c->codec_id );
794 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
795 strcpy( path, AVDATADIR );
796 strcat( path, codec->name );
798 strcat( path, vpre );
799 strcat( path, ".ffpreset" );
801 mlt_properties_close( p );
802 p = mlt_properties_load( path );
803 if ( mlt_properties_count( p ) > 0 )
804 mlt_properties_debug( p, path, stderr );
810 mlt_properties_debug( p, vpre, stderr );
813 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
814 mlt_properties_close( p );
816 int colorspace = mlt_properties_get_int( properties, "colorspace" );
817 mlt_properties_set( properties, "colorspace", NULL );
818 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
819 mlt_properties_set_int( properties, "colorspace", colorspace );
821 // Set options controlled by MLT
822 c->width = mlt_properties_get_int( properties, "width" );
823 c->height = mlt_properties_get_int( properties, "height" );
824 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
825 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
826 if ( st->time_base.den == 0 )
827 st->time_base = c->time_base;
828 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
829 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
831 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
834 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
835 switch ( colorspace )
838 c->colorspace = AVCOL_SPC_SMPTE170M;
841 c->colorspace = AVCOL_SPC_SMPTE240M;
844 c->colorspace = AVCOL_SPC_BT470BG;
847 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
850 c->colorspace = AVCOL_SPC_BT709;
855 if ( mlt_properties_get( properties, "aspect" ) )
857 // "-aspect" on ffmpeg command line is display aspect ratio
858 double ar = mlt_properties_get_double( properties, "aspect" );
859 c->sample_aspect_ratio = av_d2q( ar * c->height / c->width, 255 );
863 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
864 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
866 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
867 st->sample_aspect_ratio = c->sample_aspect_ratio;
870 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
872 c->flags |= CODEC_FLAG_QSCALE;
873 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
874 #if LIBAVFORMAT_VERSION_MAJOR < 53
875 st->quality = c->global_quality;
879 // Allow the user to override the video fourcc
880 if ( mlt_properties_get( properties, "vtag" ) )
883 const char *arg = mlt_properties_get( properties, "vtag" );
884 int tag = strtol( arg, &tail, 0);
886 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
890 // Some formats want stream headers to be seperate
891 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
892 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
894 // Translate these standard mlt consumer properties to ffmpeg
895 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
896 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
898 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
899 c->flags |= CODEC_FLAG_INTERLACED_DCT;
900 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
901 c->flags |= CODEC_FLAG_INTERLACED_ME;
904 // parse the ratecontrol override string
906 char *rc_override = mlt_properties_get( properties, "rc_override" );
907 for ( i = 0; rc_override; i++ )
910 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
912 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
913 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
914 c->rc_override[i].start_frame = start;
915 c->rc_override[i].end_frame = end;
918 c->rc_override[i].qscale = q;
919 c->rc_override[i].quality_factor = 1.0;
923 c->rc_override[i].qscale = 0;
924 c->rc_override[i].quality_factor = -q / 100.0;
926 rc_override = strchr( rc_override, '/' );
930 c->rc_override_count = i;
931 if ( !c->rc_initial_buffer_occupancy )
932 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
933 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
936 i = mlt_properties_get_int( properties, "pass" );
938 c->flags |= CODEC_FLAG_PASS1;
940 c->flags |= CODEC_FLAG_PASS2;
941 if ( codec->id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
943 char logfilename[1024];
948 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
949 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
950 if ( c->flags & CODEC_FLAG_PASS1 )
952 f = fopen( logfilename, "w" );
954 perror( logfilename );
956 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
960 /* read the log file */
961 f = fopen( logfilename, "r" );
968 mlt_properties_set( properties, "_logfilename", logfilename );
969 fseek( f, 0, SEEK_END );
971 fseek( f, 0, SEEK_SET );
972 logbuffer = av_malloc( size + 1 );
974 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
979 size = fread( logbuffer, 1, size, f );
980 logbuffer[size] = '\0';
981 c->stats_in = logbuffer;
991 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
997 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
1000 AVFrame *picture = avcodec_alloc_frame();
1002 // Determine size of the
1003 int size = avpicture_get_size(pix_fmt, width, height);
1005 // Allocate the picture buf
1006 uint8_t *picture_buf = av_malloc(size);
1008 // If we have both, then fill the image
1009 if ( picture != NULL && picture_buf != NULL )
1011 // Fill the frame with the allocated buffer
1012 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
1016 // Something failed - clean up what we can
1018 av_free( picture_buf );
1025 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
1028 AVCodecContext *video_enc = st->codec;
1030 // find the video encoder
1033 codec = avcodec_find_encoder_by_name( codec_name );
1035 codec = avcodec_find_encoder( video_enc->codec_id );
1037 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1038 // Process properties as AVOptions on the AVCodec
1039 if ( codec && codec->priv_class )
1041 char *vpre = mlt_properties_get( properties, "vpre" );
1042 if ( !video_enc->priv_data && codec->priv_data_size )
1044 video_enc->priv_data = av_mallocz( codec->priv_data_size );
1045 *(const AVClass **) video_enc->priv_data = codec->priv_class;
1046 // av_opt_set_defaults( video_enc );
1050 mlt_properties p = mlt_properties_load( vpre );
1051 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1052 mlt_properties_close( p );
1054 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1058 if( codec && codec->pix_fmts )
1060 const enum PixelFormat *p = codec->pix_fmts;
1061 for( ; *p!=-1; p++ )
1063 if( *p == video_enc->pix_fmt )
1067 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1070 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1071 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1073 int result = codec && avcodec_open( video_enc, codec ) >= 0;
1079 void close_video(AVFormatContext *oc, AVStream *st)
1081 if ( st && st->codec )
1083 av_freep( &st->codec->stats_in );
1084 avcodec_close(st->codec);
1088 static inline long time_difference( struct timeval *time1 )
1090 struct timeval time2;
1091 gettimeofday( &time2, NULL );
1092 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1095 static int mlt_write(void *h, uint8_t *buf, int size)
1097 mlt_properties properties = (mlt_properties) h;
1098 mlt_events_fire( properties, "avformat-write", buf, size, NULL );
1102 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1104 listener( owner, service, (uint8_t*) args[0], (int) args[1] );
1107 /** The main thread - the argument is simply the consumer.
1110 static void *consumer_thread( void *arg )
1112 // Map the argument to the object
1113 mlt_consumer consumer = arg;
1115 // Get the properties
1116 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1118 // Get the terminate on pause property
1119 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1122 // Determine if feed is slow (for realtime stuff)
1123 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1126 struct timeval ante;
1128 // Get the frame rate
1129 double fps = mlt_properties_get_double( properties, "fps" );
1131 // Get width and height
1132 int width = mlt_properties_get_int( properties, "width" );
1133 int height = mlt_properties_get_int( properties, "height" );
1134 int img_width = width;
1135 int img_height = height;
1137 // Get default audio properties
1138 int channels = mlt_properties_get_int( properties, "channels" );
1139 int total_channels = channels;
1140 int frequency = mlt_properties_get_int( properties, "frequency" );
1144 // AVFormat audio buffer and frame size
1145 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1146 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1147 int audio_input_frame_size = 0;
1149 // AVFormat video buffer and frame count
1150 int frame_count = 0;
1151 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1152 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1154 // Used for the frame properties
1155 mlt_frame frame = NULL;
1156 mlt_properties frame_properties = NULL;
1159 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1160 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1162 // Need two av pictures for converting
1163 AVFrame *output = NULL;
1164 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
1166 // For receiving images from an mlt_frame
1168 mlt_image_format img_fmt = mlt_image_yuv422;
1170 // For receiving audio samples back from the fifo
1171 uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1172 uint8_t *audio_buf_2 = NULL;
1175 // Allocate the context
1176 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
1177 AVFormatContext *oc = avformat_alloc_context( );
1179 AVFormatContext *oc = av_alloc_format_context( );
1183 AVStream *video_st = NULL;
1184 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1187 double audio_pts = 0;
1188 double video_pts = 0;
1190 // Frames dispatched
1191 long int frames = 0;
1192 long int total_time = 0;
1194 // Determine the format
1195 AVOutputFormat *fmt = NULL;
1196 const char *filename = mlt_properties_get( properties, "target" );
1197 char *format = mlt_properties_get( properties, "f" );
1198 char *vcodec = mlt_properties_get( properties, "vcodec" );
1199 char *acodec = mlt_properties_get( properties, "acodec" );
1200 AVCodec *audio_codec = NULL;
1201 AVCodec *video_codec = NULL;
1203 // Used to store and override codec ids
1209 mlt_properties frame_meta_properties = mlt_properties_new();
1211 // Initialize audio_st
1212 int i = MAX_AUDIO_STREAMS;
1216 // Check for user selected format first
1217 if ( format != NULL )
1218 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1219 fmt = guess_format( format, NULL, NULL );
1221 fmt = av_guess_format( format, NULL, NULL );
1224 // Otherwise check on the filename
1225 if ( fmt == NULL && filename != NULL )
1226 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1227 fmt = guess_format( NULL, filename, NULL );
1229 fmt = av_guess_format( NULL, filename, NULL );
1232 // Otherwise default to mpeg
1234 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1235 fmt = guess_format( "mpeg", NULL, NULL );
1237 fmt = av_guess_format( "mpeg", NULL, NULL );
1240 // We need a filename - default to stdout?
1241 if ( filename == NULL || !strcmp( filename, "" ) )
1244 // Get the codec ids selected
1245 audio_codec_id = fmt->audio_codec;
1246 video_codec_id = fmt->video_codec;
1248 // Check for audio codec overides
1249 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1250 audio_codec_id = CODEC_ID_NONE;
1253 audio_codec = avcodec_find_encoder_by_name( acodec );
1256 audio_codec_id = audio_codec->id;
1257 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1259 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1260 acodec = mlt_properties_get( properties, "_acodec" );
1261 audio_codec = avcodec_find_encoder_by_name( acodec );
1263 else if ( !strcmp( acodec, "aac" ) )
1265 mlt_properties_set( properties, "astrict", "experimental" );
1270 audio_codec_id = CODEC_ID_NONE;
1271 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1276 audio_codec = avcodec_find_encoder( audio_codec_id );
1279 // Check for video codec overides
1280 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1281 video_codec_id = CODEC_ID_NONE;
1284 video_codec = avcodec_find_encoder_by_name( vcodec );
1287 video_codec_id = video_codec->id;
1291 video_codec_id = CODEC_ID_NONE;
1292 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1297 video_codec = avcodec_find_encoder( video_codec_id );
1301 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1302 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1304 char *name = mlt_properties_get_name( properties, i );
1305 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1307 char *key = strdup( name + 10 );
1308 char *markup = strrchr( key, '.' );
1309 if ( markup && !strcmp( markup, ".markup") )
1312 if ( !strstr( key, ".stream." ) )
1313 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1314 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1315 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1317 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1320 av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1330 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1331 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1333 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1334 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1336 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1337 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1339 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1340 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1342 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1343 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1345 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1346 if (metavalue != 0) oc->year = metavalue;
1348 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1349 if (metavalue != 0) oc->track = metavalue;
1353 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1355 // Get a frame now, so we can set some AVOptions from properties.
1356 frame = mlt_consumer_rt_frame( consumer );
1358 // Set the timecode from the MLT metadata if available.
1361 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1362 if ( timecode && strcmp( timecode, "" ) )
1364 mlt_properties_set( properties, "timecode", timecode );
1365 if ( strchr( timecode, ';' ) )
1366 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1370 // Add audio and video streams
1371 if ( video_codec_id != CODEC_ID_NONE )
1372 video_st = add_video_stream( consumer, oc, video_codec );
1373 if ( audio_codec_id != CODEC_ID_NONE )
1379 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1381 sprintf( key, "channels.%d", i );
1382 int j = mlt_properties_get_int( properties, key );
1386 total_channels += j;
1387 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1393 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1394 total_channels = channels;
1397 mlt_properties_set_int( properties, "channels", total_channels );
1399 // Audio format is determined when adding the audio stream
1400 mlt_audio_format aud_fmt = mlt_audio_none;
1402 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1403 int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1404 sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1406 // Set the parameters (even though we have none...)
1407 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1408 if ( av_set_parameters(oc, NULL) >= 0 )
1411 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1412 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1413 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1415 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1417 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1419 // Process properties as AVOptions
1420 char *fpre = mlt_properties_get( properties, "fpre" );
1423 mlt_properties p = mlt_properties_load( fpre );
1424 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1425 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1426 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1427 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1429 mlt_properties_close( p );
1431 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1432 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1433 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1434 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1437 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1439 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1441 audio_input_frame_size = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1442 acodec? acodec : NULL );
1443 if ( !audio_input_frame_size )
1445 // Remove the audio stream from the output context
1447 for ( j = 0; j < oc->nb_streams; j++ )
1449 if ( oc->streams[j] == audio_st[i] )
1450 av_freep( &oc->streams[j] );
1457 // Setup custom I/O if redirecting
1458 if ( mlt_properties_get_int( properties, "redirect" ) )
1460 int buffer_size = 32768;
1461 unsigned char *buffer = av_malloc( buffer_size );
1462 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1463 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1465 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1470 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1471 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1473 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1474 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1475 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1480 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1483 // Open the output file, if needed
1484 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1486 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1487 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1489 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1492 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1493 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1494 goto on_fatal_error;
1498 // Write the stream header.
1499 if ( mlt_properties_get_int( properties, "running" ) )
1500 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1501 avformat_write_header( oc, NULL );
1503 av_write_header( oc );
1506 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1509 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1510 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1511 goto on_fatal_error;
1517 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1519 // Last check - need at least one stream
1520 if ( !audio_st[0] && !video_st )
1522 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1523 goto on_fatal_error;
1526 // Get the starting time (can ignore the times above)
1527 gettimeofday( &ante, NULL );
1529 // Loop while running
1530 while( mlt_properties_get_int( properties, "running" ) &&
1531 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1534 frame = mlt_consumer_rt_frame( consumer );
1536 // Check that we have a frame to work with
1537 if ( frame != NULL )
1539 // Increment frames dispatched
1542 // Default audio args
1543 frame_properties = MLT_FRAME_PROPERTIES( frame );
1545 // Check for the terminated condition
1546 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1548 // Get audio and append to the fifo
1549 if ( !terminated && audio_st[0] )
1551 samples = mlt_sample_calculator( fps, frequency, count ++ );
1552 channels = total_channels;
1553 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1555 // Save the audio channel remap properties for later
1556 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1558 // Create the fifo if we don't have one
1561 fifo = sample_fifo_init( frequency, channels );
1562 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1566 // Silence if not normal forward speed
1567 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1568 memset( pcm, 0, samples * channels * sample_bytes );
1570 // Append the samples
1571 sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1572 total_time += ( samples * 1000000 ) / frequency;
1575 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1579 if ( !terminated && video_st )
1580 mlt_deque_push_back( queue, frame );
1582 mlt_frame_close( frame );
1586 // While we have stuff to process, process...
1589 // Write interleaved audio and video frames
1590 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1593 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) / sample_bytes )
1595 int j = 0; // channel offset into interleaved source buffer
1596 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1598 // Get the audio samples
1601 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1603 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1605 // This prevents an infinite loop when some versions of vorbis do not
1606 // increment pts when encoding silence.
1607 audio_pts = video_pts;
1612 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1614 samples = n / channels;
1616 // For each output stream
1617 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1619 AVStream *stream = audio_st[i];
1620 AVCodecContext *codec = stream->codec;
1623 av_init_packet( &pkt );
1625 // Optimized for single track and no channel remap
1626 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1628 void* p = audio_buf_1;
1629 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1630 if ( codec->sample_fmt == AV_SAMPLE_FMT_FLTP )
1631 p = interleaved_to_planar( samples, channels, p, sizeof( float ) );
1632 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S16P )
1633 p = interleaved_to_planar( samples, channels, p, sizeof( int16_t ) );
1634 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S32P )
1635 p = interleaved_to_planar( samples, channels, p, sizeof( int32_t ) );
1637 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, p );
1639 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1640 if ( codec->sample_fmt == AV_SAMPLE_FMT_FLTP
1641 || codec->sample_fmt == AV_SAMPLE_FMT_S16P
1642 || codec->sample_fmt == AV_SAMPLE_FMT_S32P )
1643 mlt_pool_release( p );
1648 // Extract the audio channels according to channel mapping
1649 int dest_offset = 0; // channel offset into interleaved dest buffer
1651 // Get the number of channels for this stream
1652 sprintf( key, "channels.%d", i );
1653 int current_channels = mlt_properties_get_int( properties, key );
1655 // Clear the destination audio buffer.
1657 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1659 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1661 // For each output channel
1662 while ( dest_offset < current_channels && j < total_channels )
1664 int map_start = -1, map_channels = 0;
1665 int source_offset = 0;
1668 // Look for a mapping that starts at j
1669 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1671 sprintf( key, "%d.channels", k );
1672 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1673 sprintf( key, "%d.start", k );
1674 if ( mlt_properties_get( frame_meta_properties, key ) )
1675 map_start = mlt_properties_get_int( frame_meta_properties, key );
1676 if ( map_start != j )
1677 source_offset += map_channels;
1681 if ( map_start != j )
1683 map_channels = current_channels;
1687 // Copy samples if source offset valid
1688 if ( source_offset < channels )
1690 // Interleave the audio buffer with the # channels for this stream/mapping.
1691 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1693 void *src = audio_buf_1 + source_offset * sample_bytes;
1694 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1695 int s = samples + 1;
1698 memcpy( dest, src, sample_bytes );
1699 dest += current_channels * sample_bytes;
1700 src += channels * sample_bytes;
1704 // Otherwise silence
1707 j += current_channels;
1708 dest_offset += current_channels;
1711 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1714 // Write the compressed frame in the media file
1715 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1717 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1718 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame pts %"PRId64,
1719 stream->index, pkt.pts, codec->coded_frame->pts );
1721 pkt.flags |= PKT_FLAG_KEY;
1722 pkt.stream_index = stream->index;
1723 pkt.data = audio_outbuf;
1727 if ( av_interleaved_write_frame( oc, &pkt ) )
1729 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1730 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1731 goto on_fatal_error;
1735 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1738 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1747 else if ( video_st )
1750 if ( mlt_deque_count( queue ) )
1752 int out_size, ret = 0;
1755 frame = mlt_deque_pop_front( queue );
1756 frame_properties = MLT_FRAME_PROPERTIES( frame );
1758 c = video_st->codec;
1760 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1766 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1770 // Convert the mlt frame to an AVPicture
1771 for ( i = 0; i < height; i ++ )
1773 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1774 memcpy( p, q, width * 2 );
1778 // Do the colour space conversion
1780 int flags = SWS_BICUBIC;
1782 flags |= SWS_CPU_CAPS_MMX;
1785 flags |= SWS_CPU_CAPS_MMX2;
1787 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1788 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1789 sws_scale( context, (const uint8_t* const*) input->data, input->linesize, 0, height,
1790 output->data, output->linesize);
1791 sws_freeContext( context );
1793 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1796 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1798 // Apply the alpha if applicable
1799 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1801 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1804 for ( i = 0; i < height; i ++ )
1806 n = ( width + 7 ) / 8;
1807 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1811 case 0: do { *p = *alpha++; p += 4;
1812 case 7: *p = *alpha++; p += 4;
1813 case 6: *p = *alpha++; p += 4;
1814 case 5: *p = *alpha++; p += 4;
1815 case 4: *p = *alpha++; p += 4;
1816 case 3: *p = *alpha++; p += 4;
1817 case 2: *p = *alpha++; p += 4;
1818 case 1: *p = *alpha++; p += 4;
1826 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1828 // raw video case. The API will change slightly in the near future for that
1830 av_init_packet(&pkt);
1832 pkt.flags |= PKT_FLAG_KEY;
1833 pkt.stream_index= video_st->index;
1834 pkt.data= (uint8_t *)output;
1835 pkt.size= sizeof(AVPicture);
1837 ret = av_write_frame(oc, &pkt);
1838 video_pts += c->frame_size;
1843 output->quality = c->global_quality;
1845 // Set frame interlace hints
1846 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1847 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1848 output->pts = frame_count;
1851 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1853 // If zero size, it means the image was buffered
1857 av_init_packet( &pkt );
1859 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1860 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1861 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %"PRId64" frame pts %"PRId64, pkt.pts, c->coded_frame->pts );
1862 if( c->coded_frame && c->coded_frame->key_frame )
1863 pkt.flags |= PKT_FLAG_KEY;
1864 pkt.stream_index= video_st->index;
1865 pkt.data= video_outbuf;
1868 // write the compressed frame in the media file
1869 ret = av_interleaved_write_frame(oc, &pkt);
1870 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1871 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1873 // Dual pass logging
1874 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1875 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1877 else if ( out_size < 0 )
1879 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1885 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1886 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1887 goto on_fatal_error;
1889 mlt_frame_close( frame );
1898 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1900 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1901 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1904 if ( real_time_output == 1 && frames % 2 == 0 )
1906 long passed = time_difference( &ante );
1909 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
1912 if ( passed < total_time )
1914 long total = ( total_time - passed );
1915 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1916 nanosleep( &t, NULL );
1921 // Flush the encoder buffers
1922 if ( real_time_output <= 0 )
1925 // TODO: flush all audio streams
1926 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1928 AVCodecContext *c = audio_st[0]->codec;
1930 av_init_packet( &pkt );
1934 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) / sample_bytes ) )
1936 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size * sample_bytes );
1937 void* p = audio_buf_1;
1938 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1939 if ( c->sample_fmt == AV_SAMPLE_FMT_FLTP )
1940 p = interleaved_to_planar( audio_input_frame_size, channels, p, sizeof( float ) );
1941 else if ( c->sample_fmt == AV_SAMPLE_FMT_S16P )
1942 p = interleaved_to_planar( audio_input_frame_size, channels, p, sizeof( int16_t ) );
1943 else if ( c->sample_fmt == AV_SAMPLE_FMT_S32P )
1944 p = interleaved_to_planar( audio_input_frame_size, channels, p, sizeof( int32_t ) );
1946 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, p );
1947 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1948 if ( c->sample_fmt == AV_SAMPLE_FMT_FLTP
1949 || c->sample_fmt == AV_SAMPLE_FMT_S16P
1950 || c->sample_fmt == AV_SAMPLE_FMT_S32P )
1951 mlt_pool_release( p );
1954 if ( pkt.size <= 0 )
1955 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1956 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1957 if ( pkt.size <= 0 )
1960 // Write the compressed frame in the media file
1961 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1962 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1963 pkt.flags |= PKT_FLAG_KEY;
1964 pkt.stream_index = audio_st[0]->index;
1965 pkt.data = audio_outbuf;
1966 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1968 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1969 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1970 goto on_fatal_error;
1975 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1977 AVCodecContext *c = video_st->codec;
1979 av_init_packet( &pkt );
1982 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1983 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1984 if ( pkt.size <= 0 )
1987 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1988 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1989 if( c->coded_frame && c->coded_frame->key_frame )
1990 pkt.flags |= PKT_FLAG_KEY;
1991 pkt.stream_index = video_st->index;
1992 pkt.data = video_outbuf;
1994 // write the compressed frame in the media file
1995 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1997 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1998 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1999 goto on_fatal_error;
2001 // Dual pass logging
2002 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
2003 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
2009 // Write the trailer, if any
2011 av_write_trailer( oc );
2015 close_video(oc, video_st);
2016 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
2017 close_audio( oc, audio_st[i] );
2020 for ( i = 0; i < oc->nb_streams; i++ )
2021 av_freep( &oc->streams[i] );
2023 // Close the output file
2024 if ( !( fmt->flags & AVFMT_NOFILE ) &&
2025 !mlt_properties_get_int( properties, "redirect" ) )
2027 #if LIBAVFORMAT_VERSION_MAJOR >= 53
2028 if ( oc->pb ) avio_close( oc->pb );
2029 #elif LIBAVFORMAT_VERSION_MAJOR >= 52
2030 if ( oc->pb ) url_fclose( oc->pb );
2032 url_fclose( &oc->pb );
2036 // Clean up input and output frames
2038 av_free( output->data[0] );
2040 av_free( input->data[0] );
2042 av_free( video_outbuf );
2043 av_free( audio_buf_1 );
2044 av_free( audio_buf_2 );
2049 // Just in case we terminated on pause
2050 mlt_consumer_stopped( consumer );
2051 mlt_properties_close( frame_meta_properties );
2053 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
2055 // Remove the dual pass log file
2056 if ( mlt_properties_get( properties, "_logfilename" ) )
2057 remove( mlt_properties_get( properties, "_logfilename" ) );
2059 // Remove the x264 dual pass logs
2060 char *cwd = getcwd( NULL, 0 );
2061 const char *file = "x264_2pass.log";
2062 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2063 sprintf( full, "%s/%s", cwd, file );
2066 file = "x264_2pass.log.temp";
2067 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2068 sprintf( full, "%s/%s", cwd, file );
2071 file = "x264_2pass.log.mbtree";
2072 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2073 sprintf( full, "%s/%s", cwd, file );
2077 remove( "x264_2pass.log.temp" );
2080 while ( ( frame = mlt_deque_pop_back( queue ) ) )
2081 mlt_frame_close( frame );
2086 /** Close the consumer.
2089 static void consumer_close( mlt_consumer consumer )
2091 // Stop the consumer
2092 mlt_consumer_stop( consumer );
2095 mlt_consumer_close( consumer );