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_S16 SAMPLE_FMT_S16
54 # define AV_SAMPLE_FMT_S32 SAMPLE_FMT_S32
55 # define AV_SAMPLE_FMT_FLT SAMPLE_FMT_FLT
58 #if LIBAVUTIL_VERSION_INT < (50<<16)
59 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
60 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
63 #if LIBAVCODEC_VERSION_MAJOR >= 53
64 #include <libavutil/opt.h>
65 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
66 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
67 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
69 #include <libavcodec/opt.h>
72 #define MAX_AUDIO_STREAMS (8)
73 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
74 #define AUDIO_BUFFER_SIZE (1024 * 42)
75 #define VIDEO_BUFFER_SIZE (2048 * 1024)
78 // This structure should be extended and made globally available in mlt
90 *sample_fifo, sample_fifo_s;
92 sample_fifo sample_fifo_init( int frequency, int channels )
94 sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
95 fifo->frequency = frequency;
96 fifo->channels = channels;
100 // count is the number of samples multiplied by the number of bytes per sample
101 void sample_fifo_append( sample_fifo fifo, uint8_t *samples, int count )
103 if ( ( fifo->size - fifo->used ) < count )
105 fifo->size += count * 5;
106 fifo->buffer = realloc( fifo->buffer, fifo->size );
109 memcpy( &fifo->buffer[ fifo->used ], samples, count );
113 int sample_fifo_used( sample_fifo fifo )
118 int sample_fifo_fetch( sample_fifo fifo, uint8_t *samples, int count )
120 if ( count > fifo->used )
123 memcpy( samples, fifo->buffer, count );
125 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used );
127 fifo->time += ( double )count / fifo->channels / fifo->frequency;
132 void sample_fifo_close( sample_fifo fifo )
134 free( fifo->buffer );
138 // Forward references.
139 static int consumer_start( mlt_consumer consumer );
140 static int consumer_stop( mlt_consumer consumer );
141 static int consumer_is_stopped( mlt_consumer consumer );
142 static void *consumer_thread( void *arg );
143 static void consumer_close( mlt_consumer consumer );
145 /** Initialise the consumer.
148 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
150 // Allocate the consumer
151 mlt_consumer consumer = mlt_consumer_new( profile );
153 // If memory allocated and initialises without error
154 if ( consumer != NULL )
156 // Get properties from the consumer
157 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
159 // Assign close callback
160 consumer->close = consumer_close;
162 // Interpret the argument
164 mlt_properties_set( properties, "target", arg );
166 // sample and frame queue
167 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
169 // Audio options not fully handled by AVOptions
170 #define QSCALE_NONE (-99999)
171 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
173 // Video options not fully handled by AVOptions
174 mlt_properties_set_int( properties, "dc", 8 );
176 // Muxer options not fully handled by AVOptions
177 mlt_properties_set_double( properties, "muxdelay", 0.7 );
178 mlt_properties_set_double( properties, "muxpreload", 0.5 );
180 // Some AVOption defaults we like
181 mlt_properties_set( properties, "strict", "experimental" );
183 // Ensure termination at end of the stream
184 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
186 // Default to separate processing threads for producer and consumer with no frame dropping!
187 mlt_properties_set_int( properties, "real_time", -1 );
188 mlt_properties_set_int( properties, "prefill", 1 );
190 // Set up start/stop/terminated callbacks
191 consumer->start = consumer_start;
192 consumer->stop = consumer_stop;
193 consumer->is_stopped = consumer_is_stopped;
195 mlt_events_register( properties, "consumer-fatal-error", NULL );
202 /** Start the consumer.
205 static int consumer_start( mlt_consumer consumer )
207 // Get the properties
208 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
211 // Report information about available muxers and codecs as YAML Tiny
212 char *s = mlt_properties_get( properties, "f" );
213 if ( s && strcmp( s, "list" ) == 0 )
215 mlt_properties doc = mlt_properties_new();
216 mlt_properties formats = mlt_properties_new();
218 AVOutputFormat *format = NULL;
220 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
221 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
222 while ( ( format = av_oformat_next( format ) ) )
224 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
225 mlt_properties_set( formats, key, format->name );
227 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
228 mlt_properties_close( doc );
231 s = mlt_properties_get( properties, "acodec" );
232 if ( s && strcmp( s, "list" ) == 0 )
234 mlt_properties doc = mlt_properties_new();
235 mlt_properties codecs = mlt_properties_new();
237 AVCodec *codec = NULL;
239 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
240 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
241 while ( ( codec = av_codec_next( codec ) ) )
242 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
244 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
245 mlt_properties_set( codecs, key, codec->name );
247 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
248 mlt_properties_close( doc );
251 s = mlt_properties_get( properties, "vcodec" );
252 if ( s && strcmp( s, "list" ) == 0 )
254 mlt_properties doc = mlt_properties_new();
255 mlt_properties codecs = mlt_properties_new();
257 AVCodec *codec = NULL;
259 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
260 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
261 while ( ( codec = av_codec_next( codec ) ) )
262 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
264 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
265 mlt_properties_set( codecs, key, codec->name );
267 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
268 mlt_properties_close( doc );
272 // Check that we're not already running
273 if ( !error && !mlt_properties_get_int( properties, "running" ) )
276 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
278 // Get the width and height
279 int width = mlt_properties_get_int( properties, "width" );
280 int height = mlt_properties_get_int( properties, "height" );
282 // Obtain the size property
283 char *size = mlt_properties_get( properties, "s" );
289 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
296 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Invalid size property %s - ignoring.\n", size );
300 // Now ensure we honour the multiple of two requested by libavformat
301 width = ( width / 2 ) * 2;
302 height = ( height / 2 ) * 2;
303 mlt_properties_set_int( properties, "width", width );
304 mlt_properties_set_int( properties, "height", height );
306 // We need to set these on the profile as well because the s property is
307 // an alias to mlt properties that correspond to profile settings.
308 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
311 profile->width = width;
312 profile->height = height;
315 // Handle the ffmpeg command line "-r" property for frame rate
316 if ( mlt_properties_get( properties, "r" ) )
318 double frame_rate = mlt_properties_get_double( properties, "r" );
319 AVRational rational = av_d2q( frame_rate, 255 );
320 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
321 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
324 profile->frame_rate_num = rational.num;
325 profile->frame_rate_den = rational.den;
326 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
330 // Apply AVOptions that are synonyms for standard mlt_consumer options
331 if ( mlt_properties_get( properties, "ac" ) )
332 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
333 if ( mlt_properties_get( properties, "ar" ) )
334 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
336 // Assign the thread to properties
337 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
339 // Set the running state
340 mlt_properties_set_int( properties, "running", 1 );
343 pthread_create( thread, NULL, consumer_thread, consumer );
348 /** Stop the consumer.
351 static int consumer_stop( mlt_consumer consumer )
353 // Get the properties
354 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
356 // Check that we're running
357 if ( mlt_properties_get_int( properties, "running" ) )
360 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
363 mlt_properties_set_int( properties, "running", 0 );
365 // Wait for termination
366 pthread_join( *thread, NULL );
372 /** Determine if the consumer is stopped.
375 static int consumer_is_stopped( mlt_consumer consumer )
377 // Get the properties
378 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
379 return !mlt_properties_get_int( properties, "running" );
382 /** Process properties as AVOptions and apply to AV context obj
385 static void apply_properties( void *obj, mlt_properties properties, int flags )
388 int count = mlt_properties_count( properties );
389 #if LIBAVUTIL_VERSION_INT < ((51<<16)+(12<<8)+0)
393 for ( i = 0; i < count; i++ )
395 const char *opt_name = mlt_properties_get_name( properties, i );
396 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(7<<8)+0)
397 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
399 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
402 // If option not found, see if it was prefixed with a or v (-vb)
404 ( opt_name[0] == 'v' && ( flags & AV_OPT_FLAG_VIDEO_PARAM ) ) ||
405 ( opt_name[0] == 'a' && ( flags & AV_OPT_FLAG_AUDIO_PARAM ) ) ) )
406 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(7<<8)+0)
407 opt = av_opt_find( obj, ++opt_name, NULL, flags, flags );
409 opt = av_find_opt( obj, ++opt_name, NULL, flags, flags );
411 // Apply option if found
413 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
414 av_opt_set( obj, opt_name, mlt_properties_get_value( properties, i), 0 );
415 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
416 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
417 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
418 av_set_string2( obj, opt_name, mlt_properties_get_value( properties, i), alloc );
420 av_set_string( obj, opt_name, mlt_properties_get_value( properties, i) );
425 static int get_mlt_audio_format( int av_sample_fmt )
427 switch ( av_sample_fmt )
429 case AV_SAMPLE_FMT_S32:
430 return mlt_audio_s32le;
431 case AV_SAMPLE_FMT_FLT:
432 return mlt_audio_f32le;
433 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
434 case AV_SAMPLE_FMT_S32P:
435 return mlt_audio_s32;
436 case AV_SAMPLE_FMT_FLTP:
437 return mlt_audio_float;
440 return mlt_audio_s16;
444 static int pick_sample_fmt( mlt_properties properties, AVCodec *codec )
446 int sample_fmt = AV_SAMPLE_FMT_S16;
447 const char *format = mlt_properties_get( properties, "mlt_audio_format" );
448 const int *p = codec->sample_fmts;
450 // get default av_sample_fmt from mlt_audio_format
453 if ( !strcmp( format, "s32le" ) )
454 sample_fmt = AV_SAMPLE_FMT_S32;
455 else if ( !strcmp( format, "f32le" ) )
456 sample_fmt = AV_SAMPLE_FMT_FLT;
457 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
458 else if ( !strcmp( format, "s32" ) )
459 sample_fmt = AV_SAMPLE_FMT_S32P;
460 else if ( !strcmp( format, "float" ) )
461 sample_fmt = AV_SAMPLE_FMT_FLTP;
464 // check if codec supports our mlt_audio_format
465 for ( ; *p != -1; p++ )
467 if ( *p == sample_fmt )
470 // no match - pick first one we support
471 for ( p = codec->sample_fmts; *p != -1; p++ )
475 case AV_SAMPLE_FMT_S16:
476 case AV_SAMPLE_FMT_S32:
477 case AV_SAMPLE_FMT_FLT:
478 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
479 case AV_SAMPLE_FMT_S32P:
480 case AV_SAMPLE_FMT_FLTP:
487 mlt_log_error( properties, "audio codec sample_fmt not compatible" );
489 return AV_SAMPLE_FMT_NONE;
492 /** Add an audio output stream
495 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec, int channels )
497 // Get the properties
498 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
500 // Create a new stream
501 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
502 AVStream *st = avformat_new_stream( oc, codec );
504 AVStream *st = av_new_stream( oc, oc->nb_streams );
507 // If created, then initialise from properties
510 AVCodecContext *c = st->codec;
512 // Establish defaults from AVOptions
513 #if LIBAVCODEC_VERSION_MAJOR >= 53
514 avcodec_get_context_defaults3( c, codec );
516 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
519 c->codec_id = codec->id;
520 c->codec_type = CODEC_TYPE_AUDIO;
521 c->sample_fmt = pick_sample_fmt( properties, codec );
523 #if 0 // disabled until some audio codecs are multi-threaded
524 // Setup multi-threading
525 int thread_count = mlt_properties_get_int( properties, "threads" );
526 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
527 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
528 if ( thread_count > 1 )
529 c->thread_count = thread_count;
532 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
533 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
535 // Allow the user to override the audio fourcc
536 if ( mlt_properties_get( properties, "atag" ) )
539 char *arg = mlt_properties_get( properties, "atag" );
540 int tag = strtol( arg, &tail, 0);
542 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
546 // Process properties as AVOptions
547 char *apre = mlt_properties_get( properties, "apre" );
550 mlt_properties p = mlt_properties_load( apre );
551 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
552 mlt_properties_close( p );
554 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
556 int audio_qscale = mlt_properties_get_int( properties, "aq" );
557 if ( audio_qscale > QSCALE_NONE )
559 c->flags |= CODEC_FLAG_QSCALE;
560 c->global_quality = FF_QP2LAMBDA * audio_qscale;
561 #if LIBAVFORMAT_VERSION_MAJOR < 53
562 st->quality = c->global_quality;
566 // Set parameters controlled by MLT
567 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
568 c->time_base = ( AVRational ){ 1, c->sample_rate };
569 c->channels = channels;
571 if ( mlt_properties_get( properties, "alang" ) != NULL )
572 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
573 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
574 av_dict_set( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
576 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
580 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
585 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
591 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
593 // We will return the audio input size from here
594 int audio_input_frame_size = 0;
597 AVCodecContext *c = st->codec;
602 codec = avcodec_find_encoder_by_name( codec_name );
604 codec = avcodec_find_encoder( c->codec_id );
606 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
607 // Process properties as AVOptions on the AVCodec
608 if ( codec && codec->priv_class )
610 char *apre = mlt_properties_get( properties, "apre" );
611 if ( !c->priv_data && codec->priv_data_size )
613 c->priv_data = av_mallocz( codec->priv_data_size );
614 *(const AVClass **) c->priv_data = codec->priv_class;
615 // av_opt_set_defaults( c );
619 mlt_properties p = mlt_properties_load( apre );
620 apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
621 mlt_properties_close( p );
623 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
627 // Continue if codec found and we can open it
628 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
629 if ( codec && avcodec_open2( c, codec, NULL ) >= 0 )
631 if ( codec && avcodec_open( c, codec ) >= 0 )
634 // ugly hack for PCM codecs (will be removed ASAP with new PCM
635 // support to compute the input frame size in samples
636 if ( c->frame_size <= 1 )
638 audio_input_frame_size = audio_outbuf_size / c->channels;
639 switch(st->codec->codec_id)
641 case CODEC_ID_PCM_S16LE:
642 case CODEC_ID_PCM_S16BE:
643 case CODEC_ID_PCM_U16LE:
644 case CODEC_ID_PCM_U16BE:
645 audio_input_frame_size >>= 1;
653 audio_input_frame_size = c->frame_size;
656 // Some formats want stream headers to be seperate (hmm)
657 if ( !strcmp( oc->oformat->name, "mp4" ) ||
658 !strcmp( oc->oformat->name, "mov" ) ||
659 !strcmp( oc->oformat->name, "3gp" ) )
660 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
664 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
667 return audio_input_frame_size;
670 static void close_audio( AVFormatContext *oc, AVStream *st )
672 if ( st && st->codec )
673 avcodec_close( st->codec );
676 /** Add a video output stream
679 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
681 // Get the properties
682 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
684 // Create a new stream
685 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
686 AVStream *st = avformat_new_stream( oc, codec );
688 AVStream *st = av_new_stream( oc, oc->nb_streams );
693 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
694 AVCodecContext *c = st->codec;
696 // Establish defaults from AVOptions
697 #if LIBAVCODEC_VERSION_MAJOR >= 53
698 avcodec_get_context_defaults3( c, codec );
700 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
703 c->codec_id = codec->id;
704 c->codec_type = CODEC_TYPE_VIDEO;
706 // Setup multi-threading
707 int thread_count = mlt_properties_get_int( properties, "threads" );
708 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
709 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
710 if ( thread_count > 1 )
711 #if LIBAVCODEC_VERSION_MAJOR >= 53
712 c->thread_count = thread_count;
714 avcodec_thread_init( c, thread_count );
717 // Process properties as AVOptions
718 char *vpre = mlt_properties_get( properties, "vpre" );
721 mlt_properties p = mlt_properties_load( vpre );
723 if ( mlt_properties_count( p ) < 1 )
725 AVCodec *codec = avcodec_find_encoder( c->codec_id );
728 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
729 strcpy( path, AVDATADIR );
730 strcat( path, codec->name );
732 strcat( path, vpre );
733 strcat( path, ".ffpreset" );
735 mlt_properties_close( p );
736 p = mlt_properties_load( path );
737 if ( mlt_properties_count( p ) > 0 )
738 mlt_properties_debug( p, path, stderr );
744 mlt_properties_debug( p, vpre, stderr );
747 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
748 mlt_properties_close( p );
750 int colorspace = mlt_properties_get_int( properties, "colorspace" );
751 mlt_properties_set( properties, "colorspace", NULL );
752 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
753 mlt_properties_set_int( properties, "colorspace", colorspace );
755 // Set options controlled by MLT
756 c->width = mlt_properties_get_int( properties, "width" );
757 c->height = mlt_properties_get_int( properties, "height" );
758 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
759 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
760 if ( st->time_base.den == 0 )
761 st->time_base = c->time_base;
762 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
763 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
765 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
768 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
769 switch ( colorspace )
772 c->colorspace = AVCOL_SPC_SMPTE170M;
775 c->colorspace = AVCOL_SPC_SMPTE240M;
778 c->colorspace = AVCOL_SPC_BT470BG;
781 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
784 c->colorspace = AVCOL_SPC_BT709;
789 if ( mlt_properties_get( properties, "aspect" ) )
791 // "-aspect" on ffmpeg command line is display aspect ratio
792 double ar = mlt_properties_get_double( properties, "aspect" );
793 AVRational rational = av_d2q( ar, 255 );
795 // Update the profile and properties as well since this is an alias
796 // for mlt properties that correspond to profile settings
797 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
798 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
799 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
802 profile->display_aspect_num = rational.num;
803 profile->display_aspect_den = rational.den;
804 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
807 // Now compute the sample aspect ratio
808 rational = av_d2q( ar * c->height / c->width, 255 );
809 c->sample_aspect_ratio = rational;
810 // Update the profile and properties as well since this is an alias
811 // for mlt properties that correspond to profile settings
812 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
813 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
816 profile->sample_aspect_num = rational.num;
817 profile->sample_aspect_den = rational.den;
818 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
823 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
824 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
826 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
827 st->sample_aspect_ratio = c->sample_aspect_ratio;
830 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
832 c->flags |= CODEC_FLAG_QSCALE;
833 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
834 #if LIBAVFORMAT_VERSION_MAJOR < 53
835 st->quality = c->global_quality;
839 // Allow the user to override the video fourcc
840 if ( mlt_properties_get( properties, "vtag" ) )
843 const char *arg = mlt_properties_get( properties, "vtag" );
844 int tag = strtol( arg, &tail, 0);
846 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
850 // Some formats want stream headers to be seperate
851 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
852 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
854 // Translate these standard mlt consumer properties to ffmpeg
855 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
856 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
858 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
859 c->flags |= CODEC_FLAG_INTERLACED_DCT;
860 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
861 c->flags |= CODEC_FLAG_INTERLACED_ME;
864 // parse the ratecontrol override string
866 char *rc_override = mlt_properties_get( properties, "rc_override" );
867 for ( i = 0; rc_override; i++ )
870 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
872 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
873 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
874 c->rc_override[i].start_frame = start;
875 c->rc_override[i].end_frame = end;
878 c->rc_override[i].qscale = q;
879 c->rc_override[i].quality_factor = 1.0;
883 c->rc_override[i].qscale = 0;
884 c->rc_override[i].quality_factor = -q / 100.0;
886 rc_override = strchr( rc_override, '/' );
890 c->rc_override_count = i;
891 if ( !c->rc_initial_buffer_occupancy )
892 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
893 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
896 i = mlt_properties_get_int( properties, "pass" );
898 c->flags |= CODEC_FLAG_PASS1;
900 c->flags |= CODEC_FLAG_PASS2;
901 if ( codec->id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
903 char logfilename[1024];
908 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
909 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
910 if ( c->flags & CODEC_FLAG_PASS1 )
912 f = fopen( logfilename, "w" );
914 perror( logfilename );
916 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
920 /* read the log file */
921 f = fopen( logfilename, "r" );
928 mlt_properties_set( properties, "_logfilename", logfilename );
929 fseek( f, 0, SEEK_END );
931 fseek( f, 0, SEEK_SET );
932 logbuffer = av_malloc( size + 1 );
934 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
937 size = fread( logbuffer, 1, size, f );
939 logbuffer[size] = '\0';
940 c->stats_in = logbuffer;
948 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
954 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
957 AVFrame *picture = avcodec_alloc_frame();
959 // Determine size of the
960 int size = avpicture_get_size(pix_fmt, width, height);
962 // Allocate the picture buf
963 uint8_t *picture_buf = av_malloc(size);
965 // If we have both, then fill the image
966 if ( picture != NULL && picture_buf != NULL )
968 // Fill the frame with the allocated buffer
969 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
973 // Something failed - clean up what we can
975 av_free( picture_buf );
982 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
985 AVCodecContext *video_enc = st->codec;
987 // find the video encoder
990 codec = avcodec_find_encoder_by_name( codec_name );
992 codec = avcodec_find_encoder( video_enc->codec_id );
994 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
995 // Process properties as AVOptions on the AVCodec
996 if ( codec && codec->priv_class )
998 char *vpre = mlt_properties_get( properties, "vpre" );
999 if ( !video_enc->priv_data && codec->priv_data_size )
1001 video_enc->priv_data = av_mallocz( codec->priv_data_size );
1002 *(const AVClass **) video_enc->priv_data = codec->priv_class;
1003 // av_opt_set_defaults( video_enc );
1007 mlt_properties p = mlt_properties_load( vpre );
1008 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1009 mlt_properties_close( p );
1011 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1015 if( codec && codec->pix_fmts )
1017 const enum PixelFormat *p = codec->pix_fmts;
1018 for( ; *p!=-1; p++ )
1020 if( *p == video_enc->pix_fmt )
1024 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1027 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1028 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1030 int result = codec && avcodec_open( video_enc, codec ) >= 0;
1036 void close_video(AVFormatContext *oc, AVStream *st)
1038 if ( st && st->codec )
1040 av_freep( &st->codec->stats_in );
1041 avcodec_close(st->codec);
1045 static inline long time_difference( struct timeval *time1 )
1047 struct timeval time2;
1048 gettimeofday( &time2, NULL );
1049 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1052 static int mlt_write(void *h, uint8_t *buf, int size)
1054 mlt_properties properties = (mlt_properties) h;
1055 mlt_events_fire( properties, "avformat-write", buf, size, NULL );
1059 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1061 listener( owner, service, (uint8_t*) args[0], (int) args[1] );
1065 /** The main thread - the argument is simply the consumer.
1068 static void *consumer_thread( void *arg )
1070 // Map the argument to the object
1071 mlt_consumer consumer = arg;
1073 // Get the properties
1074 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1076 // Get the terminate on pause property
1077 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1080 // Determine if feed is slow (for realtime stuff)
1081 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1084 struct timeval ante;
1086 // Get the frame rate
1087 double fps = mlt_properties_get_double( properties, "fps" );
1089 // Get width and height
1090 int width = mlt_properties_get_int( properties, "width" );
1091 int height = mlt_properties_get_int( properties, "height" );
1092 int img_width = width;
1093 int img_height = height;
1095 // Get default audio properties
1096 int channels = mlt_properties_get_int( properties, "channels" );
1097 int total_channels = channels;
1098 int frequency = mlt_properties_get_int( properties, "frequency" );
1102 // AVFormat audio buffer and frame size
1103 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1104 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1105 int audio_input_frame_size = 0;
1107 // AVFormat video buffer and frame count
1108 int frame_count = 0;
1109 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1110 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1112 // Used for the frame properties
1113 mlt_frame frame = NULL;
1114 mlt_properties frame_properties = NULL;
1117 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1118 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1120 // Need two av pictures for converting
1121 AVFrame *output = NULL;
1122 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
1124 // For receiving images from an mlt_frame
1126 mlt_image_format img_fmt = mlt_image_yuv422;
1128 // For receiving audio samples back from the fifo
1129 uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1130 uint8_t *audio_buf_2 = NULL;
1133 // Allocate the context
1134 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
1135 AVFormatContext *oc = avformat_alloc_context( );
1137 AVFormatContext *oc = av_alloc_format_context( );
1141 AVStream *video_st = NULL;
1142 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1145 double audio_pts = 0;
1146 double video_pts = 0;
1148 // Frames dispatched
1149 long int frames = 0;
1150 long int total_time = 0;
1152 // Determine the format
1153 AVOutputFormat *fmt = NULL;
1154 const char *filename = mlt_properties_get( properties, "target" );
1155 char *format = mlt_properties_get( properties, "f" );
1156 char *vcodec = mlt_properties_get( properties, "vcodec" );
1157 char *acodec = mlt_properties_get( properties, "acodec" );
1158 AVCodec *audio_codec = NULL;
1159 AVCodec *video_codec = NULL;
1161 // Used to store and override codec ids
1167 mlt_properties frame_meta_properties = mlt_properties_new();
1169 // Initialize audio_st
1170 int i = MAX_AUDIO_STREAMS;
1174 // Check for user selected format first
1175 if ( format != NULL )
1176 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1177 fmt = guess_format( format, NULL, NULL );
1179 fmt = av_guess_format( format, NULL, NULL );
1182 // Otherwise check on the filename
1183 if ( fmt == NULL && filename != NULL )
1184 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1185 fmt = guess_format( NULL, filename, NULL );
1187 fmt = av_guess_format( NULL, filename, NULL );
1190 // Otherwise default to mpeg
1192 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1193 fmt = guess_format( "mpeg", NULL, NULL );
1195 fmt = av_guess_format( "mpeg", NULL, NULL );
1198 // We need a filename - default to stdout?
1199 if ( filename == NULL || !strcmp( filename, "" ) )
1202 // Get the codec ids selected
1203 audio_codec_id = fmt->audio_codec;
1204 video_codec_id = fmt->video_codec;
1206 // Check for audio codec overides
1207 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1208 audio_codec_id = CODEC_ID_NONE;
1211 audio_codec = avcodec_find_encoder_by_name( acodec );
1214 audio_codec_id = audio_codec->id;
1215 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1217 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1218 acodec = mlt_properties_get( properties, "_acodec" );
1219 audio_codec = avcodec_find_encoder_by_name( acodec );
1224 audio_codec_id = CODEC_ID_NONE;
1225 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1230 audio_codec = avcodec_find_encoder( audio_codec_id );
1233 // Check for video codec overides
1234 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1235 video_codec_id = CODEC_ID_NONE;
1238 video_codec = avcodec_find_encoder_by_name( vcodec );
1241 video_codec_id = video_codec->id;
1245 video_codec_id = CODEC_ID_NONE;
1246 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1251 video_codec = avcodec_find_encoder( video_codec_id );
1255 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1256 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1258 char *name = mlt_properties_get_name( properties, i );
1259 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1261 char *key = strdup( name + 10 );
1262 char *markup = strrchr( key, '.' );
1263 if ( markup && !strcmp( markup, ".markup") )
1266 if ( !strstr( key, ".stream." ) )
1267 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1268 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1269 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1271 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1274 av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1284 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1285 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1287 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1288 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1290 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1291 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1293 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1294 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1296 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1297 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1299 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1300 if (metavalue != 0) oc->year = metavalue;
1302 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1303 if (metavalue != 0) oc->track = metavalue;
1307 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1309 // Get a frame now, so we can set some AVOptions from properties.
1310 frame = mlt_consumer_rt_frame( consumer );
1312 // Set the timecode from the MLT metadata if available.
1315 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1316 if ( timecode && strcmp( timecode, "" ) )
1318 mlt_properties_set( properties, "timecode", timecode );
1319 if ( strchr( timecode, ';' ) )
1320 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1324 // Add audio and video streams
1325 if ( video_codec_id != CODEC_ID_NONE )
1326 video_st = add_video_stream( consumer, oc, video_codec );
1327 if ( audio_codec_id != CODEC_ID_NONE )
1333 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1335 sprintf( key, "channels.%d", i );
1336 int j = mlt_properties_get_int( properties, key );
1340 total_channels += j;
1341 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1347 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1348 total_channels = channels;
1351 mlt_properties_set_int( properties, "channels", total_channels );
1353 // Audio format is determined when adding the audio stream
1354 mlt_audio_format aud_fmt = mlt_audio_none;
1356 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1357 int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1358 sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1360 // Set the parameters (even though we have none...)
1361 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1362 if ( av_set_parameters(oc, NULL) >= 0 )
1365 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1366 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1367 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1369 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1371 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1373 // Process properties as AVOptions
1374 char *fpre = mlt_properties_get( properties, "fpre" );
1377 mlt_properties p = mlt_properties_load( fpre );
1378 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1379 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1380 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1381 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1383 mlt_properties_close( p );
1385 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1386 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1387 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1388 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1391 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1393 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1395 audio_input_frame_size = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1396 acodec? acodec : NULL );
1397 if ( !audio_input_frame_size )
1401 // Setup custom I/O if redirecting
1402 if ( mlt_properties_get_int( properties, "redirect" ) )
1404 int buffer_size = 32768;
1405 unsigned char *buffer = av_malloc( buffer_size );
1406 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1407 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1409 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1414 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1415 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1417 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1418 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1419 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1424 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1427 // Open the output file, if needed
1428 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1430 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1431 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1433 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1436 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1437 mlt_properties_set_int( properties, "running", 0 );
1441 // Write the stream header.
1442 if ( mlt_properties_get_int( properties, "running" ) )
1443 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1444 avformat_write_header( oc, NULL );
1446 av_write_header( oc );
1449 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1452 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1453 mlt_properties_set_int( properties, "running", 0 );
1459 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1461 // Last check - need at least one stream
1462 if ( !audio_st[0] && !video_st )
1463 mlt_properties_set_int( properties, "running", 0 );
1465 // Get the starting time (can ignore the times above)
1466 gettimeofday( &ante, NULL );
1468 // Loop while running
1469 while( mlt_properties_get_int( properties, "running" ) &&
1470 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1473 frame = mlt_consumer_rt_frame( consumer );
1475 // Check that we have a frame to work with
1476 if ( frame != NULL )
1478 // Increment frames dispatched
1481 // Default audio args
1482 frame_properties = MLT_FRAME_PROPERTIES( frame );
1484 // Check for the terminated condition
1485 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1487 // Get audio and append to the fifo
1488 if ( !terminated && audio_st[0] )
1490 samples = mlt_sample_calculator( fps, frequency, count ++ );
1491 channels = total_channels;
1492 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1494 // Save the audio channel remap properties for later
1495 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1497 // Create the fifo if we don't have one
1500 fifo = sample_fifo_init( frequency, channels );
1501 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1504 // Silence if not normal forward speed
1505 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1506 memset( pcm, 0, samples * channels * sample_bytes );
1508 // Append the samples
1509 sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1510 total_time += ( samples * 1000000 ) / frequency;
1513 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1517 if ( !terminated && video_st )
1518 mlt_deque_push_back( queue, frame );
1520 mlt_frame_close( frame );
1524 // While we have stuff to process, process...
1527 // Write interleaved audio and video frames
1528 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1531 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) / sample_bytes )
1533 int j = 0; // channel offset into interleaved source buffer
1534 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1536 // Get the audio samples
1539 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1541 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1543 // This prevents an infinite loop when some versions of vorbis do not
1544 // increment pts when encoding silence.
1545 audio_pts = video_pts;
1550 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1552 samples = n / channels;
1554 // For each output stream
1555 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1557 AVStream *stream = audio_st[i];
1558 AVCodecContext *codec = stream->codec;
1561 av_init_packet( &pkt );
1563 // Optimized for single track and no channel remap
1564 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1566 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_1 );
1570 // Extract the audio channels according to channel mapping
1571 int dest_offset = 0; // channel offset into interleaved dest buffer
1573 // Get the number of channels for this stream
1574 sprintf( key, "channels.%d", i );
1575 int current_channels = mlt_properties_get_int( properties, key );
1577 // Clear the destination audio buffer.
1579 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1581 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1583 // For each output channel
1584 while ( dest_offset < current_channels && j < total_channels )
1586 int map_start = -1, map_channels = 0;
1587 int source_offset = 0;
1590 // Look for a mapping that starts at j
1591 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1593 sprintf( key, "%d.channels", k );
1594 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1595 sprintf( key, "%d.start", k );
1596 if ( mlt_properties_get( frame_meta_properties, key ) )
1597 map_start = mlt_properties_get_int( frame_meta_properties, key );
1598 if ( map_start != j )
1599 source_offset += map_channels;
1603 if ( map_start != j )
1605 map_channels = current_channels;
1609 // Copy samples if source offset valid
1610 if ( source_offset < channels )
1612 // Interleave the audio buffer with the # channels for this stream/mapping.
1613 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1615 void *src = audio_buf_1 + source_offset * sample_bytes;
1616 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1617 int s = samples + 1;
1620 memcpy( dest, src, sample_bytes );
1621 dest += current_channels * sample_bytes;
1622 src += channels * sample_bytes;
1626 // Otherwise silence
1629 j += current_channels;
1630 dest_offset += current_channels;
1633 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1636 // Write the compressed frame in the media file
1637 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1639 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1640 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame pts %"PRId64,
1641 stream->index, pkt.pts, codec->coded_frame->pts );
1643 pkt.flags |= PKT_FLAG_KEY;
1644 pkt.stream_index = stream->index;
1645 pkt.data = audio_outbuf;
1649 if ( av_interleaved_write_frame( oc, &pkt ) )
1651 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1652 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1653 goto on_fatal_error;
1657 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1660 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1669 else if ( video_st )
1672 if ( mlt_deque_count( queue ) )
1674 int out_size, ret = 0;
1677 frame = mlt_deque_pop_front( queue );
1678 frame_properties = MLT_FRAME_PROPERTIES( frame );
1680 c = video_st->codec;
1682 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1688 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1692 // Convert the mlt frame to an AVPicture
1693 for ( i = 0; i < height; i ++ )
1695 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1696 memcpy( p, q, width * 2 );
1700 // Do the colour space conversion
1702 int flags = SWS_BILINEAR;
1704 flags |= SWS_CPU_CAPS_MMX;
1707 flags |= SWS_CPU_CAPS_MMX2;
1709 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1710 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1711 sws_scale( context, (const uint8_t* const*) input->data, input->linesize, 0, height,
1712 output->data, output->linesize);
1713 sws_freeContext( context );
1715 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1718 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1720 // Apply the alpha if applicable
1721 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1723 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1726 for ( i = 0; i < height; i ++ )
1728 n = ( width + 7 ) / 8;
1729 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1733 case 0: do { *p = *alpha++; p += 4;
1734 case 7: *p = *alpha++; p += 4;
1735 case 6: *p = *alpha++; p += 4;
1736 case 5: *p = *alpha++; p += 4;
1737 case 4: *p = *alpha++; p += 4;
1738 case 3: *p = *alpha++; p += 4;
1739 case 2: *p = *alpha++; p += 4;
1740 case 1: *p = *alpha++; p += 4;
1748 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1750 // raw video case. The API will change slightly in the near future for that
1752 av_init_packet(&pkt);
1754 pkt.flags |= PKT_FLAG_KEY;
1755 pkt.stream_index= video_st->index;
1756 pkt.data= (uint8_t *)output;
1757 pkt.size= sizeof(AVPicture);
1759 ret = av_write_frame(oc, &pkt);
1760 video_pts += c->frame_size;
1765 output->quality = c->global_quality;
1767 // Set frame interlace hints
1768 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1769 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1770 output->pts = frame_count;
1773 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1775 // If zero size, it means the image was buffered
1779 av_init_packet( &pkt );
1781 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1782 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1783 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %"PRId64" frame pts %"PRId64, pkt.pts, c->coded_frame->pts );
1784 if( c->coded_frame && c->coded_frame->key_frame )
1785 pkt.flags |= PKT_FLAG_KEY;
1786 pkt.stream_index= video_st->index;
1787 pkt.data= video_outbuf;
1790 // write the compressed frame in the media file
1791 ret = av_interleaved_write_frame(oc, &pkt);
1792 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1793 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1795 // Dual pass logging
1796 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1797 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1799 else if ( out_size < 0 )
1801 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1807 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1808 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1809 goto on_fatal_error;
1811 mlt_frame_close( frame );
1820 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1822 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1823 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1826 if ( real_time_output == 1 && frames % 2 == 0 )
1828 long passed = time_difference( &ante );
1831 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
1834 if ( passed < total_time )
1836 long total = ( total_time - passed );
1837 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1838 nanosleep( &t, NULL );
1843 // Flush the encoder buffers
1844 if ( real_time_output <= 0 )
1847 // TODO: flush all audio streams
1848 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1850 AVCodecContext *c = audio_st[0]->codec;
1852 av_init_packet( &pkt );
1855 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1856 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) / sample_bytes ) )
1858 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size * sample_bytes );
1859 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, (short*) audio_buf_1 );
1861 if ( pkt.size <= 0 )
1862 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1863 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1864 if ( pkt.size <= 0 )
1867 // Write the compressed frame in the media file
1868 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1869 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1870 pkt.flags |= PKT_FLAG_KEY;
1871 pkt.stream_index = audio_st[0]->index;
1872 pkt.data = audio_outbuf;
1873 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1875 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1876 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1877 goto on_fatal_error;
1882 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1884 AVCodecContext *c = video_st->codec;
1886 av_init_packet( &pkt );
1889 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1890 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1891 if ( pkt.size <= 0 )
1894 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1895 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1896 if( c->coded_frame && c->coded_frame->key_frame )
1897 pkt.flags |= PKT_FLAG_KEY;
1898 pkt.stream_index = video_st->index;
1899 pkt.data = video_outbuf;
1901 // write the compressed frame in the media file
1902 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1904 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1905 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1906 goto on_fatal_error;
1908 // Dual pass logging
1909 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1910 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1916 // Write the trailer, if any
1917 av_write_trailer( oc );
1921 close_video(oc, video_st);
1922 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1923 close_audio( oc, audio_st[i] );
1926 for ( i = 0; i < oc->nb_streams; i++ )
1927 av_freep( &oc->streams[i] );
1929 // Close the output file
1930 if ( !( fmt->flags & AVFMT_NOFILE ) )
1932 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1933 if ( !mlt_properties_get_int( properties, "redirect" ) )
1934 avio_close( oc->pb );
1935 #elif LIBAVFORMAT_VERSION_MAJOR >= 52
1936 url_fclose( oc->pb );
1938 url_fclose( &oc->pb );
1942 // Clean up input and output frames
1944 av_free( output->data[0] );
1946 av_free( input->data[0] );
1948 av_free( video_outbuf );
1949 av_free( audio_buf_1 );
1950 av_free( audio_buf_2 );
1955 // Just in case we terminated on pause
1956 mlt_properties_set_int( properties, "running", 0 );
1958 mlt_consumer_stopped( consumer );
1959 mlt_properties_close( frame_meta_properties );
1961 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1963 // Remove the dual pass log file
1964 if ( mlt_properties_get( properties, "_logfilename" ) )
1965 remove( mlt_properties_get( properties, "_logfilename" ) );
1967 // Remove the x264 dual pass logs
1968 char *cwd = getcwd( NULL, 0 );
1969 const char *file = "x264_2pass.log";
1970 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1971 sprintf( full, "%s/%s", cwd, file );
1974 file = "x264_2pass.log.temp";
1975 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1976 sprintf( full, "%s/%s", cwd, file );
1979 file = "x264_2pass.log.mbtree";
1980 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1981 sprintf( full, "%s/%s", cwd, file );
1985 remove( "x264_2pass.log.temp" );
1988 while ( ( frame = mlt_deque_pop_back( queue ) ) )
1989 mlt_frame_close( frame );
1994 /** Close the consumer.
1997 static void consumer_close( mlt_consumer consumer )
1999 // Stop the consumer
2000 mlt_consumer_stop( consumer );
2003 mlt_consumer_close( consumer );