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_U8 SAMPLE_FMT_U8
55 # define AV_SAMPLE_FMT_S16 SAMPLE_FMT_S16
56 # define AV_SAMPLE_FMT_S32 SAMPLE_FMT_S32
57 # define AV_SAMPLE_FMT_FLT SAMPLE_FMT_FLT
60 #if LIBAVUTIL_VERSION_INT < (50<<16)
61 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
62 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
65 #if LIBAVCODEC_VERSION_MAJOR >= 53
66 #include <libavutil/opt.h>
67 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
68 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
69 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
71 #include <libavcodec/opt.h>
74 #define MAX_AUDIO_STREAMS (8)
75 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
76 #define AUDIO_BUFFER_SIZE (1024 * 42)
77 #define VIDEO_BUFFER_SIZE (2048 * 1024)
80 // This structure should be extended and made globally available in mlt
92 *sample_fifo, sample_fifo_s;
94 sample_fifo sample_fifo_init( int frequency, int channels )
96 sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
97 fifo->frequency = frequency;
98 fifo->channels = channels;
102 // count is the number of samples multiplied by the number of bytes per sample
103 void sample_fifo_append( sample_fifo fifo, uint8_t *samples, int count )
105 if ( ( fifo->size - fifo->used ) < count )
107 fifo->size += count * 5;
108 fifo->buffer = realloc( fifo->buffer, fifo->size );
111 memcpy( &fifo->buffer[ fifo->used ], samples, count );
115 int sample_fifo_used( sample_fifo fifo )
120 int sample_fifo_fetch( sample_fifo fifo, uint8_t *samples, int count )
122 if ( count > fifo->used )
125 memcpy( samples, fifo->buffer, count );
127 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used );
129 fifo->time += ( double )count / fifo->channels / fifo->frequency;
134 void sample_fifo_close( sample_fifo fifo )
136 free( fifo->buffer );
140 // Forward references.
141 static int consumer_start( mlt_consumer consumer );
142 static int consumer_stop( mlt_consumer consumer );
143 static int consumer_is_stopped( mlt_consumer consumer );
144 static void *consumer_thread( void *arg );
145 static void consumer_close( mlt_consumer consumer );
147 /** Initialise the consumer.
150 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
152 // Allocate the consumer
153 mlt_consumer consumer = mlt_consumer_new( profile );
155 // If memory allocated and initialises without error
156 if ( consumer != NULL )
158 // Get properties from the consumer
159 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
161 // Assign close callback
162 consumer->close = consumer_close;
164 // Interpret the argument
166 mlt_properties_set( properties, "target", arg );
168 // sample and frame queue
169 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
171 // Audio options not fully handled by AVOptions
172 #define QSCALE_NONE (-99999)
173 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
175 // Video options not fully handled by AVOptions
176 mlt_properties_set_int( properties, "dc", 8 );
178 // Muxer options not fully handled by AVOptions
179 mlt_properties_set_double( properties, "muxdelay", 0.7 );
180 mlt_properties_set_double( properties, "muxpreload", 0.5 );
182 // Ensure termination at end of the stream
183 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
185 // Default to separate processing threads for producer and consumer with no frame dropping!
186 mlt_properties_set_int( properties, "real_time", -1 );
187 mlt_properties_set_int( properties, "prefill", 1 );
189 // Set up start/stop/terminated callbacks
190 consumer->start = consumer_start;
191 consumer->stop = consumer_stop;
192 consumer->is_stopped = consumer_is_stopped;
194 mlt_events_register( properties, "consumer-fatal-error", NULL );
201 /** Start the consumer.
204 static int consumer_start( mlt_consumer consumer )
206 // Get the properties
207 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
210 // Report information about available muxers and codecs as YAML Tiny
211 char *s = mlt_properties_get( properties, "f" );
212 if ( s && strcmp( s, "list" ) == 0 )
214 mlt_properties doc = mlt_properties_new();
215 mlt_properties formats = mlt_properties_new();
217 AVOutputFormat *format = NULL;
219 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
220 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
221 while ( ( format = av_oformat_next( format ) ) )
223 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
224 mlt_properties_set( formats, key, format->name );
226 s = mlt_properties_serialise_yaml( doc );
227 fprintf( stdout, "%s", s );
229 mlt_properties_close( doc );
232 s = mlt_properties_get( properties, "acodec" );
233 if ( s && strcmp( s, "list" ) == 0 )
235 mlt_properties doc = mlt_properties_new();
236 mlt_properties codecs = mlt_properties_new();
238 AVCodec *codec = NULL;
240 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
241 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
242 while ( ( codec = av_codec_next( codec ) ) )
243 #if (defined(FFUDIV) && LIBAVCODEC_VERSION_INT >= ((54<<16)+(56<<8)+100)) || (LIBAVCODEC_VERSION_INT >= ((54<<16)+(27<<8)+0))
244 if ( codec->encode2 && codec->type == CODEC_TYPE_AUDIO )
245 #elif LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
246 if ( ( codec->encode || codec->encode2 ) && codec->type == CODEC_TYPE_AUDIO )
248 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
251 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
252 mlt_properties_set( codecs, key, codec->name );
254 s = mlt_properties_serialise_yaml( doc );
255 fprintf( stdout, "%s", s );
257 mlt_properties_close( doc );
260 s = mlt_properties_get( properties, "vcodec" );
261 if ( s && strcmp( s, "list" ) == 0 )
263 mlt_properties doc = mlt_properties_new();
264 mlt_properties codecs = mlt_properties_new();
266 AVCodec *codec = NULL;
268 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
269 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
270 while ( ( codec = av_codec_next( codec ) ) )
271 #if (defined(FFUDIV) && LIBAVCODEC_VERSION_INT >= ((54<<16)+(56<<8)+100)) || (LIBAVCODEC_VERSION_INT >= ((54<<16)+(27<<8)+0))
272 if ( codec->encode2 && codec->type == CODEC_TYPE_VIDEO )
273 #elif LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
274 if ( (codec->encode || codec->encode2) && codec->type == CODEC_TYPE_VIDEO )
276 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
279 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
280 mlt_properties_set( codecs, key, codec->name );
282 s = mlt_properties_serialise_yaml( doc );
283 fprintf( stdout, "%s", s );
285 mlt_properties_close( doc );
289 // Check that we're not already running
290 if ( !error && !mlt_properties_get_int( properties, "running" ) )
293 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
295 // Get the width and height
296 int width = mlt_properties_get_int( properties, "width" );
297 int height = mlt_properties_get_int( properties, "height" );
299 // Obtain the size property
300 char *size = mlt_properties_get( properties, "s" );
306 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
313 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Invalid size property %s - ignoring.\n", size );
317 // Now ensure we honour the multiple of two requested by libavformat
318 width = ( width / 2 ) * 2;
319 height = ( height / 2 ) * 2;
320 mlt_properties_set_int( properties, "width", width );
321 mlt_properties_set_int( properties, "height", height );
323 // We need to set these on the profile as well because the s property is
324 // an alias to mlt properties that correspond to profile settings.
325 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
328 profile->width = width;
329 profile->height = height;
332 if ( mlt_properties_get( properties, "aspect" ) )
334 // "-aspect" on ffmpeg command line is display aspect ratio
335 double ar = mlt_properties_get_double( properties, "aspect" );
336 AVRational rational = av_d2q( ar, 255 );
338 // Update the profile and properties as well since this is an alias
339 // for mlt properties that correspond to profile settings
340 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
341 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
344 profile->display_aspect_num = rational.num;
345 profile->display_aspect_den = rational.den;
346 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
349 // Now compute the sample aspect ratio
350 rational = av_d2q( ar * height / width, 255 );
352 // Update the profile and properties as well since this is an alias
353 // for mlt properties that correspond to profile settings
354 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
355 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
358 profile->sample_aspect_num = rational.num;
359 profile->sample_aspect_den = rational.den;
360 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
364 // Handle the ffmpeg command line "-r" property for frame rate
365 if ( mlt_properties_get( properties, "r" ) )
367 double frame_rate = mlt_properties_get_double( properties, "r" );
368 AVRational rational = av_d2q( frame_rate, 255 );
369 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
370 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
373 profile->frame_rate_num = rational.num;
374 profile->frame_rate_den = rational.den;
375 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
379 // Apply AVOptions that are synonyms for standard mlt_consumer options
380 if ( mlt_properties_get( properties, "ac" ) )
381 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
382 if ( mlt_properties_get( properties, "ar" ) )
383 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
385 // Assign the thread to properties
386 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
389 pthread_create( thread, NULL, consumer_thread, consumer );
391 // Set the running state
392 mlt_properties_set_int( properties, "running", 1 );
397 /** Stop the consumer.
400 static int consumer_stop( mlt_consumer consumer )
402 // Get the properties
403 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
404 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
406 // Check that we're running
410 mlt_properties_set_int( properties, "running", 0 );
412 // Wait for termination
413 pthread_join( *thread, NULL );
415 mlt_properties_set_data( properties, "thread", NULL, 0, NULL, NULL );
421 /** Determine if the consumer is stopped.
424 static int consumer_is_stopped( mlt_consumer consumer )
426 // Get the properties
427 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
428 return !mlt_properties_get_int( properties, "running" );
431 /** Process properties as AVOptions and apply to AV context obj
434 static void apply_properties( void *obj, mlt_properties properties, int flags )
437 int count = mlt_properties_count( properties );
438 #if LIBAVUTIL_VERSION_INT < ((51<<16)+(12<<8)+0)
442 for ( i = 0; i < count; i++ )
444 const char *opt_name = mlt_properties_get_name( properties, i );
445 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
446 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
448 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
451 // If option not found, see if it was prefixed with a or v (-vb)
453 ( opt_name[0] == 'v' && ( flags & AV_OPT_FLAG_VIDEO_PARAM ) ) ||
454 ( opt_name[0] == 'a' && ( flags & AV_OPT_FLAG_AUDIO_PARAM ) ) ) )
455 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
456 opt = av_opt_find( obj, ++opt_name, NULL, flags, flags );
458 opt = av_find_opt( obj, ++opt_name, NULL, flags, flags );
460 // Apply option if found
462 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
463 av_opt_set( obj, opt_name, mlt_properties_get_value( properties, i), 0 );
464 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
465 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
466 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
467 av_set_string2( obj, opt_name, mlt_properties_get_value( properties, i), alloc );
469 av_set_string( obj, opt_name, mlt_properties_get_value( properties, i) );
474 static int get_mlt_audio_format( int av_sample_fmt )
476 switch ( av_sample_fmt )
478 case AV_SAMPLE_FMT_U8:
480 case AV_SAMPLE_FMT_S32:
481 return mlt_audio_s32le;
482 case AV_SAMPLE_FMT_FLT:
483 return mlt_audio_f32le;
484 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
485 case AV_SAMPLE_FMT_U8P:
487 case AV_SAMPLE_FMT_S32P:
488 return mlt_audio_s32le;
489 case AV_SAMPLE_FMT_FLTP:
490 return mlt_audio_f32le;
493 return mlt_audio_s16;
497 static int pick_sample_fmt( mlt_properties properties, AVCodec *codec )
499 int sample_fmt = AV_SAMPLE_FMT_S16;
500 const char *format = mlt_properties_get( properties, "mlt_audio_format" );
501 const int *p = codec->sample_fmts;
503 // get default av_sample_fmt from mlt_audio_format
506 if ( !strcmp( format, "s32le" ) )
507 sample_fmt = AV_SAMPLE_FMT_S32;
508 else if ( !strcmp( format, "f32le" ) )
509 sample_fmt = AV_SAMPLE_FMT_FLT;
510 else if ( !strcmp( format, "u8" ) )
511 sample_fmt = AV_SAMPLE_FMT_U8;
512 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
513 else if ( !strcmp( format, "s32" ) )
514 sample_fmt = AV_SAMPLE_FMT_S32P;
515 else if ( !strcmp( format, "float" ) )
516 sample_fmt = AV_SAMPLE_FMT_FLTP;
519 // check if codec supports our mlt_audio_format
520 for ( ; *p != -1; p++ )
522 if ( *p == sample_fmt )
525 // no match - pick first one we support
526 for ( p = codec->sample_fmts; *p != -1; p++ )
530 case AV_SAMPLE_FMT_U8:
531 case AV_SAMPLE_FMT_S16:
532 case AV_SAMPLE_FMT_S32:
533 case AV_SAMPLE_FMT_FLT:
534 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
535 case AV_SAMPLE_FMT_U8P:
536 case AV_SAMPLE_FMT_S16P:
537 case AV_SAMPLE_FMT_S32P:
538 case AV_SAMPLE_FMT_FLTP:
545 mlt_log_error( properties, "audio codec sample_fmt not compatible" );
547 return AV_SAMPLE_FMT_NONE;
550 static uint8_t* interleaved_to_planar( int samples, int channels, uint8_t* audio, int bytes_per_sample )
552 int size = samples * channels * bytes_per_sample;
553 uint8_t *buffer = mlt_pool_alloc( AUDIO_ENCODE_BUFFER_SIZE );
557 memset( buffer, 0, AUDIO_ENCODE_BUFFER_SIZE );
558 for ( c = 0; c < channels; c++ )
560 uint8_t *q = audio + c * bytes_per_sample;
564 memcpy( p, q, bytes_per_sample );
565 p += bytes_per_sample;
566 q += channels * bytes_per_sample;
572 /** Add an audio output stream
575 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec, int channels )
577 // Get the properties
578 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
580 // Create a new stream
581 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
582 AVStream *st = avformat_new_stream( oc, codec );
584 AVStream *st = av_new_stream( oc, oc->nb_streams );
587 // If created, then initialise from properties
590 AVCodecContext *c = st->codec;
592 // Establish defaults from AVOptions
593 #if LIBAVCODEC_VERSION_MAJOR >= 53
594 avcodec_get_context_defaults3( c, codec );
596 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
599 c->codec_id = codec->id;
600 c->codec_type = CODEC_TYPE_AUDIO;
601 c->sample_fmt = pick_sample_fmt( properties, codec );
603 #if 0 // disabled until some audio codecs are multi-threaded
604 // Setup multi-threading
605 int thread_count = mlt_properties_get_int( properties, "threads" );
606 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
607 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
608 if ( thread_count > 1 )
609 c->thread_count = thread_count;
612 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
613 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
615 // Allow the user to override the audio fourcc
616 if ( mlt_properties_get( properties, "atag" ) )
619 char *arg = mlt_properties_get( properties, "atag" );
620 int tag = strtol( arg, &tail, 0);
622 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
626 // Process properties as AVOptions
627 char *apre = mlt_properties_get( properties, "apre" );
630 mlt_properties p = mlt_properties_load( apre );
631 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
632 mlt_properties_close( p );
634 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
636 int audio_qscale = mlt_properties_get_int( properties, "aq" );
637 if ( audio_qscale > QSCALE_NONE )
639 c->flags |= CODEC_FLAG_QSCALE;
640 c->global_quality = FF_QP2LAMBDA * audio_qscale;
641 #if LIBAVFORMAT_VERSION_MAJOR < 53
642 st->quality = c->global_quality;
646 // Set parameters controlled by MLT
647 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
648 c->time_base = ( AVRational ){ 1, c->sample_rate };
649 c->channels = channels;
651 if ( mlt_properties_get( properties, "alang" ) != NULL )
652 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
653 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
654 av_dict_set( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
656 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
660 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
665 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
671 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
673 // We will return the audio input size from here
674 int audio_input_frame_size = 0;
677 AVCodecContext *c = st->codec;
682 codec = avcodec_find_encoder_by_name( codec_name );
684 codec = avcodec_find_encoder( c->codec_id );
686 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
687 // Process properties as AVOptions on the AVCodec
688 if ( codec && codec->priv_class )
690 char *apre = mlt_properties_get( properties, "apre" );
691 if ( !c->priv_data && codec->priv_data_size )
693 c->priv_data = av_mallocz( codec->priv_data_size );
694 *(const AVClass **) c->priv_data = codec->priv_class;
695 // av_opt_set_defaults( c );
699 mlt_properties p = mlt_properties_load( apre );
700 apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
701 mlt_properties_close( p );
703 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
707 // Continue if codec found and we can open it
708 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
709 if ( codec && avcodec_open2( c, codec, NULL ) >= 0 )
711 if ( codec && avcodec_open( c, codec ) >= 0 )
714 // ugly hack for PCM codecs (will be removed ASAP with new PCM
715 // support to compute the input frame size in samples
716 if ( c->frame_size <= 1 )
718 audio_input_frame_size = audio_outbuf_size / c->channels;
719 switch(st->codec->codec_id)
721 case CODEC_ID_PCM_S16LE:
722 case CODEC_ID_PCM_S16BE:
723 case CODEC_ID_PCM_U16LE:
724 case CODEC_ID_PCM_U16BE:
725 audio_input_frame_size >>= 1;
733 audio_input_frame_size = c->frame_size;
736 // Some formats want stream headers to be seperate (hmm)
737 if ( !strcmp( oc->oformat->name, "mp4" ) ||
738 !strcmp( oc->oformat->name, "mov" ) ||
739 !strcmp( oc->oformat->name, "3gp" ) )
740 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
744 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
745 audio_input_frame_size = 0;
748 return audio_input_frame_size;
751 static void close_audio( AVFormatContext *oc, AVStream *st )
753 if ( st && st->codec )
754 avcodec_close( st->codec );
757 /** Add a video output stream
760 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
762 // Get the properties
763 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
765 // Create a new stream
766 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
767 AVStream *st = avformat_new_stream( oc, codec );
769 AVStream *st = av_new_stream( oc, oc->nb_streams );
774 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
775 AVCodecContext *c = st->codec;
777 // Establish defaults from AVOptions
778 #if LIBAVCODEC_VERSION_MAJOR >= 53
779 avcodec_get_context_defaults3( c, codec );
781 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
784 c->codec_id = codec->id;
785 c->codec_type = CODEC_TYPE_VIDEO;
787 // Setup multi-threading
788 int thread_count = mlt_properties_get_int( properties, "threads" );
789 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
790 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
791 if ( thread_count > 1 )
792 #if LIBAVCODEC_VERSION_MAJOR >= 53
793 c->thread_count = thread_count;
795 avcodec_thread_init( c, thread_count );
798 // Process properties as AVOptions
799 char *vpre = mlt_properties_get( properties, "vpre" );
802 mlt_properties p = mlt_properties_load( vpre );
804 if ( mlt_properties_count( p ) < 1 )
806 AVCodec *codec = avcodec_find_encoder( c->codec_id );
809 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
810 strcpy( path, AVDATADIR );
811 strcat( path, codec->name );
813 strcat( path, vpre );
814 strcat( path, ".ffpreset" );
816 mlt_properties_close( p );
817 p = mlt_properties_load( path );
818 if ( mlt_properties_count( p ) > 0 )
819 mlt_properties_debug( p, path, stderr );
825 mlt_properties_debug( p, vpre, stderr );
828 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
829 mlt_properties_close( p );
831 int colorspace = mlt_properties_get_int( properties, "colorspace" );
832 mlt_properties_set( properties, "colorspace", NULL );
833 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
834 mlt_properties_set_int( properties, "colorspace", colorspace );
836 // Set options controlled by MLT
837 c->width = mlt_properties_get_int( properties, "width" );
838 c->height = mlt_properties_get_int( properties, "height" );
839 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
840 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
841 if ( st->time_base.den == 0 )
842 st->time_base = c->time_base;
843 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
844 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
846 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
849 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
850 switch ( colorspace )
853 c->colorspace = AVCOL_SPC_SMPTE170M;
856 c->colorspace = AVCOL_SPC_SMPTE240M;
859 c->colorspace = AVCOL_SPC_BT470BG;
862 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
865 c->colorspace = AVCOL_SPC_BT709;
870 if ( mlt_properties_get( properties, "aspect" ) )
872 // "-aspect" on ffmpeg command line is display aspect ratio
873 double ar = mlt_properties_get_double( properties, "aspect" );
874 c->sample_aspect_ratio = av_d2q( ar * c->height / c->width, 255 );
878 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
879 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
881 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
882 st->sample_aspect_ratio = c->sample_aspect_ratio;
885 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
887 c->flags |= CODEC_FLAG_QSCALE;
888 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
889 #if LIBAVFORMAT_VERSION_MAJOR < 53
890 st->quality = c->global_quality;
894 // Allow the user to override the video fourcc
895 if ( mlt_properties_get( properties, "vtag" ) )
898 const char *arg = mlt_properties_get( properties, "vtag" );
899 int tag = strtol( arg, &tail, 0);
901 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
905 // Some formats want stream headers to be seperate
906 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
907 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
909 // Translate these standard mlt consumer properties to ffmpeg
910 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
911 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
913 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
914 c->flags |= CODEC_FLAG_INTERLACED_DCT;
915 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
916 c->flags |= CODEC_FLAG_INTERLACED_ME;
919 // parse the ratecontrol override string
921 char *rc_override = mlt_properties_get( properties, "rc_override" );
922 for ( i = 0; rc_override; i++ )
925 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
927 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
928 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
929 c->rc_override[i].start_frame = start;
930 c->rc_override[i].end_frame = end;
933 c->rc_override[i].qscale = q;
934 c->rc_override[i].quality_factor = 1.0;
938 c->rc_override[i].qscale = 0;
939 c->rc_override[i].quality_factor = -q / 100.0;
941 rc_override = strchr( rc_override, '/' );
945 c->rc_override_count = i;
946 if ( !c->rc_initial_buffer_occupancy )
947 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
948 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
951 i = mlt_properties_get_int( properties, "pass" );
953 c->flags |= CODEC_FLAG_PASS1;
955 c->flags |= CODEC_FLAG_PASS2;
956 if ( codec->id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
958 char logfilename[1024];
963 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
964 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
965 if ( c->flags & CODEC_FLAG_PASS1 )
967 f = fopen( logfilename, "w" );
969 perror( logfilename );
971 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
975 /* read the log file */
976 f = fopen( logfilename, "r" );
983 mlt_properties_set( properties, "_logfilename", logfilename );
984 fseek( f, 0, SEEK_END );
986 fseek( f, 0, SEEK_SET );
987 logbuffer = av_malloc( size + 1 );
989 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
994 size = fread( logbuffer, 1, size, f );
995 logbuffer[size] = '\0';
996 c->stats_in = logbuffer;
1006 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
1012 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
1015 AVFrame *picture = avcodec_alloc_frame();
1017 // Determine size of the
1018 int size = avpicture_get_size(pix_fmt, width, height);
1020 // Allocate the picture buf
1021 uint8_t *picture_buf = av_malloc(size);
1023 // If we have both, then fill the image
1024 if ( picture != NULL && picture_buf != NULL )
1026 // Fill the frame with the allocated buffer
1027 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
1031 // Something failed - clean up what we can
1033 av_free( picture_buf );
1040 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
1043 AVCodecContext *video_enc = st->codec;
1045 // find the video encoder
1048 codec = avcodec_find_encoder_by_name( codec_name );
1050 codec = avcodec_find_encoder( video_enc->codec_id );
1052 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1053 // Process properties as AVOptions on the AVCodec
1054 if ( codec && codec->priv_class )
1056 char *vpre = mlt_properties_get( properties, "vpre" );
1057 if ( !video_enc->priv_data && codec->priv_data_size )
1059 video_enc->priv_data = av_mallocz( codec->priv_data_size );
1060 *(const AVClass **) video_enc->priv_data = codec->priv_class;
1061 // av_opt_set_defaults( video_enc );
1065 mlt_properties p = mlt_properties_load( vpre );
1066 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1067 mlt_properties_close( p );
1069 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1073 if( codec && codec->pix_fmts )
1075 const enum PixelFormat *p = codec->pix_fmts;
1076 for( ; *p!=-1; p++ )
1078 if( *p == video_enc->pix_fmt )
1082 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1085 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1086 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1088 int result = codec && avcodec_open( video_enc, codec ) >= 0;
1094 void close_video(AVFormatContext *oc, AVStream *st)
1096 if ( st && st->codec )
1098 av_freep( &st->codec->stats_in );
1099 avcodec_close(st->codec);
1103 static inline long time_difference( struct timeval *time1 )
1105 struct timeval time2;
1106 gettimeofday( &time2, NULL );
1107 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1110 static int mlt_write(void *h, uint8_t *buf, int size)
1112 mlt_properties properties = (mlt_properties) h;
1113 mlt_events_fire( properties, "avformat-write", buf, size, NULL );
1117 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1119 listener( owner, service, (uint8_t*) args[0], (int) args[1] );
1122 /** The main thread - the argument is simply the consumer.
1125 static void *consumer_thread( void *arg )
1127 // Map the argument to the object
1128 mlt_consumer consumer = arg;
1130 // Get the properties
1131 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1133 // Get the terminate on pause property
1134 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1137 // Determine if feed is slow (for realtime stuff)
1138 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1141 struct timeval ante;
1143 // Get the frame rate
1144 double fps = mlt_properties_get_double( properties, "fps" );
1146 // Get width and height
1147 int width = mlt_properties_get_int( properties, "width" );
1148 int height = mlt_properties_get_int( properties, "height" );
1149 int img_width = width;
1150 int img_height = height;
1152 // Get default audio properties
1153 int channels = mlt_properties_get_int( properties, "channels" );
1154 int total_channels = channels;
1155 int frequency = mlt_properties_get_int( properties, "frequency" );
1159 // AVFormat audio buffer and frame size
1160 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1161 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1162 int audio_input_frame_size = 0;
1164 // AVFormat video buffer and frame count
1165 int frame_count = 0;
1166 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1167 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1169 // Used for the frame properties
1170 mlt_frame frame = NULL;
1171 mlt_properties frame_properties = NULL;
1174 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1175 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1177 // Need two av pictures for converting
1178 AVFrame *output = NULL;
1179 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
1181 // For receiving images from an mlt_frame
1183 mlt_image_format img_fmt = mlt_image_yuv422;
1185 // For receiving audio samples back from the fifo
1186 uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1187 uint8_t *audio_buf_2 = NULL;
1190 // Allocate the context
1191 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
1192 AVFormatContext *oc = avformat_alloc_context( );
1194 AVFormatContext *oc = av_alloc_format_context( );
1198 AVStream *video_st = NULL;
1199 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1202 double audio_pts = 0;
1203 double video_pts = 0;
1205 // Frames dispatched
1206 long int frames = 0;
1207 long int total_time = 0;
1209 // Determine the format
1210 AVOutputFormat *fmt = NULL;
1211 const char *filename = mlt_properties_get( properties, "target" );
1212 char *format = mlt_properties_get( properties, "f" );
1213 char *vcodec = mlt_properties_get( properties, "vcodec" );
1214 char *acodec = mlt_properties_get( properties, "acodec" );
1215 AVCodec *audio_codec = NULL;
1216 AVCodec *video_codec = NULL;
1218 // Used to store and override codec ids
1224 mlt_properties frame_meta_properties = mlt_properties_new();
1226 // Initialize audio_st
1227 int i = MAX_AUDIO_STREAMS;
1231 // Check for user selected format first
1232 if ( format != NULL )
1233 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1234 fmt = guess_format( format, NULL, NULL );
1236 fmt = av_guess_format( format, NULL, NULL );
1239 // Otherwise check on the filename
1240 if ( fmt == NULL && filename != NULL )
1241 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1242 fmt = guess_format( NULL, filename, NULL );
1244 fmt = av_guess_format( NULL, filename, NULL );
1247 // Otherwise default to mpeg
1249 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1250 fmt = guess_format( "mpeg", NULL, NULL );
1252 fmt = av_guess_format( "mpeg", NULL, NULL );
1255 // We need a filename - default to stdout?
1256 if ( filename == NULL || !strcmp( filename, "" ) )
1259 // Get the codec ids selected
1260 audio_codec_id = fmt->audio_codec;
1261 video_codec_id = fmt->video_codec;
1263 // Check for audio codec overides
1264 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1265 audio_codec_id = CODEC_ID_NONE;
1268 audio_codec = avcodec_find_encoder_by_name( acodec );
1271 audio_codec_id = audio_codec->id;
1272 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1274 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1275 acodec = mlt_properties_get( properties, "_acodec" );
1276 audio_codec = avcodec_find_encoder_by_name( acodec );
1278 else if ( !strcmp( acodec, "aac" ) )
1280 mlt_properties_set( properties, "astrict", "experimental" );
1285 audio_codec_id = CODEC_ID_NONE;
1286 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1291 audio_codec = avcodec_find_encoder( audio_codec_id );
1294 // Check for video codec overides
1295 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1296 video_codec_id = CODEC_ID_NONE;
1299 video_codec = avcodec_find_encoder_by_name( vcodec );
1302 video_codec_id = video_codec->id;
1306 video_codec_id = CODEC_ID_NONE;
1307 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1312 video_codec = avcodec_find_encoder( video_codec_id );
1316 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1317 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1319 char *name = mlt_properties_get_name( properties, i );
1320 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1322 char *key = strdup( name + 10 );
1323 char *markup = strrchr( key, '.' );
1324 if ( markup && !strcmp( markup, ".markup") )
1327 if ( !strstr( key, ".stream." ) )
1328 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1329 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1330 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1332 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1335 av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1345 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1346 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1348 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1349 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1351 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1352 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1354 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1355 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1357 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1358 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1360 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1361 if (metavalue != 0) oc->year = metavalue;
1363 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1364 if (metavalue != 0) oc->track = metavalue;
1368 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1370 // Get a frame now, so we can set some AVOptions from properties.
1371 frame = mlt_consumer_rt_frame( consumer );
1373 // Set the timecode from the MLT metadata if available.
1376 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1377 if ( timecode && strcmp( timecode, "" ) )
1379 mlt_properties_set( properties, "timecode", timecode );
1380 if ( strchr( timecode, ';' ) )
1381 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1385 // Add audio and video streams
1386 if ( video_codec_id != CODEC_ID_NONE )
1387 video_st = add_video_stream( consumer, oc, video_codec );
1388 if ( audio_codec_id != CODEC_ID_NONE )
1394 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1396 sprintf( key, "channels.%d", i );
1397 int j = mlt_properties_get_int( properties, key );
1401 total_channels += j;
1402 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1408 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1409 total_channels = channels;
1412 mlt_properties_set_int( properties, "channels", total_channels );
1414 // Audio format is determined when adding the audio stream
1415 mlt_audio_format aud_fmt = mlt_audio_none;
1417 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1418 int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1419 sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1421 // Set the parameters (even though we have none...)
1422 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1423 if ( av_set_parameters(oc, NULL) >= 0 )
1426 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1427 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1428 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1430 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1432 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1434 // Process properties as AVOptions
1435 char *fpre = mlt_properties_get( properties, "fpre" );
1438 mlt_properties p = mlt_properties_load( fpre );
1439 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1440 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1441 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1442 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1444 mlt_properties_close( p );
1446 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1447 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1448 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1449 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1452 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1454 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1456 audio_input_frame_size = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1457 acodec? acodec : NULL );
1458 if ( !audio_input_frame_size )
1460 // Remove the audio stream from the output context
1462 for ( j = 0; j < oc->nb_streams; j++ )
1464 if ( oc->streams[j] == audio_st[i] )
1465 av_freep( &oc->streams[j] );
1472 // Setup custom I/O if redirecting
1473 if ( mlt_properties_get_int( properties, "redirect" ) )
1475 int buffer_size = 32768;
1476 unsigned char *buffer = av_malloc( buffer_size );
1477 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1478 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1480 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1485 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1486 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1488 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1489 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1490 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1495 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1498 // Open the output file, if needed
1499 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1501 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1502 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1504 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1507 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1508 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1509 goto on_fatal_error;
1513 // Write the stream header.
1514 if ( mlt_properties_get_int( properties, "running" ) )
1515 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1516 avformat_write_header( oc, NULL );
1518 av_write_header( oc );
1521 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1524 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1525 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1526 goto on_fatal_error;
1532 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1534 // Last check - need at least one stream
1535 if ( !audio_st[0] && !video_st )
1537 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1538 goto on_fatal_error;
1541 // Get the starting time (can ignore the times above)
1542 gettimeofday( &ante, NULL );
1544 // Loop while running
1545 while( mlt_properties_get_int( properties, "running" ) &&
1546 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1549 frame = mlt_consumer_rt_frame( consumer );
1551 // Check that we have a frame to work with
1552 if ( frame != NULL )
1554 // Increment frames dispatched
1557 // Default audio args
1558 frame_properties = MLT_FRAME_PROPERTIES( frame );
1560 // Check for the terminated condition
1561 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1563 // Get audio and append to the fifo
1564 if ( !terminated && audio_st[0] )
1566 samples = mlt_sample_calculator( fps, frequency, count ++ );
1567 channels = total_channels;
1568 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1570 // Save the audio channel remap properties for later
1571 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1573 // Create the fifo if we don't have one
1576 fifo = sample_fifo_init( frequency, channels );
1577 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1581 // Silence if not normal forward speed
1582 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1583 memset( pcm, 0, samples * channels * sample_bytes );
1585 // Append the samples
1586 sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1587 total_time += ( samples * 1000000 ) / frequency;
1590 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1594 if ( !terminated && video_st )
1595 mlt_deque_push_back( queue, frame );
1597 mlt_frame_close( frame );
1601 // While we have stuff to process, process...
1604 // Write interleaved audio and video frames
1605 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1608 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) / sample_bytes )
1610 int j = 0; // channel offset into interleaved source buffer
1611 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1613 // Get the audio samples
1616 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1618 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1620 // This prevents an infinite loop when some versions of vorbis do not
1621 // increment pts when encoding silence.
1622 audio_pts = video_pts;
1627 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1629 samples = n / channels;
1631 // For each output stream
1632 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1634 AVStream *stream = audio_st[i];
1635 AVCodecContext *codec = stream->codec;
1638 av_init_packet( &pkt );
1640 // Optimized for single track and no channel remap
1641 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1643 void* p = audio_buf_1;
1644 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1645 if ( codec->sample_fmt == AV_SAMPLE_FMT_FLTP )
1646 p = interleaved_to_planar( samples, channels, p, sizeof( float ) );
1647 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S16P )
1648 p = interleaved_to_planar( samples, channels, p, sizeof( int16_t ) );
1649 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S32P )
1650 p = interleaved_to_planar( samples, channels, p, sizeof( int32_t ) );
1651 else if ( codec->sample_fmt == AV_SAMPLE_FMT_U8P )
1652 p = interleaved_to_planar( samples, channels, p, sizeof( uint8_t ) );
1654 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, p );
1656 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1657 if ( p != audio_buf_1 )
1658 mlt_pool_release( p );
1663 // Extract the audio channels according to channel mapping
1664 int dest_offset = 0; // channel offset into interleaved dest buffer
1666 // Get the number of channels for this stream
1667 sprintf( key, "channels.%d", i );
1668 int current_channels = mlt_properties_get_int( properties, key );
1670 // Clear the destination audio buffer.
1672 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1674 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1676 // For each output channel
1677 while ( dest_offset < current_channels && j < total_channels )
1679 int map_start = -1, map_channels = 0;
1680 int source_offset = 0;
1683 // Look for a mapping that starts at j
1684 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1686 sprintf( key, "%d.channels", k );
1687 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1688 sprintf( key, "%d.start", k );
1689 if ( mlt_properties_get( frame_meta_properties, key ) )
1690 map_start = mlt_properties_get_int( frame_meta_properties, key );
1691 if ( map_start != j )
1692 source_offset += map_channels;
1696 if ( map_start != j )
1698 map_channels = current_channels;
1702 // Copy samples if source offset valid
1703 if ( source_offset < channels )
1705 // Interleave the audio buffer with the # channels for this stream/mapping.
1706 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1708 void *src = audio_buf_1 + source_offset * sample_bytes;
1709 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1710 int s = samples + 1;
1713 memcpy( dest, src, sample_bytes );
1714 dest += current_channels * sample_bytes;
1715 src += channels * sample_bytes;
1719 // Otherwise silence
1722 j += current_channels;
1723 dest_offset += current_channels;
1726 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1729 // Write the compressed frame in the media file
1730 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1732 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1733 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame pts %"PRId64,
1734 stream->index, pkt.pts, codec->coded_frame->pts );
1736 pkt.flags |= PKT_FLAG_KEY;
1737 pkt.stream_index = stream->index;
1738 pkt.data = audio_outbuf;
1742 if ( av_interleaved_write_frame( oc, &pkt ) )
1744 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1745 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1746 goto on_fatal_error;
1750 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1753 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1762 else if ( video_st )
1765 if ( mlt_deque_count( queue ) )
1767 int out_size, ret = 0;
1770 frame = mlt_deque_pop_front( queue );
1771 frame_properties = MLT_FRAME_PROPERTIES( frame );
1773 c = video_st->codec;
1775 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1781 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1785 // Convert the mlt frame to an AVPicture
1786 for ( i = 0; i < height; i ++ )
1788 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1789 memcpy( p, q, width * 2 );
1793 // Do the colour space conversion
1795 int flags = SWS_BICUBIC;
1797 flags |= SWS_CPU_CAPS_MMX;
1800 flags |= SWS_CPU_CAPS_MMX2;
1802 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1803 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1804 sws_scale( context, (const uint8_t* const*) input->data, input->linesize, 0, height,
1805 output->data, output->linesize);
1806 sws_freeContext( context );
1808 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1811 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1813 // Apply the alpha if applicable
1814 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1816 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1819 for ( i = 0; i < height; i ++ )
1821 n = ( width + 7 ) / 8;
1822 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1826 case 0: do { *p = *alpha++; p += 4;
1827 case 7: *p = *alpha++; p += 4;
1828 case 6: *p = *alpha++; p += 4;
1829 case 5: *p = *alpha++; p += 4;
1830 case 4: *p = *alpha++; p += 4;
1831 case 3: *p = *alpha++; p += 4;
1832 case 2: *p = *alpha++; p += 4;
1833 case 1: *p = *alpha++; p += 4;
1841 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1843 // raw video case. The API will change slightly in the near future for that
1845 av_init_packet(&pkt);
1847 // Set frame interlace hints
1848 c->coded_frame->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1849 c->coded_frame->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1851 pkt.flags |= PKT_FLAG_KEY;
1852 pkt.stream_index= video_st->index;
1853 pkt.data= (uint8_t *)output;
1854 pkt.size= sizeof(AVPicture);
1856 ret = av_write_frame(oc, &pkt);
1857 video_pts += c->frame_size;
1862 output->quality = c->global_quality;
1864 // Set frame interlace hints
1865 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1866 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1867 output->pts = frame_count;
1870 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1872 // If zero size, it means the image was buffered
1876 av_init_packet( &pkt );
1878 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1879 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1880 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %"PRId64" frame pts %"PRId64, pkt.pts, c->coded_frame->pts );
1881 if( c->coded_frame && c->coded_frame->key_frame )
1882 pkt.flags |= PKT_FLAG_KEY;
1883 pkt.stream_index= video_st->index;
1884 pkt.data= video_outbuf;
1887 // write the compressed frame in the media file
1888 ret = av_interleaved_write_frame(oc, &pkt);
1889 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1890 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1892 // Dual pass logging
1893 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1894 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1896 else if ( out_size < 0 )
1898 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1904 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1905 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1906 goto on_fatal_error;
1908 mlt_frame_close( frame );
1917 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1919 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1920 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1923 if ( real_time_output == 1 && frames % 2 == 0 )
1925 long passed = time_difference( &ante );
1928 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
1931 if ( passed < total_time )
1933 long total = ( total_time - passed );
1934 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1935 nanosleep( &t, NULL );
1940 // Flush the encoder buffers
1941 if ( real_time_output <= 0 )
1944 // TODO: flush all audio streams
1945 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1947 AVCodecContext *c = audio_st[0]->codec;
1949 av_init_packet( &pkt );
1953 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) / sample_bytes ) )
1955 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size * sample_bytes );
1956 void* p = audio_buf_1;
1957 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1958 if ( c->sample_fmt == AV_SAMPLE_FMT_FLTP )
1959 p = interleaved_to_planar( audio_input_frame_size, channels, p, sizeof( float ) );
1960 else if ( c->sample_fmt == AV_SAMPLE_FMT_S16P )
1961 p = interleaved_to_planar( audio_input_frame_size, channels, p, sizeof( int16_t ) );
1962 else if ( c->sample_fmt == AV_SAMPLE_FMT_S32P )
1963 p = interleaved_to_planar( audio_input_frame_size, channels, p, sizeof( int32_t ) );
1964 else if ( c->sample_fmt == AV_SAMPLE_FMT_U8P )
1965 p = interleaved_to_planar( audio_input_frame_size, channels, p, sizeof( uint8_t ) );
1967 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, p );
1968 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1969 if ( p != audio_buf_1 )
1970 mlt_pool_release( p );
1973 if ( pkt.size <= 0 )
1974 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1975 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1976 if ( pkt.size <= 0 )
1979 // Write the compressed frame in the media file
1980 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1981 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1982 pkt.flags |= PKT_FLAG_KEY;
1983 pkt.stream_index = audio_st[0]->index;
1984 pkt.data = audio_outbuf;
1985 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1987 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1988 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1989 goto on_fatal_error;
1994 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1996 AVCodecContext *c = video_st->codec;
1998 av_init_packet( &pkt );
2001 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
2002 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
2003 if ( pkt.size <= 0 )
2006 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
2007 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
2008 if( c->coded_frame && c->coded_frame->key_frame )
2009 pkt.flags |= PKT_FLAG_KEY;
2010 pkt.stream_index = video_st->index;
2011 pkt.data = video_outbuf;
2013 // write the compressed frame in the media file
2014 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
2016 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
2017 mlt_events_fire( properties, "consumer-fatal-error", NULL );
2018 goto on_fatal_error;
2020 // Dual pass logging
2021 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
2022 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
2028 // Write the trailer, if any
2030 av_write_trailer( oc );
2034 close_video(oc, video_st);
2035 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
2036 close_audio( oc, audio_st[i] );
2039 for ( i = 0; i < oc->nb_streams; i++ )
2040 av_freep( &oc->streams[i] );
2042 // Close the output file
2043 if ( !( fmt->flags & AVFMT_NOFILE ) &&
2044 !mlt_properties_get_int( properties, "redirect" ) )
2046 #if LIBAVFORMAT_VERSION_MAJOR >= 53
2047 if ( oc->pb ) avio_close( oc->pb );
2048 #elif LIBAVFORMAT_VERSION_MAJOR >= 52
2049 if ( oc->pb ) url_fclose( oc->pb );
2051 url_fclose( &oc->pb );
2055 // Clean up input and output frames
2057 av_free( output->data[0] );
2059 av_free( input->data[0] );
2061 av_free( video_outbuf );
2062 av_free( audio_buf_1 );
2063 av_free( audio_buf_2 );
2068 // Just in case we terminated on pause
2069 mlt_consumer_stopped( consumer );
2070 mlt_properties_close( frame_meta_properties );
2072 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
2074 // Remove the dual pass log file
2075 if ( mlt_properties_get( properties, "_logfilename" ) )
2076 remove( mlt_properties_get( properties, "_logfilename" ) );
2078 // Remove the x264 dual pass logs
2079 char *cwd = getcwd( NULL, 0 );
2080 const char *file = "x264_2pass.log";
2081 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2082 sprintf( full, "%s/%s", cwd, file );
2085 file = "x264_2pass.log.temp";
2086 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2087 sprintf( full, "%s/%s", cwd, file );
2090 file = "x264_2pass.log.mbtree";
2091 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2092 sprintf( full, "%s/%s", cwd, file );
2096 remove( "x264_2pass.log.temp" );
2099 while ( ( frame = mlt_deque_pop_back( queue ) ) )
2100 mlt_frame_close( frame );
2105 /** Close the consumer.
2108 static void consumer_close( mlt_consumer consumer )
2110 // Stop the consumer
2111 mlt_consumer_stop( consumer );
2114 mlt_consumer_close( consumer );