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 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
49 #include <libavutil/samplefmt.h>
51 #include <libavutil/mathematics.h>
53 #if LIBAVUTIL_VERSION_INT < (50<<16)
54 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
55 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
58 #if LIBAVCODEC_VERSION_MAJOR >= 53
59 #include <libavutil/opt.h>
60 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
61 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
62 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
64 #include <libavcodec/opt.h>
67 #define MAX_AUDIO_STREAMS (8)
68 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
69 #define AUDIO_BUFFER_SIZE (1024 * 42)
70 #define VIDEO_BUFFER_SIZE (2048 * 1024)
73 // This structure should be extended and made globally available in mlt
85 *sample_fifo, sample_fifo_s;
87 sample_fifo sample_fifo_init( int frequency, int channels )
89 sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
90 fifo->frequency = frequency;
91 fifo->channels = channels;
95 // count is the number of samples multiplied by the number of bytes per sample
96 void sample_fifo_append( sample_fifo fifo, uint8_t *samples, int count )
98 if ( ( fifo->size - fifo->used ) < count )
100 fifo->size += count * 5;
101 fifo->buffer = realloc( fifo->buffer, fifo->size );
104 memcpy( &fifo->buffer[ fifo->used ], samples, count );
108 int sample_fifo_used( sample_fifo fifo )
113 int sample_fifo_fetch( sample_fifo fifo, uint8_t *samples, int count )
115 if ( count > fifo->used )
118 memcpy( samples, fifo->buffer, count );
120 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used );
122 fifo->time += ( double )count / fifo->channels / fifo->frequency;
127 void sample_fifo_close( sample_fifo fifo )
129 free( fifo->buffer );
133 // Forward references.
134 static int consumer_start( mlt_consumer consumer );
135 static int consumer_stop( mlt_consumer consumer );
136 static int consumer_is_stopped( mlt_consumer consumer );
137 static void *consumer_thread( void *arg );
138 static void consumer_close( mlt_consumer consumer );
140 /** Initialise the consumer.
143 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
145 // Allocate the consumer
146 mlt_consumer consumer = mlt_consumer_new( profile );
148 // If memory allocated and initialises without error
149 if ( consumer != NULL )
151 // Get properties from the consumer
152 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
154 // Assign close callback
155 consumer->close = consumer_close;
157 // Interpret the argument
159 mlt_properties_set( properties, "target", arg );
161 // sample and frame queue
162 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
164 // Audio options not fully handled by AVOptions
165 #define QSCALE_NONE (-99999)
166 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
168 // Video options not fully handled by AVOptions
169 mlt_properties_set_int( properties, "dc", 8 );
171 // Muxer options not fully handled by AVOptions
172 mlt_properties_set_double( properties, "muxdelay", 0.7 );
173 mlt_properties_set_double( properties, "muxpreload", 0.5 );
175 // Some AVOption defaults we like
176 mlt_properties_set( properties, "strict", "experimental" );
178 // Ensure termination at end of the stream
179 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
181 // Default to separate processing threads for producer and consumer with no frame dropping!
182 mlt_properties_set_int( properties, "real_time", -1 );
183 mlt_properties_set_int( properties, "prefill", 1 );
185 // Set up start/stop/terminated callbacks
186 consumer->start = consumer_start;
187 consumer->stop = consumer_stop;
188 consumer->is_stopped = consumer_is_stopped;
190 mlt_events_register( properties, "consumer-fatal-error", NULL );
197 /** Start the consumer.
200 static int consumer_start( mlt_consumer consumer )
202 // Get the properties
203 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
206 // Report information about available muxers and codecs as YAML Tiny
207 char *s = mlt_properties_get( properties, "f" );
208 if ( s && strcmp( s, "list" ) == 0 )
210 mlt_properties doc = mlt_properties_new();
211 mlt_properties formats = mlt_properties_new();
213 AVOutputFormat *format = NULL;
215 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
216 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
217 while ( ( format = av_oformat_next( format ) ) )
219 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
220 mlt_properties_set( formats, key, format->name );
222 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
223 mlt_properties_close( doc );
226 s = mlt_properties_get( properties, "acodec" );
227 if ( s && strcmp( s, "list" ) == 0 )
229 mlt_properties doc = mlt_properties_new();
230 mlt_properties codecs = mlt_properties_new();
232 AVCodec *codec = NULL;
234 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
235 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
236 while ( ( codec = av_codec_next( codec ) ) )
237 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
239 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
240 mlt_properties_set( codecs, key, codec->name );
242 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
243 mlt_properties_close( doc );
246 s = mlt_properties_get( properties, "vcodec" );
247 if ( s && strcmp( s, "list" ) == 0 )
249 mlt_properties doc = mlt_properties_new();
250 mlt_properties codecs = mlt_properties_new();
252 AVCodec *codec = NULL;
254 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
255 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
256 while ( ( codec = av_codec_next( codec ) ) )
257 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
259 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
260 mlt_properties_set( codecs, key, codec->name );
262 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
263 mlt_properties_close( doc );
267 // Check that we're not already running
268 if ( !error && !mlt_properties_get_int( properties, "running" ) )
271 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
273 // Get the width and height
274 int width = mlt_properties_get_int( properties, "width" );
275 int height = mlt_properties_get_int( properties, "height" );
277 // Obtain the size property
278 char *size = mlt_properties_get( properties, "s" );
284 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
291 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Invalid size property %s - ignoring.\n", size );
295 // Now ensure we honour the multiple of two requested by libavformat
296 width = ( width / 2 ) * 2;
297 height = ( height / 2 ) * 2;
298 mlt_properties_set_int( properties, "width", width );
299 mlt_properties_set_int( properties, "height", height );
301 // We need to set these on the profile as well because the s property is
302 // an alias to mlt properties that correspond to profile settings.
303 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
306 profile->width = width;
307 profile->height = height;
310 // Handle the ffmpeg command line "-r" property for frame rate
311 if ( mlt_properties_get( properties, "r" ) )
313 double frame_rate = mlt_properties_get_double( properties, "r" );
314 AVRational rational = av_d2q( frame_rate, 255 );
315 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
316 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
319 profile->frame_rate_num = rational.num;
320 profile->frame_rate_den = rational.den;
321 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
325 // Apply AVOptions that are synonyms for standard mlt_consumer options
326 if ( mlt_properties_get( properties, "ac" ) )
327 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
328 if ( mlt_properties_get( properties, "ar" ) )
329 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
331 // Assign the thread to properties
332 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
334 // Set the running state
335 mlt_properties_set_int( properties, "running", 1 );
338 pthread_create( thread, NULL, consumer_thread, consumer );
343 /** Stop the consumer.
346 static int consumer_stop( mlt_consumer consumer )
348 // Get the properties
349 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
351 // Check that we're running
352 if ( mlt_properties_get_int( properties, "running" ) )
355 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
358 mlt_properties_set_int( properties, "running", 0 );
360 // Wait for termination
361 pthread_join( *thread, NULL );
367 /** Determine if the consumer is stopped.
370 static int consumer_is_stopped( mlt_consumer consumer )
372 // Get the properties
373 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
374 return !mlt_properties_get_int( properties, "running" );
377 /** Process properties as AVOptions and apply to AV context obj
380 static void apply_properties( void *obj, mlt_properties properties, int flags )
383 int count = mlt_properties_count( properties );
384 #if LIBAVUTIL_VERSION_INT < ((51<<16)+(12<<8)+0)
388 for ( i = 0; i < count; i++ )
390 const char *opt_name = mlt_properties_get_name( properties, i );
391 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(7<<8)+0)
392 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
394 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
397 // If option not found, see if it was prefixed with a or v (-vb)
399 ( opt_name[0] == 'v' && ( flags & AV_OPT_FLAG_VIDEO_PARAM ) ) ||
400 ( opt_name[0] == 'a' && ( flags & AV_OPT_FLAG_AUDIO_PARAM ) ) ) )
401 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(7<<8)+0)
402 opt = av_opt_find( obj, ++opt_name, NULL, flags, flags );
404 opt = av_find_opt( obj, ++opt_name, NULL, flags, flags );
406 // Apply option if found
408 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
409 av_opt_set( obj, opt_name, mlt_properties_get_value( properties, i), 0 );
410 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
411 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
412 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
413 av_set_string2( obj, opt_name, mlt_properties_get_value( properties, i), alloc );
415 av_set_string( obj, opt_name, mlt_properties_get_value( properties, i) );
420 static int get_mlt_audio_format( int av_sample_fmt )
422 switch ( av_sample_fmt )
424 case AV_SAMPLE_FMT_S32:
425 return mlt_audio_s32le;
426 case AV_SAMPLE_FMT_FLT:
427 return mlt_audio_f32le;
428 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
429 case AV_SAMPLE_FMT_S32P:
430 return mlt_audio_s32;
431 case AV_SAMPLE_FMT_FLTP:
432 return mlt_audio_float;
435 return mlt_audio_s16;
439 static int pick_sample_fmt( mlt_properties properties, AVCodec *codec )
441 int sample_fmt = AV_SAMPLE_FMT_S16;
442 const char *format = mlt_properties_get( properties, "mlt_audio_format" );
443 const int *p = codec->sample_fmts;
445 // get default av_sample_fmt from mlt_audio_format
448 if ( !strcmp( format, "s32le" ) )
449 sample_fmt = AV_SAMPLE_FMT_S32;
450 else if ( !strcmp( format, "f32le" ) )
451 sample_fmt = AV_SAMPLE_FMT_FLT;
452 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
453 else if ( !strcmp( format, "s32" ) )
454 sample_fmt = AV_SAMPLE_FMT_S32P;
455 else if ( !strcmp( format, "float" ) )
456 sample_fmt = AV_SAMPLE_FMT_FLTP;
459 // check if codec supports our mlt_audio_format
460 for ( ; *p != -1; p++ )
462 if ( *p == sample_fmt )
465 // no match - pick first one we support
466 for ( p = codec->sample_fmts; *p != -1; p++ )
470 case AV_SAMPLE_FMT_S16:
471 case AV_SAMPLE_FMT_S32:
472 case AV_SAMPLE_FMT_FLT:
473 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
474 case AV_SAMPLE_FMT_S32P:
475 case AV_SAMPLE_FMT_FLTP:
482 mlt_log_error( properties, "audio codec sample_fmt not compatible" );
484 return AV_SAMPLE_FMT_NONE;
487 /** Add an audio output stream
490 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec, int channels )
492 // Get the properties
493 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
495 // Create a new stream
496 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
497 AVStream *st = avformat_new_stream( oc, codec );
499 AVStream *st = av_new_stream( oc, oc->nb_streams );
502 // If created, then initialise from properties
505 AVCodecContext *c = st->codec;
507 // Establish defaults from AVOptions
508 #if LIBAVCODEC_VERSION_MAJOR >= 53
509 avcodec_get_context_defaults3( c, codec );
511 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
514 c->codec_id = codec->id;
515 c->codec_type = CODEC_TYPE_AUDIO;
516 c->sample_fmt = pick_sample_fmt( properties, codec );
518 #if 0 // disabled until some audio codecs are multi-threaded
519 // Setup multi-threading
520 int thread_count = mlt_properties_get_int( properties, "threads" );
521 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
522 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
523 if ( thread_count > 1 )
524 c->thread_count = thread_count;
527 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
528 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
530 // Allow the user to override the audio fourcc
531 if ( mlt_properties_get( properties, "atag" ) )
534 char *arg = mlt_properties_get( properties, "atag" );
535 int tag = strtol( arg, &tail, 0);
537 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
541 // Process properties as AVOptions
542 char *apre = mlt_properties_get( properties, "apre" );
545 mlt_properties p = mlt_properties_load( apre );
546 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
547 mlt_properties_close( p );
549 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
551 int audio_qscale = mlt_properties_get_int( properties, "aq" );
552 if ( audio_qscale > QSCALE_NONE )
554 c->flags |= CODEC_FLAG_QSCALE;
555 c->global_quality = FF_QP2LAMBDA * audio_qscale;
556 #if LIBAVFORMAT_VERSION_MAJOR < 53
557 st->quality = c->global_quality;
561 // Set parameters controlled by MLT
562 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
563 c->time_base = ( AVRational ){ 1, c->sample_rate };
564 c->channels = channels;
566 if ( mlt_properties_get( properties, "alang" ) != NULL )
567 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
568 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
569 av_dict_set( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
571 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
575 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
580 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
586 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
588 // We will return the audio input size from here
589 int audio_input_frame_size = 0;
592 AVCodecContext *c = st->codec;
597 codec = avcodec_find_encoder_by_name( codec_name );
599 codec = avcodec_find_encoder( c->codec_id );
601 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
602 // Process properties as AVOptions on the AVCodec
603 if ( codec && codec->priv_class )
605 char *apre = mlt_properties_get( properties, "apre" );
606 if ( !c->priv_data && codec->priv_data_size )
608 c->priv_data = av_mallocz( codec->priv_data_size );
609 *(const AVClass **) c->priv_data = codec->priv_class;
610 // av_opt_set_defaults( c );
614 mlt_properties p = mlt_properties_load( apre );
615 apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
616 mlt_properties_close( p );
618 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
622 // Continue if codec found and we can open it
623 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
624 if ( codec && avcodec_open2( c, codec, NULL ) >= 0 )
626 if ( codec && avcodec_open( c, codec ) >= 0 )
629 // ugly hack for PCM codecs (will be removed ASAP with new PCM
630 // support to compute the input frame size in samples
631 if ( c->frame_size <= 1 )
633 audio_input_frame_size = audio_outbuf_size / c->channels;
634 switch(st->codec->codec_id)
636 case CODEC_ID_PCM_S16LE:
637 case CODEC_ID_PCM_S16BE:
638 case CODEC_ID_PCM_U16LE:
639 case CODEC_ID_PCM_U16BE:
640 audio_input_frame_size >>= 1;
648 audio_input_frame_size = c->frame_size;
651 // Some formats want stream headers to be seperate (hmm)
652 if ( !strcmp( oc->oformat->name, "mp4" ) ||
653 !strcmp( oc->oformat->name, "mov" ) ||
654 !strcmp( oc->oformat->name, "3gp" ) )
655 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
659 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
662 return audio_input_frame_size;
665 static void close_audio( AVFormatContext *oc, AVStream *st )
667 if ( st && st->codec )
668 avcodec_close( st->codec );
671 /** Add a video output stream
674 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
676 // Get the properties
677 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
679 // Create a new stream
680 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
681 AVStream *st = avformat_new_stream( oc, codec );
683 AVStream *st = av_new_stream( oc, oc->nb_streams );
688 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
689 AVCodecContext *c = st->codec;
691 // Establish defaults from AVOptions
692 #if LIBAVCODEC_VERSION_MAJOR >= 53
693 avcodec_get_context_defaults3( c, codec );
695 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
698 c->codec_id = codec->id;
699 c->codec_type = CODEC_TYPE_VIDEO;
701 // Setup multi-threading
702 int thread_count = mlt_properties_get_int( properties, "threads" );
703 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
704 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
705 if ( thread_count > 1 )
706 #if LIBAVCODEC_VERSION_MAJOR >= 53
707 c->thread_count = thread_count;
709 avcodec_thread_init( c, thread_count );
712 // Process properties as AVOptions
713 char *vpre = mlt_properties_get( properties, "vpre" );
716 mlt_properties p = mlt_properties_load( vpre );
718 if ( mlt_properties_count( p ) < 1 )
720 AVCodec *codec = avcodec_find_encoder( c->codec_id );
723 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
724 strcpy( path, AVDATADIR );
725 strcat( path, codec->name );
727 strcat( path, vpre );
728 strcat( path, ".ffpreset" );
730 mlt_properties_close( p );
731 p = mlt_properties_load( path );
732 if ( mlt_properties_count( p ) > 0 )
733 mlt_properties_debug( p, path, stderr );
739 mlt_properties_debug( p, vpre, stderr );
742 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
743 mlt_properties_close( p );
745 int colorspace = mlt_properties_get_int( properties, "colorspace" );
746 mlt_properties_set( properties, "colorspace", NULL );
747 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
748 mlt_properties_set_int( properties, "colorspace", colorspace );
750 // Set options controlled by MLT
751 c->width = mlt_properties_get_int( properties, "width" );
752 c->height = mlt_properties_get_int( properties, "height" );
753 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
754 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
755 if ( st->time_base.den == 0 )
756 st->time_base = c->time_base;
757 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
758 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
760 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
763 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
764 switch ( colorspace )
767 c->colorspace = AVCOL_SPC_SMPTE170M;
770 c->colorspace = AVCOL_SPC_SMPTE240M;
773 c->colorspace = AVCOL_SPC_BT470BG;
776 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
779 c->colorspace = AVCOL_SPC_BT709;
784 if ( mlt_properties_get( properties, "aspect" ) )
786 // "-aspect" on ffmpeg command line is display aspect ratio
787 double ar = mlt_properties_get_double( properties, "aspect" );
788 AVRational rational = av_d2q( ar, 255 );
790 // Update the profile and properties as well since this is an alias
791 // for mlt properties that correspond to profile settings
792 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
793 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
794 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
797 profile->display_aspect_num = rational.num;
798 profile->display_aspect_den = rational.den;
799 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
802 // Now compute the sample aspect ratio
803 rational = av_d2q( ar * c->height / c->width, 255 );
804 c->sample_aspect_ratio = rational;
805 // Update the profile and properties as well since this is an alias
806 // for mlt properties that correspond to profile settings
807 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
808 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
811 profile->sample_aspect_num = rational.num;
812 profile->sample_aspect_den = rational.den;
813 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
818 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
819 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
821 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
822 st->sample_aspect_ratio = c->sample_aspect_ratio;
825 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
827 c->flags |= CODEC_FLAG_QSCALE;
828 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
829 #if LIBAVFORMAT_VERSION_MAJOR < 53
830 st->quality = c->global_quality;
834 // Allow the user to override the video fourcc
835 if ( mlt_properties_get( properties, "vtag" ) )
838 const char *arg = mlt_properties_get( properties, "vtag" );
839 int tag = strtol( arg, &tail, 0);
841 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
845 // Some formats want stream headers to be seperate
846 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
847 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
849 // Translate these standard mlt consumer properties to ffmpeg
850 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
851 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
853 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
854 c->flags |= CODEC_FLAG_INTERLACED_DCT;
855 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
856 c->flags |= CODEC_FLAG_INTERLACED_ME;
859 // parse the ratecontrol override string
861 char *rc_override = mlt_properties_get( properties, "rc_override" );
862 for ( i = 0; rc_override; i++ )
865 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
867 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
868 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
869 c->rc_override[i].start_frame = start;
870 c->rc_override[i].end_frame = end;
873 c->rc_override[i].qscale = q;
874 c->rc_override[i].quality_factor = 1.0;
878 c->rc_override[i].qscale = 0;
879 c->rc_override[i].quality_factor = -q / 100.0;
881 rc_override = strchr( rc_override, '/' );
885 c->rc_override_count = i;
886 if ( !c->rc_initial_buffer_occupancy )
887 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
888 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
891 i = mlt_properties_get_int( properties, "pass" );
893 c->flags |= CODEC_FLAG_PASS1;
895 c->flags |= CODEC_FLAG_PASS2;
896 if ( codec->id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
898 char logfilename[1024];
903 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
904 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
905 if ( c->flags & CODEC_FLAG_PASS1 )
907 f = fopen( logfilename, "w" );
909 perror( logfilename );
911 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
915 /* read the log file */
916 f = fopen( logfilename, "r" );
923 mlt_properties_set( properties, "_logfilename", logfilename );
924 fseek( f, 0, SEEK_END );
926 fseek( f, 0, SEEK_SET );
927 logbuffer = av_malloc( size + 1 );
929 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
932 size = fread( logbuffer, 1, size, f );
934 logbuffer[size] = '\0';
935 c->stats_in = logbuffer;
943 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
949 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
952 AVFrame *picture = avcodec_alloc_frame();
954 // Determine size of the
955 int size = avpicture_get_size(pix_fmt, width, height);
957 // Allocate the picture buf
958 uint8_t *picture_buf = av_malloc(size);
960 // If we have both, then fill the image
961 if ( picture != NULL && picture_buf != NULL )
963 // Fill the frame with the allocated buffer
964 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
968 // Something failed - clean up what we can
970 av_free( picture_buf );
977 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
980 AVCodecContext *video_enc = st->codec;
982 // find the video encoder
985 codec = avcodec_find_encoder_by_name( codec_name );
987 codec = avcodec_find_encoder( video_enc->codec_id );
989 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
990 // Process properties as AVOptions on the AVCodec
991 if ( codec && codec->priv_class )
993 char *vpre = mlt_properties_get( properties, "vpre" );
994 if ( !video_enc->priv_data && codec->priv_data_size )
996 video_enc->priv_data = av_mallocz( codec->priv_data_size );
997 *(const AVClass **) video_enc->priv_data = codec->priv_class;
998 // av_opt_set_defaults( video_enc );
1002 mlt_properties p = mlt_properties_load( vpre );
1003 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1004 mlt_properties_close( p );
1006 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1010 if( codec && codec->pix_fmts )
1012 const enum PixelFormat *p = codec->pix_fmts;
1013 for( ; *p!=-1; p++ )
1015 if( *p == video_enc->pix_fmt )
1019 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1022 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1023 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1025 int result = codec && avcodec_open( video_enc, codec ) >= 0;
1031 void close_video(AVFormatContext *oc, AVStream *st)
1033 if ( st && st->codec )
1035 av_freep( &st->codec->stats_in );
1036 avcodec_close(st->codec);
1040 static inline long time_difference( struct timeval *time1 )
1042 struct timeval time2;
1043 gettimeofday( &time2, NULL );
1044 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1047 static int mlt_write(void *h, uint8_t *buf, int size)
1049 mlt_properties properties = (mlt_properties) h;
1050 mlt_events_fire( properties, "avformat-write", buf, size, NULL );
1054 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1056 listener( owner, service, (uint8_t*) args[0], (int) args[1] );
1060 /** The main thread - the argument is simply the consumer.
1063 static void *consumer_thread( void *arg )
1065 // Map the argument to the object
1066 mlt_consumer consumer = arg;
1068 // Get the properties
1069 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1071 // Get the terminate on pause property
1072 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1075 // Determine if feed is slow (for realtime stuff)
1076 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1079 struct timeval ante;
1081 // Get the frame rate
1082 double fps = mlt_properties_get_double( properties, "fps" );
1084 // Get width and height
1085 int width = mlt_properties_get_int( properties, "width" );
1086 int height = mlt_properties_get_int( properties, "height" );
1087 int img_width = width;
1088 int img_height = height;
1090 // Get default audio properties
1091 int channels = mlt_properties_get_int( properties, "channels" );
1092 int total_channels = channels;
1093 int frequency = mlt_properties_get_int( properties, "frequency" );
1097 // AVFormat audio buffer and frame size
1098 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1099 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1100 int audio_input_frame_size = 0;
1102 // AVFormat video buffer and frame count
1103 int frame_count = 0;
1104 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1105 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1107 // Used for the frame properties
1108 mlt_frame frame = NULL;
1109 mlt_properties frame_properties = NULL;
1112 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1113 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1115 // Need two av pictures for converting
1116 AVFrame *output = NULL;
1117 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
1119 // For receiving images from an mlt_frame
1121 mlt_image_format img_fmt = mlt_image_yuv422;
1123 // For receiving audio samples back from the fifo
1124 uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1125 uint8_t *audio_buf_2 = NULL;
1128 // Allocate the context
1129 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
1130 AVFormatContext *oc = avformat_alloc_context( );
1132 AVFormatContext *oc = av_alloc_format_context( );
1136 AVStream *video_st = NULL;
1137 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1140 double audio_pts = 0;
1141 double video_pts = 0;
1143 // Frames dispatched
1144 long int frames = 0;
1145 long int total_time = 0;
1147 // Determine the format
1148 AVOutputFormat *fmt = NULL;
1149 const char *filename = mlt_properties_get( properties, "target" );
1150 char *format = mlt_properties_get( properties, "f" );
1151 char *vcodec = mlt_properties_get( properties, "vcodec" );
1152 char *acodec = mlt_properties_get( properties, "acodec" );
1153 AVCodec *audio_codec = NULL;
1154 AVCodec *video_codec = NULL;
1156 // Used to store and override codec ids
1162 mlt_properties frame_meta_properties = mlt_properties_new();
1164 // Initialize audio_st
1165 int i = MAX_AUDIO_STREAMS;
1169 // Check for user selected format first
1170 if ( format != NULL )
1171 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1172 fmt = guess_format( format, NULL, NULL );
1174 fmt = av_guess_format( format, NULL, NULL );
1177 // Otherwise check on the filename
1178 if ( fmt == NULL && filename != NULL )
1179 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1180 fmt = guess_format( NULL, filename, NULL );
1182 fmt = av_guess_format( NULL, filename, NULL );
1185 // Otherwise default to mpeg
1187 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1188 fmt = guess_format( "mpeg", NULL, NULL );
1190 fmt = av_guess_format( "mpeg", NULL, NULL );
1193 // We need a filename - default to stdout?
1194 if ( filename == NULL || !strcmp( filename, "" ) )
1197 // Get the codec ids selected
1198 audio_codec_id = fmt->audio_codec;
1199 video_codec_id = fmt->video_codec;
1201 // Check for audio codec overides
1202 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1203 audio_codec_id = CODEC_ID_NONE;
1206 audio_codec = avcodec_find_encoder_by_name( acodec );
1209 audio_codec_id = audio_codec->id;
1210 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1212 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1213 acodec = mlt_properties_get( properties, "_acodec" );
1214 audio_codec = avcodec_find_encoder_by_name( acodec );
1219 audio_codec_id = CODEC_ID_NONE;
1220 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1225 audio_codec = avcodec_find_encoder( audio_codec_id );
1228 // Check for video codec overides
1229 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1230 video_codec_id = CODEC_ID_NONE;
1233 video_codec = avcodec_find_encoder_by_name( vcodec );
1236 video_codec_id = video_codec->id;
1240 video_codec_id = CODEC_ID_NONE;
1241 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1246 video_codec = avcodec_find_encoder( video_codec_id );
1250 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1251 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1253 char *name = mlt_properties_get_name( properties, i );
1254 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1256 char *key = strdup( name + 10 );
1257 char *markup = strrchr( key, '.' );
1258 if ( markup && !strcmp( markup, ".markup") )
1261 if ( !strstr( key, ".stream." ) )
1262 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1263 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1264 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1266 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1269 av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1279 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1280 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1282 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1283 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1285 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1286 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1288 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1289 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1291 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1292 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1294 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1295 if (metavalue != 0) oc->year = metavalue;
1297 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1298 if (metavalue != 0) oc->track = metavalue;
1302 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1304 // Get a frame now, so we can set some AVOptions from properties.
1305 frame = mlt_consumer_rt_frame( consumer );
1307 // Set the timecode from the MLT metadata if available.
1310 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1311 if ( timecode && strcmp( timecode, "" ) )
1313 mlt_properties_set( properties, "timecode", timecode );
1314 if ( strchr( timecode, ';' ) )
1315 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1319 // Add audio and video streams
1320 if ( video_codec_id != CODEC_ID_NONE )
1321 video_st = add_video_stream( consumer, oc, video_codec );
1322 if ( audio_codec_id != CODEC_ID_NONE )
1328 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1330 sprintf( key, "channels.%d", i );
1331 int j = mlt_properties_get_int( properties, key );
1335 total_channels += j;
1336 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1342 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1343 total_channels = channels;
1346 mlt_properties_set_int( properties, "channels", total_channels );
1348 // Audio format is determined when adding the audio stream
1349 mlt_audio_format aud_fmt = mlt_audio_none;
1351 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1352 int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1353 sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1355 // Set the parameters (even though we have none...)
1356 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1357 if ( av_set_parameters(oc, NULL) >= 0 )
1360 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1361 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1362 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1364 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1366 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1368 // Process properties as AVOptions
1369 char *fpre = mlt_properties_get( properties, "fpre" );
1372 mlt_properties p = mlt_properties_load( fpre );
1373 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1374 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1375 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1376 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1378 mlt_properties_close( p );
1380 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1381 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1382 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1383 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1386 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1388 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1390 audio_input_frame_size = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1391 acodec? acodec : NULL );
1392 if ( !audio_input_frame_size )
1396 // Setup custom I/O if redirecting
1397 if ( mlt_properties_get_int( properties, "redirect" ) )
1399 int buffer_size = 32768;
1400 unsigned char *buffer = av_malloc( buffer_size );
1401 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1402 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1404 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1409 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1410 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1412 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1413 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1414 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1419 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1422 // Open the output file, if needed
1423 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1425 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1426 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1428 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1431 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1432 mlt_properties_set_int( properties, "running", 0 );
1436 // Write the stream header.
1437 if ( mlt_properties_get_int( properties, "running" ) )
1438 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1439 avformat_write_header( oc, NULL );
1441 av_write_header( oc );
1444 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1447 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1448 mlt_properties_set_int( properties, "running", 0 );
1454 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1456 // Last check - need at least one stream
1457 if ( !audio_st[0] && !video_st )
1458 mlt_properties_set_int( properties, "running", 0 );
1460 // Get the starting time (can ignore the times above)
1461 gettimeofday( &ante, NULL );
1463 // Loop while running
1464 while( mlt_properties_get_int( properties, "running" ) &&
1465 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1468 frame = mlt_consumer_rt_frame( consumer );
1470 // Check that we have a frame to work with
1471 if ( frame != NULL )
1473 // Increment frames dispatched
1476 // Default audio args
1477 frame_properties = MLT_FRAME_PROPERTIES( frame );
1479 // Check for the terminated condition
1480 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1482 // Get audio and append to the fifo
1483 if ( !terminated && audio_st[0] )
1485 samples = mlt_sample_calculator( fps, frequency, count ++ );
1486 channels = total_channels;
1487 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1489 // Save the audio channel remap properties for later
1490 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1492 // Create the fifo if we don't have one
1495 fifo = sample_fifo_init( frequency, channels );
1496 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1499 // Silence if not normal forward speed
1500 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1501 memset( pcm, 0, samples * channels * sample_bytes );
1503 // Append the samples
1504 sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1505 total_time += ( samples * 1000000 ) / frequency;
1508 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1512 if ( !terminated && video_st )
1513 mlt_deque_push_back( queue, frame );
1515 mlt_frame_close( frame );
1519 // While we have stuff to process, process...
1522 // Write interleaved audio and video frames
1523 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1526 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) / sample_bytes )
1528 int j = 0; // channel offset into interleaved source buffer
1529 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1531 // Get the audio samples
1534 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1536 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1538 // This prevents an infinite loop when some versions of vorbis do not
1539 // increment pts when encoding silence.
1540 audio_pts = video_pts;
1545 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1547 samples = n / channels;
1549 // For each output stream
1550 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1552 AVStream *stream = audio_st[i];
1553 AVCodecContext *codec = stream->codec;
1556 av_init_packet( &pkt );
1558 // Optimized for single track and no channel remap
1559 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1561 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_1 );
1565 // Extract the audio channels according to channel mapping
1566 int dest_offset = 0; // channel offset into interleaved dest buffer
1568 // Get the number of channels for this stream
1569 sprintf( key, "channels.%d", i );
1570 int current_channels = mlt_properties_get_int( properties, key );
1572 // Clear the destination audio buffer.
1574 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1576 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1578 // For each output channel
1579 while ( dest_offset < current_channels && j < total_channels )
1581 int map_start = -1, map_channels = 0;
1582 int source_offset = 0;
1585 // Look for a mapping that starts at j
1586 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1588 sprintf( key, "%d.channels", k );
1589 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1590 sprintf( key, "%d.start", k );
1591 if ( mlt_properties_get( frame_meta_properties, key ) )
1592 map_start = mlt_properties_get_int( frame_meta_properties, key );
1593 if ( map_start != j )
1594 source_offset += map_channels;
1598 if ( map_start != j )
1600 map_channels = current_channels;
1604 // Copy samples if source offset valid
1605 if ( source_offset < channels )
1607 // Interleave the audio buffer with the # channels for this stream/mapping.
1608 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1610 void *src = audio_buf_1 + source_offset * sample_bytes;
1611 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1612 int s = samples + 1;
1615 memcpy( dest, src, sample_bytes );
1616 dest += current_channels * sample_bytes;
1617 src += channels * sample_bytes;
1621 // Otherwise silence
1624 j += current_channels;
1625 dest_offset += current_channels;
1628 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1631 // Write the compressed frame in the media file
1632 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1634 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1635 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame pts %"PRId64,
1636 stream->index, pkt.pts, codec->coded_frame->pts );
1638 pkt.flags |= PKT_FLAG_KEY;
1639 pkt.stream_index = stream->index;
1640 pkt.data = audio_outbuf;
1644 if ( av_interleaved_write_frame( oc, &pkt ) )
1646 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1647 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1648 goto on_fatal_error;
1652 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1655 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1664 else if ( video_st )
1667 if ( mlt_deque_count( queue ) )
1669 int out_size, ret = 0;
1672 frame = mlt_deque_pop_front( queue );
1673 frame_properties = MLT_FRAME_PROPERTIES( frame );
1675 c = video_st->codec;
1677 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1683 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1687 // Convert the mlt frame to an AVPicture
1688 for ( i = 0; i < height; i ++ )
1690 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1691 memcpy( p, q, width * 2 );
1695 // Do the colour space conversion
1697 int flags = SWS_BILINEAR;
1699 flags |= SWS_CPU_CAPS_MMX;
1702 flags |= SWS_CPU_CAPS_MMX2;
1704 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1705 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1706 sws_scale( context, (const uint8_t* const*) input->data, input->linesize, 0, height,
1707 output->data, output->linesize);
1708 sws_freeContext( context );
1710 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1713 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1715 // Apply the alpha if applicable
1716 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1718 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1721 for ( i = 0; i < height; i ++ )
1723 n = ( width + 7 ) / 8;
1724 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1728 case 0: do { *p = *alpha++; p += 4;
1729 case 7: *p = *alpha++; p += 4;
1730 case 6: *p = *alpha++; p += 4;
1731 case 5: *p = *alpha++; p += 4;
1732 case 4: *p = *alpha++; p += 4;
1733 case 3: *p = *alpha++; p += 4;
1734 case 2: *p = *alpha++; p += 4;
1735 case 1: *p = *alpha++; p += 4;
1743 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1745 // raw video case. The API will change slightly in the near future for that
1747 av_init_packet(&pkt);
1749 pkt.flags |= PKT_FLAG_KEY;
1750 pkt.stream_index= video_st->index;
1751 pkt.data= (uint8_t *)output;
1752 pkt.size= sizeof(AVPicture);
1754 ret = av_write_frame(oc, &pkt);
1755 video_pts += c->frame_size;
1760 output->quality = c->global_quality;
1762 // Set frame interlace hints
1763 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1764 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1765 output->pts = frame_count;
1768 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1770 // If zero size, it means the image was buffered
1774 av_init_packet( &pkt );
1776 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1777 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1778 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %"PRId64" frame pts %"PRId64, pkt.pts, c->coded_frame->pts );
1779 if( c->coded_frame && c->coded_frame->key_frame )
1780 pkt.flags |= PKT_FLAG_KEY;
1781 pkt.stream_index= video_st->index;
1782 pkt.data= video_outbuf;
1785 // write the compressed frame in the media file
1786 ret = av_interleaved_write_frame(oc, &pkt);
1787 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1788 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1790 // Dual pass logging
1791 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1792 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1794 else if ( out_size < 0 )
1796 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1802 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1803 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1804 goto on_fatal_error;
1806 mlt_frame_close( frame );
1815 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1817 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1818 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1821 if ( real_time_output == 1 && frames % 2 == 0 )
1823 long passed = time_difference( &ante );
1826 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
1829 if ( passed < total_time )
1831 long total = ( total_time - passed );
1832 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1833 nanosleep( &t, NULL );
1838 // Flush the encoder buffers
1839 if ( real_time_output <= 0 )
1842 // TODO: flush all audio streams
1843 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1845 AVCodecContext *c = audio_st[0]->codec;
1847 av_init_packet( &pkt );
1850 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1851 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) / sample_bytes ) )
1853 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size * sample_bytes );
1854 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, (short*) audio_buf_1 );
1856 if ( pkt.size <= 0 )
1857 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1858 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1859 if ( pkt.size <= 0 )
1862 // Write the compressed frame in the media file
1863 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1864 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1865 pkt.flags |= PKT_FLAG_KEY;
1866 pkt.stream_index = audio_st[0]->index;
1867 pkt.data = audio_outbuf;
1868 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1870 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1871 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1872 goto on_fatal_error;
1877 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1879 AVCodecContext *c = video_st->codec;
1881 av_init_packet( &pkt );
1884 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1885 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1886 if ( pkt.size <= 0 )
1889 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1890 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1891 if( c->coded_frame && c->coded_frame->key_frame )
1892 pkt.flags |= PKT_FLAG_KEY;
1893 pkt.stream_index = video_st->index;
1894 pkt.data = video_outbuf;
1896 // write the compressed frame in the media file
1897 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1899 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1900 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1901 goto on_fatal_error;
1903 // Dual pass logging
1904 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1905 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1911 // Write the trailer, if any
1912 av_write_trailer( oc );
1916 close_video(oc, video_st);
1917 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1918 close_audio( oc, audio_st[i] );
1921 for ( i = 0; i < oc->nb_streams; i++ )
1922 av_freep( &oc->streams[i] );
1924 // Close the output file
1925 if ( !( fmt->flags & AVFMT_NOFILE ) )
1927 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1928 if ( !mlt_properties_get_int( properties, "redirect" ) )
1929 avio_close( oc->pb );
1930 #elif LIBAVFORMAT_VERSION_MAJOR >= 52
1931 url_fclose( oc->pb );
1933 url_fclose( &oc->pb );
1937 // Clean up input and output frames
1939 av_free( output->data[0] );
1941 av_free( input->data[0] );
1943 av_free( video_outbuf );
1944 av_free( audio_buf_1 );
1945 av_free( audio_buf_2 );
1950 // Just in case we terminated on pause
1951 mlt_properties_set_int( properties, "running", 0 );
1953 mlt_consumer_stopped( consumer );
1954 mlt_properties_close( frame_meta_properties );
1956 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1958 // Remove the dual pass log file
1959 if ( mlt_properties_get( properties, "_logfilename" ) )
1960 remove( mlt_properties_get( properties, "_logfilename" ) );
1962 // Remove the x264 dual pass logs
1963 char *cwd = getcwd( NULL, 0 );
1964 const char *file = "x264_2pass.log";
1965 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1966 sprintf( full, "%s/%s", cwd, file );
1969 file = "x264_2pass.log.temp";
1970 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1971 sprintf( full, "%s/%s", cwd, file );
1974 file = "x264_2pass.log.mbtree";
1975 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1976 sprintf( full, "%s/%s", cwd, file );
1980 remove( "x264_2pass.log.temp" );
1983 while ( ( frame = mlt_deque_pop_back( queue ) ) )
1984 mlt_frame_close( frame );
1989 /** Close the consumer.
1992 static void consumer_close( mlt_consumer consumer )
1994 // Stop the consumer
1995 mlt_consumer_stop( consumer );
1998 mlt_consumer_close( consumer );