2 * consumer_avformat.c -- an encoder based on avformat
3 * Copyright (C) 2003-2012 Ushodaya Enterprises Limited
4 * Author: Charles Yates <charles.yates@pandora.be>
5 * Author: Dan Dennedy <dan@dennedy.org>
6 * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include <framework/mlt_consumer.h>
25 #include <framework/mlt_frame.h>
26 #include <framework/mlt_profile.h>
27 #include <framework/mlt_log.h>
28 #include <framework/mlt_events.h>
30 // System header files
39 // avformat header files
40 #include <libavformat/avformat.h>
41 #include <libavformat/avio.h>
43 #include <libswscale/swscale.h>
45 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
46 #include <libavutil/pixdesc.h>
48 #include <libavutil/mathematics.h>
50 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
51 # include <libavutil/samplefmt.h>
53 # define AV_SAMPLE_FMT_NONE SAMPLE_FMT_NONE
54 # define AV_SAMPLE_FMT_S16 SAMPLE_FMT_S16
55 # define AV_SAMPLE_FMT_S32 SAMPLE_FMT_S32
56 # define AV_SAMPLE_FMT_FLT SAMPLE_FMT_FLT
59 #if LIBAVUTIL_VERSION_INT < (50<<16)
60 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
61 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
64 #if LIBAVCODEC_VERSION_MAJOR >= 53
65 #include <libavutil/opt.h>
66 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
67 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
68 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
70 #include <libavcodec/opt.h>
73 #define MAX_AUDIO_STREAMS (8)
74 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
75 #define AUDIO_BUFFER_SIZE (1024 * 42)
76 #define VIDEO_BUFFER_SIZE (2048 * 1024)
79 // This structure should be extended and made globally available in mlt
91 *sample_fifo, sample_fifo_s;
93 sample_fifo sample_fifo_init( int frequency, int channels )
95 sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
96 fifo->frequency = frequency;
97 fifo->channels = channels;
101 // count is the number of samples multiplied by the number of bytes per sample
102 void sample_fifo_append( sample_fifo fifo, uint8_t *samples, int count )
104 if ( ( fifo->size - fifo->used ) < count )
106 fifo->size += count * 5;
107 fifo->buffer = realloc( fifo->buffer, fifo->size );
110 memcpy( &fifo->buffer[ fifo->used ], samples, count );
114 int sample_fifo_used( sample_fifo fifo )
119 int sample_fifo_fetch( sample_fifo fifo, uint8_t *samples, int count )
121 if ( count > fifo->used )
124 memcpy( samples, fifo->buffer, count );
126 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used );
128 fifo->time += ( double )count / fifo->channels / fifo->frequency;
133 void sample_fifo_close( sample_fifo fifo )
135 free( fifo->buffer );
139 // Forward references.
140 static int consumer_start( mlt_consumer consumer );
141 static int consumer_stop( mlt_consumer consumer );
142 static int consumer_is_stopped( mlt_consumer consumer );
143 static void *consumer_thread( void *arg );
144 static void consumer_close( mlt_consumer consumer );
146 /** Initialise the consumer.
149 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
151 // Allocate the consumer
152 mlt_consumer consumer = mlt_consumer_new( profile );
154 // If memory allocated and initialises without error
155 if ( consumer != NULL )
157 // Get properties from the consumer
158 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
160 // Assign close callback
161 consumer->close = consumer_close;
163 // Interpret the argument
165 mlt_properties_set( properties, "target", arg );
167 // sample and frame queue
168 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
170 // Audio options not fully handled by AVOptions
171 #define QSCALE_NONE (-99999)
172 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
174 // Video options not fully handled by AVOptions
175 mlt_properties_set_int( properties, "dc", 8 );
177 // Muxer options not fully handled by AVOptions
178 mlt_properties_set_double( properties, "muxdelay", 0.7 );
179 mlt_properties_set_double( properties, "muxpreload", 0.5 );
181 // Ensure termination at end of the stream
182 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
184 // Default to separate processing threads for producer and consumer with no frame dropping!
185 mlt_properties_set_int( properties, "real_time", -1 );
186 mlt_properties_set_int( properties, "prefill", 1 );
188 // Set up start/stop/terminated callbacks
189 consumer->start = consumer_start;
190 consumer->stop = consumer_stop;
191 consumer->is_stopped = consumer_is_stopped;
193 mlt_events_register( properties, "consumer-fatal-error", NULL );
200 /** Start the consumer.
203 static int consumer_start( mlt_consumer consumer )
205 // Get the properties
206 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
209 // Report information about available muxers and codecs as YAML Tiny
210 char *s = mlt_properties_get( properties, "f" );
211 if ( s && strcmp( s, "list" ) == 0 )
213 mlt_properties doc = mlt_properties_new();
214 mlt_properties formats = mlt_properties_new();
216 AVOutputFormat *format = NULL;
218 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
219 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
220 while ( ( format = av_oformat_next( format ) ) )
222 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
223 mlt_properties_set( formats, key, format->name );
225 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
226 mlt_properties_close( doc );
229 s = mlt_properties_get( properties, "acodec" );
230 if ( s && strcmp( s, "list" ) == 0 )
232 mlt_properties doc = mlt_properties_new();
233 mlt_properties codecs = mlt_properties_new();
235 AVCodec *codec = NULL;
237 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
238 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
239 while ( ( codec = av_codec_next( codec ) ) )
240 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
242 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
243 mlt_properties_set( codecs, key, codec->name );
245 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
246 mlt_properties_close( doc );
249 s = mlt_properties_get( properties, "vcodec" );
250 if ( s && strcmp( s, "list" ) == 0 )
252 mlt_properties doc = mlt_properties_new();
253 mlt_properties codecs = mlt_properties_new();
255 AVCodec *codec = NULL;
257 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
258 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
259 while ( ( codec = av_codec_next( codec ) ) )
260 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
262 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
263 mlt_properties_set( codecs, key, codec->name );
265 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
266 mlt_properties_close( doc );
270 // Check that we're not already running
271 if ( !error && !mlt_properties_get_int( properties, "running" ) )
274 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
276 // Get the width and height
277 int width = mlt_properties_get_int( properties, "width" );
278 int height = mlt_properties_get_int( properties, "height" );
280 // Obtain the size property
281 char *size = mlt_properties_get( properties, "s" );
287 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
294 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Invalid size property %s - ignoring.\n", size );
298 // Now ensure we honour the multiple of two requested by libavformat
299 width = ( width / 2 ) * 2;
300 height = ( height / 2 ) * 2;
301 mlt_properties_set_int( properties, "width", width );
302 mlt_properties_set_int( properties, "height", height );
304 // We need to set these on the profile as well because the s property is
305 // an alias to mlt properties that correspond to profile settings.
306 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
309 profile->width = width;
310 profile->height = height;
313 // Handle the ffmpeg command line "-r" property for frame rate
314 if ( mlt_properties_get( properties, "r" ) )
316 double frame_rate = mlt_properties_get_double( properties, "r" );
317 AVRational rational = av_d2q( frame_rate, 255 );
318 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
319 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
322 profile->frame_rate_num = rational.num;
323 profile->frame_rate_den = rational.den;
324 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
328 // Apply AVOptions that are synonyms for standard mlt_consumer options
329 if ( mlt_properties_get( properties, "ac" ) )
330 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
331 if ( mlt_properties_get( properties, "ar" ) )
332 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
334 // Assign the thread to properties
335 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
337 // Set the running state
338 mlt_properties_set_int( properties, "running", 1 );
341 pthread_create( thread, NULL, consumer_thread, consumer );
346 /** Stop the consumer.
349 static int consumer_stop( mlt_consumer consumer )
351 // Get the properties
352 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
354 // Check that we're running
355 if ( mlt_properties_get_int( properties, "running" ) )
358 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
361 mlt_properties_set_int( properties, "running", 0 );
363 // Wait for termination
364 pthread_join( *thread, NULL );
370 /** Determine if the consumer is stopped.
373 static int consumer_is_stopped( mlt_consumer consumer )
375 // Get the properties
376 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
377 return !mlt_properties_get_int( properties, "running" );
380 /** Process properties as AVOptions and apply to AV context obj
383 static void apply_properties( void *obj, mlt_properties properties, int flags )
386 int count = mlt_properties_count( properties );
387 #if LIBAVUTIL_VERSION_INT < ((51<<16)+(12<<8)+0)
391 for ( i = 0; i < count; i++ )
393 const char *opt_name = mlt_properties_get_name( properties, i );
394 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
395 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
397 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
400 // If option not found, see if it was prefixed with a or v (-vb)
402 ( opt_name[0] == 'v' && ( flags & AV_OPT_FLAG_VIDEO_PARAM ) ) ||
403 ( opt_name[0] == 'a' && ( flags & AV_OPT_FLAG_AUDIO_PARAM ) ) ) )
404 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
405 opt = av_opt_find( obj, ++opt_name, NULL, flags, flags );
407 opt = av_find_opt( obj, ++opt_name, NULL, flags, flags );
409 // Apply option if found
411 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
412 av_opt_set( obj, opt_name, mlt_properties_get_value( properties, i), 0 );
413 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
414 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
415 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
416 av_set_string2( obj, opt_name, mlt_properties_get_value( properties, i), alloc );
418 av_set_string( obj, opt_name, mlt_properties_get_value( properties, i) );
423 static int get_mlt_audio_format( int av_sample_fmt )
425 switch ( av_sample_fmt )
427 case AV_SAMPLE_FMT_S32:
428 return mlt_audio_s32le;
429 case AV_SAMPLE_FMT_FLT:
430 return mlt_audio_f32le;
431 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
432 case AV_SAMPLE_FMT_S32P:
433 return mlt_audio_s32;
434 case AV_SAMPLE_FMT_FLTP:
435 return mlt_audio_float;
438 return mlt_audio_s16;
442 static int pick_sample_fmt( mlt_properties properties, AVCodec *codec )
444 int sample_fmt = AV_SAMPLE_FMT_S16;
445 const char *format = mlt_properties_get( properties, "mlt_audio_format" );
446 const int *p = codec->sample_fmts;
448 // get default av_sample_fmt from mlt_audio_format
451 if ( !strcmp( format, "s32le" ) )
452 sample_fmt = AV_SAMPLE_FMT_S32;
453 else if ( !strcmp( format, "f32le" ) )
454 sample_fmt = AV_SAMPLE_FMT_FLT;
455 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
456 else if ( !strcmp( format, "s32" ) )
457 sample_fmt = AV_SAMPLE_FMT_S32P;
458 else if ( !strcmp( format, "float" ) )
459 sample_fmt = AV_SAMPLE_FMT_FLTP;
462 // check if codec supports our mlt_audio_format
463 for ( ; *p != -1; p++ )
465 if ( *p == sample_fmt )
468 // no match - pick first one we support
469 for ( p = codec->sample_fmts; *p != -1; p++ )
473 case AV_SAMPLE_FMT_S16:
474 case AV_SAMPLE_FMT_S32:
475 case AV_SAMPLE_FMT_FLT:
476 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
477 case AV_SAMPLE_FMT_S32P:
478 case AV_SAMPLE_FMT_FLTP:
485 mlt_log_error( properties, "audio codec sample_fmt not compatible" );
487 return AV_SAMPLE_FMT_NONE;
490 /** Add an audio output stream
493 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec, int channels )
495 // Get the properties
496 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
498 // Create a new stream
499 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
500 AVStream *st = avformat_new_stream( oc, codec );
502 AVStream *st = av_new_stream( oc, oc->nb_streams );
505 // If created, then initialise from properties
508 AVCodecContext *c = st->codec;
510 // Establish defaults from AVOptions
511 #if LIBAVCODEC_VERSION_MAJOR >= 53
512 avcodec_get_context_defaults3( c, codec );
514 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
517 c->codec_id = codec->id;
518 c->codec_type = CODEC_TYPE_AUDIO;
519 c->sample_fmt = pick_sample_fmt( properties, codec );
521 #if 0 // disabled until some audio codecs are multi-threaded
522 // Setup multi-threading
523 int thread_count = mlt_properties_get_int( properties, "threads" );
524 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
525 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
526 if ( thread_count > 1 )
527 c->thread_count = thread_count;
530 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
531 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
533 // Allow the user to override the audio fourcc
534 if ( mlt_properties_get( properties, "atag" ) )
537 char *arg = mlt_properties_get( properties, "atag" );
538 int tag = strtol( arg, &tail, 0);
540 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
544 // Process properties as AVOptions
545 char *apre = mlt_properties_get( properties, "apre" );
548 mlt_properties p = mlt_properties_load( apre );
549 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
550 mlt_properties_close( p );
552 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
554 int audio_qscale = mlt_properties_get_int( properties, "aq" );
555 if ( audio_qscale > QSCALE_NONE )
557 c->flags |= CODEC_FLAG_QSCALE;
558 c->global_quality = FF_QP2LAMBDA * audio_qscale;
559 #if LIBAVFORMAT_VERSION_MAJOR < 53
560 st->quality = c->global_quality;
564 // Set parameters controlled by MLT
565 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
566 c->time_base = ( AVRational ){ 1, c->sample_rate };
567 c->channels = channels;
569 if ( mlt_properties_get( properties, "alang" ) != NULL )
570 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
571 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
572 av_dict_set( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
574 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
578 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
583 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
589 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
591 // We will return the audio input size from here
592 int audio_input_frame_size = 0;
595 AVCodecContext *c = st->codec;
600 codec = avcodec_find_encoder_by_name( codec_name );
602 codec = avcodec_find_encoder( c->codec_id );
604 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
605 // Process properties as AVOptions on the AVCodec
606 if ( codec && codec->priv_class )
608 char *apre = mlt_properties_get( properties, "apre" );
609 if ( !c->priv_data && codec->priv_data_size )
611 c->priv_data = av_mallocz( codec->priv_data_size );
612 *(const AVClass **) c->priv_data = codec->priv_class;
613 // av_opt_set_defaults( c );
617 mlt_properties p = mlt_properties_load( apre );
618 apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
619 mlt_properties_close( p );
621 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
625 // Continue if codec found and we can open it
626 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
627 if ( codec && avcodec_open2( c, codec, NULL ) >= 0 )
629 if ( codec && avcodec_open( c, codec ) >= 0 )
632 // ugly hack for PCM codecs (will be removed ASAP with new PCM
633 // support to compute the input frame size in samples
634 if ( c->frame_size <= 1 )
636 audio_input_frame_size = audio_outbuf_size / c->channels;
637 switch(st->codec->codec_id)
639 case CODEC_ID_PCM_S16LE:
640 case CODEC_ID_PCM_S16BE:
641 case CODEC_ID_PCM_U16LE:
642 case CODEC_ID_PCM_U16BE:
643 audio_input_frame_size >>= 1;
651 audio_input_frame_size = c->frame_size;
654 // Some formats want stream headers to be seperate (hmm)
655 if ( !strcmp( oc->oformat->name, "mp4" ) ||
656 !strcmp( oc->oformat->name, "mov" ) ||
657 !strcmp( oc->oformat->name, "3gp" ) )
658 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
662 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
665 return audio_input_frame_size;
668 static void close_audio( AVFormatContext *oc, AVStream *st )
670 if ( st && st->codec )
671 avcodec_close( st->codec );
674 /** Add a video output stream
677 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
679 // Get the properties
680 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
682 // Create a new stream
683 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
684 AVStream *st = avformat_new_stream( oc, codec );
686 AVStream *st = av_new_stream( oc, oc->nb_streams );
691 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
692 AVCodecContext *c = st->codec;
694 // Establish defaults from AVOptions
695 #if LIBAVCODEC_VERSION_MAJOR >= 53
696 avcodec_get_context_defaults3( c, codec );
698 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
701 c->codec_id = codec->id;
702 c->codec_type = CODEC_TYPE_VIDEO;
704 // Setup multi-threading
705 int thread_count = mlt_properties_get_int( properties, "threads" );
706 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
707 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
708 if ( thread_count > 1 )
709 #if LIBAVCODEC_VERSION_MAJOR >= 53
710 c->thread_count = thread_count;
712 avcodec_thread_init( c, thread_count );
715 // Process properties as AVOptions
716 char *vpre = mlt_properties_get( properties, "vpre" );
719 mlt_properties p = mlt_properties_load( vpre );
721 if ( mlt_properties_count( p ) < 1 )
723 AVCodec *codec = avcodec_find_encoder( c->codec_id );
726 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
727 strcpy( path, AVDATADIR );
728 strcat( path, codec->name );
730 strcat( path, vpre );
731 strcat( path, ".ffpreset" );
733 mlt_properties_close( p );
734 p = mlt_properties_load( path );
735 if ( mlt_properties_count( p ) > 0 )
736 mlt_properties_debug( p, path, stderr );
742 mlt_properties_debug( p, vpre, stderr );
745 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
746 mlt_properties_close( p );
748 int colorspace = mlt_properties_get_int( properties, "colorspace" );
749 mlt_properties_set( properties, "colorspace", NULL );
750 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
751 mlt_properties_set_int( properties, "colorspace", colorspace );
753 // Set options controlled by MLT
754 c->width = mlt_properties_get_int( properties, "width" );
755 c->height = mlt_properties_get_int( properties, "height" );
756 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
757 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
758 if ( st->time_base.den == 0 )
759 st->time_base = c->time_base;
760 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
761 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
763 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
766 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
767 switch ( colorspace )
770 c->colorspace = AVCOL_SPC_SMPTE170M;
773 c->colorspace = AVCOL_SPC_SMPTE240M;
776 c->colorspace = AVCOL_SPC_BT470BG;
779 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
782 c->colorspace = AVCOL_SPC_BT709;
787 if ( mlt_properties_get( properties, "aspect" ) )
789 // "-aspect" on ffmpeg command line is display aspect ratio
790 double ar = mlt_properties_get_double( properties, "aspect" );
791 AVRational rational = av_d2q( ar, 255 );
793 // Update the profile and properties as well since this is an alias
794 // for mlt properties that correspond to profile settings
795 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
796 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
797 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
800 profile->display_aspect_num = rational.num;
801 profile->display_aspect_den = rational.den;
802 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
805 // Now compute the sample aspect ratio
806 rational = av_d2q( ar * c->height / c->width, 255 );
807 c->sample_aspect_ratio = rational;
808 // Update the profile and properties as well since this is an alias
809 // for mlt properties that correspond to profile settings
810 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
811 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
814 profile->sample_aspect_num = rational.num;
815 profile->sample_aspect_den = rational.den;
816 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
821 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
822 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
824 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
825 st->sample_aspect_ratio = c->sample_aspect_ratio;
828 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
830 c->flags |= CODEC_FLAG_QSCALE;
831 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
832 #if LIBAVFORMAT_VERSION_MAJOR < 53
833 st->quality = c->global_quality;
837 // Allow the user to override the video fourcc
838 if ( mlt_properties_get( properties, "vtag" ) )
841 const char *arg = mlt_properties_get( properties, "vtag" );
842 int tag = strtol( arg, &tail, 0);
844 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
848 // Some formats want stream headers to be seperate
849 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
850 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
852 // Translate these standard mlt consumer properties to ffmpeg
853 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
854 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
856 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
857 c->flags |= CODEC_FLAG_INTERLACED_DCT;
858 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
859 c->flags |= CODEC_FLAG_INTERLACED_ME;
862 // parse the ratecontrol override string
864 char *rc_override = mlt_properties_get( properties, "rc_override" );
865 for ( i = 0; rc_override; i++ )
868 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
870 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
871 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
872 c->rc_override[i].start_frame = start;
873 c->rc_override[i].end_frame = end;
876 c->rc_override[i].qscale = q;
877 c->rc_override[i].quality_factor = 1.0;
881 c->rc_override[i].qscale = 0;
882 c->rc_override[i].quality_factor = -q / 100.0;
884 rc_override = strchr( rc_override, '/' );
888 c->rc_override_count = i;
889 if ( !c->rc_initial_buffer_occupancy )
890 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
891 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
894 i = mlt_properties_get_int( properties, "pass" );
896 c->flags |= CODEC_FLAG_PASS1;
898 c->flags |= CODEC_FLAG_PASS2;
899 if ( codec->id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
901 char logfilename[1024];
906 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
907 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
908 if ( c->flags & CODEC_FLAG_PASS1 )
910 f = fopen( logfilename, "w" );
912 perror( logfilename );
914 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
918 /* read the log file */
919 f = fopen( logfilename, "r" );
926 mlt_properties_set( properties, "_logfilename", logfilename );
927 fseek( f, 0, SEEK_END );
929 fseek( f, 0, SEEK_SET );
930 logbuffer = av_malloc( size + 1 );
932 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
935 size = fread( logbuffer, 1, size, f );
937 logbuffer[size] = '\0';
938 c->stats_in = logbuffer;
946 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
952 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
955 AVFrame *picture = avcodec_alloc_frame();
957 // Determine size of the
958 int size = avpicture_get_size(pix_fmt, width, height);
960 // Allocate the picture buf
961 uint8_t *picture_buf = av_malloc(size);
963 // If we have both, then fill the image
964 if ( picture != NULL && picture_buf != NULL )
966 // Fill the frame with the allocated buffer
967 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
971 // Something failed - clean up what we can
973 av_free( picture_buf );
980 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
983 AVCodecContext *video_enc = st->codec;
985 // find the video encoder
988 codec = avcodec_find_encoder_by_name( codec_name );
990 codec = avcodec_find_encoder( video_enc->codec_id );
992 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
993 // Process properties as AVOptions on the AVCodec
994 if ( codec && codec->priv_class )
996 char *vpre = mlt_properties_get( properties, "vpre" );
997 if ( !video_enc->priv_data && codec->priv_data_size )
999 video_enc->priv_data = av_mallocz( codec->priv_data_size );
1000 *(const AVClass **) video_enc->priv_data = codec->priv_class;
1001 // av_opt_set_defaults( video_enc );
1005 mlt_properties p = mlt_properties_load( vpre );
1006 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1007 mlt_properties_close( p );
1009 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1013 if( codec && codec->pix_fmts )
1015 const enum PixelFormat *p = codec->pix_fmts;
1016 for( ; *p!=-1; p++ )
1018 if( *p == video_enc->pix_fmt )
1022 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1025 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1026 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1028 int result = codec && avcodec_open( video_enc, codec ) >= 0;
1034 void close_video(AVFormatContext *oc, AVStream *st)
1036 if ( st && st->codec )
1038 av_freep( &st->codec->stats_in );
1039 avcodec_close(st->codec);
1043 static inline long time_difference( struct timeval *time1 )
1045 struct timeval time2;
1046 gettimeofday( &time2, NULL );
1047 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1050 static int mlt_write(void *h, uint8_t *buf, int size)
1052 mlt_properties properties = (mlt_properties) h;
1053 mlt_events_fire( properties, "avformat-write", buf, size, NULL );
1057 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1059 listener( owner, service, (uint8_t*) args[0], (int) args[1] );
1063 /** The main thread - the argument is simply the consumer.
1066 static void *consumer_thread( void *arg )
1068 // Map the argument to the object
1069 mlt_consumer consumer = arg;
1071 // Get the properties
1072 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1074 // Get the terminate on pause property
1075 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1078 // Determine if feed is slow (for realtime stuff)
1079 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1082 struct timeval ante;
1084 // Get the frame rate
1085 double fps = mlt_properties_get_double( properties, "fps" );
1087 // Get width and height
1088 int width = mlt_properties_get_int( properties, "width" );
1089 int height = mlt_properties_get_int( properties, "height" );
1090 int img_width = width;
1091 int img_height = height;
1093 // Get default audio properties
1094 int channels = mlt_properties_get_int( properties, "channels" );
1095 int total_channels = channels;
1096 int frequency = mlt_properties_get_int( properties, "frequency" );
1100 // AVFormat audio buffer and frame size
1101 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1102 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1103 int audio_input_frame_size = 0;
1105 // AVFormat video buffer and frame count
1106 int frame_count = 0;
1107 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1108 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1110 // Used for the frame properties
1111 mlt_frame frame = NULL;
1112 mlt_properties frame_properties = NULL;
1115 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1116 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1118 // Need two av pictures for converting
1119 AVFrame *output = NULL;
1120 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
1122 // For receiving images from an mlt_frame
1124 mlt_image_format img_fmt = mlt_image_yuv422;
1126 // For receiving audio samples back from the fifo
1127 uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1128 uint8_t *audio_buf_2 = NULL;
1131 // Allocate the context
1132 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
1133 AVFormatContext *oc = avformat_alloc_context( );
1135 AVFormatContext *oc = av_alloc_format_context( );
1139 AVStream *video_st = NULL;
1140 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1143 double audio_pts = 0;
1144 double video_pts = 0;
1146 // Frames dispatched
1147 long int frames = 0;
1148 long int total_time = 0;
1150 // Determine the format
1151 AVOutputFormat *fmt = NULL;
1152 const char *filename = mlt_properties_get( properties, "target" );
1153 char *format = mlt_properties_get( properties, "f" );
1154 char *vcodec = mlt_properties_get( properties, "vcodec" );
1155 char *acodec = mlt_properties_get( properties, "acodec" );
1156 AVCodec *audio_codec = NULL;
1157 AVCodec *video_codec = NULL;
1159 // Used to store and override codec ids
1165 mlt_properties frame_meta_properties = mlt_properties_new();
1167 // Initialize audio_st
1168 int i = MAX_AUDIO_STREAMS;
1172 // Check for user selected format first
1173 if ( format != NULL )
1174 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1175 fmt = guess_format( format, NULL, NULL );
1177 fmt = av_guess_format( format, NULL, NULL );
1180 // Otherwise check on the filename
1181 if ( fmt == NULL && filename != NULL )
1182 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1183 fmt = guess_format( NULL, filename, NULL );
1185 fmt = av_guess_format( NULL, filename, NULL );
1188 // Otherwise default to mpeg
1190 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1191 fmt = guess_format( "mpeg", NULL, NULL );
1193 fmt = av_guess_format( "mpeg", NULL, NULL );
1196 // We need a filename - default to stdout?
1197 if ( filename == NULL || !strcmp( filename, "" ) )
1200 // Get the codec ids selected
1201 audio_codec_id = fmt->audio_codec;
1202 video_codec_id = fmt->video_codec;
1204 // Check for audio codec overides
1205 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1206 audio_codec_id = CODEC_ID_NONE;
1209 audio_codec = avcodec_find_encoder_by_name( acodec );
1212 audio_codec_id = audio_codec->id;
1213 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1215 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1216 acodec = mlt_properties_get( properties, "_acodec" );
1217 audio_codec = avcodec_find_encoder_by_name( acodec );
1222 audio_codec_id = CODEC_ID_NONE;
1223 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1228 audio_codec = avcodec_find_encoder( audio_codec_id );
1231 // Check for video codec overides
1232 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1233 video_codec_id = CODEC_ID_NONE;
1236 video_codec = avcodec_find_encoder_by_name( vcodec );
1239 video_codec_id = video_codec->id;
1243 video_codec_id = CODEC_ID_NONE;
1244 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1249 video_codec = avcodec_find_encoder( video_codec_id );
1253 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1254 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1256 char *name = mlt_properties_get_name( properties, i );
1257 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1259 char *key = strdup( name + 10 );
1260 char *markup = strrchr( key, '.' );
1261 if ( markup && !strcmp( markup, ".markup") )
1264 if ( !strstr( key, ".stream." ) )
1265 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1266 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1267 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1269 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1272 av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1282 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1283 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1285 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1286 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1288 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1289 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1291 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1292 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1294 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1295 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1297 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1298 if (metavalue != 0) oc->year = metavalue;
1300 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1301 if (metavalue != 0) oc->track = metavalue;
1305 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1307 // Get a frame now, so we can set some AVOptions from properties.
1308 frame = mlt_consumer_rt_frame( consumer );
1310 // Set the timecode from the MLT metadata if available.
1313 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1314 if ( timecode && strcmp( timecode, "" ) )
1316 mlt_properties_set( properties, "timecode", timecode );
1317 if ( strchr( timecode, ';' ) )
1318 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1322 // Add audio and video streams
1323 if ( video_codec_id != CODEC_ID_NONE )
1324 video_st = add_video_stream( consumer, oc, video_codec );
1325 if ( audio_codec_id != CODEC_ID_NONE )
1331 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1333 sprintf( key, "channels.%d", i );
1334 int j = mlt_properties_get_int( properties, key );
1338 total_channels += j;
1339 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1345 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1346 total_channels = channels;
1349 mlt_properties_set_int( properties, "channels", total_channels );
1351 // Audio format is determined when adding the audio stream
1352 mlt_audio_format aud_fmt = mlt_audio_none;
1354 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1355 int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1356 sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1358 // Set the parameters (even though we have none...)
1359 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1360 if ( av_set_parameters(oc, NULL) >= 0 )
1363 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1364 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1365 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1367 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1369 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1371 // Process properties as AVOptions
1372 char *fpre = mlt_properties_get( properties, "fpre" );
1375 mlt_properties p = mlt_properties_load( fpre );
1376 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1377 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1378 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1379 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1381 mlt_properties_close( p );
1383 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1384 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1385 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1386 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1389 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1391 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1393 audio_input_frame_size = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1394 acodec? acodec : NULL );
1395 if ( !audio_input_frame_size )
1399 // Setup custom I/O if redirecting
1400 if ( mlt_properties_get_int( properties, "redirect" ) )
1402 int buffer_size = 32768;
1403 unsigned char *buffer = av_malloc( buffer_size );
1404 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1405 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1407 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1412 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1413 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1415 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1416 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1417 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1422 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1425 // Open the output file, if needed
1426 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1428 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1429 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1431 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1434 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1435 mlt_properties_set_int( properties, "running", 0 );
1439 // Write the stream header.
1440 if ( mlt_properties_get_int( properties, "running" ) )
1441 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1442 avformat_write_header( oc, NULL );
1444 av_write_header( oc );
1447 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1450 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1451 mlt_properties_set_int( properties, "running", 0 );
1457 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1459 // Last check - need at least one stream
1460 if ( !audio_st[0] && !video_st )
1461 mlt_properties_set_int( properties, "running", 0 );
1463 // Get the starting time (can ignore the times above)
1464 gettimeofday( &ante, NULL );
1466 // Loop while running
1467 while( mlt_properties_get_int( properties, "running" ) &&
1468 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1471 frame = mlt_consumer_rt_frame( consumer );
1473 // Check that we have a frame to work with
1474 if ( frame != NULL )
1476 // Increment frames dispatched
1479 // Default audio args
1480 frame_properties = MLT_FRAME_PROPERTIES( frame );
1482 // Check for the terminated condition
1483 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1485 // Get audio and append to the fifo
1486 if ( !terminated && audio_st[0] )
1488 samples = mlt_sample_calculator( fps, frequency, count ++ );
1489 channels = total_channels;
1490 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1492 // Save the audio channel remap properties for later
1493 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1495 // Create the fifo if we don't have one
1498 fifo = sample_fifo_init( frequency, channels );
1499 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1503 // Silence if not normal forward speed
1504 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1505 memset( pcm, 0, samples * channels * sample_bytes );
1507 // Append the samples
1508 sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1509 total_time += ( samples * 1000000 ) / frequency;
1512 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1516 if ( !terminated && video_st )
1517 mlt_deque_push_back( queue, frame );
1519 mlt_frame_close( frame );
1523 // While we have stuff to process, process...
1526 // Write interleaved audio and video frames
1527 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1530 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) / sample_bytes )
1532 int j = 0; // channel offset into interleaved source buffer
1533 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1535 // Get the audio samples
1538 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1540 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1542 // This prevents an infinite loop when some versions of vorbis do not
1543 // increment pts when encoding silence.
1544 audio_pts = video_pts;
1549 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1551 samples = n / channels;
1553 // For each output stream
1554 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1556 AVStream *stream = audio_st[i];
1557 AVCodecContext *codec = stream->codec;
1560 av_init_packet( &pkt );
1562 // Optimized for single track and no channel remap
1563 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1565 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_1 );
1569 // Extract the audio channels according to channel mapping
1570 int dest_offset = 0; // channel offset into interleaved dest buffer
1572 // Get the number of channels for this stream
1573 sprintf( key, "channels.%d", i );
1574 int current_channels = mlt_properties_get_int( properties, key );
1576 // Clear the destination audio buffer.
1578 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1580 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1582 // For each output channel
1583 while ( dest_offset < current_channels && j < total_channels )
1585 int map_start = -1, map_channels = 0;
1586 int source_offset = 0;
1589 // Look for a mapping that starts at j
1590 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1592 sprintf( key, "%d.channels", k );
1593 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1594 sprintf( key, "%d.start", k );
1595 if ( mlt_properties_get( frame_meta_properties, key ) )
1596 map_start = mlt_properties_get_int( frame_meta_properties, key );
1597 if ( map_start != j )
1598 source_offset += map_channels;
1602 if ( map_start != j )
1604 map_channels = current_channels;
1608 // Copy samples if source offset valid
1609 if ( source_offset < channels )
1611 // Interleave the audio buffer with the # channels for this stream/mapping.
1612 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1614 void *src = audio_buf_1 + source_offset * sample_bytes;
1615 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1616 int s = samples + 1;
1619 memcpy( dest, src, sample_bytes );
1620 dest += current_channels * sample_bytes;
1621 src += channels * sample_bytes;
1625 // Otherwise silence
1628 j += current_channels;
1629 dest_offset += current_channels;
1632 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1635 // Write the compressed frame in the media file
1636 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1638 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1639 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame pts %"PRId64,
1640 stream->index, pkt.pts, codec->coded_frame->pts );
1642 pkt.flags |= PKT_FLAG_KEY;
1643 pkt.stream_index = stream->index;
1644 pkt.data = audio_outbuf;
1648 if ( av_interleaved_write_frame( oc, &pkt ) )
1650 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1651 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1652 goto on_fatal_error;
1656 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1659 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1668 else if ( video_st )
1671 if ( mlt_deque_count( queue ) )
1673 int out_size, ret = 0;
1676 frame = mlt_deque_pop_front( queue );
1677 frame_properties = MLT_FRAME_PROPERTIES( frame );
1679 c = video_st->codec;
1681 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1687 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1691 // Convert the mlt frame to an AVPicture
1692 for ( i = 0; i < height; i ++ )
1694 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1695 memcpy( p, q, width * 2 );
1699 // Do the colour space conversion
1701 int flags = SWS_BICUBIC;
1703 flags |= SWS_CPU_CAPS_MMX;
1706 flags |= SWS_CPU_CAPS_MMX2;
1708 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1709 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1710 sws_scale( context, (const uint8_t* const*) input->data, input->linesize, 0, height,
1711 output->data, output->linesize);
1712 sws_freeContext( context );
1714 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1717 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1719 // Apply the alpha if applicable
1720 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1722 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1725 for ( i = 0; i < height; i ++ )
1727 n = ( width + 7 ) / 8;
1728 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1732 case 0: do { *p = *alpha++; p += 4;
1733 case 7: *p = *alpha++; p += 4;
1734 case 6: *p = *alpha++; p += 4;
1735 case 5: *p = *alpha++; p += 4;
1736 case 4: *p = *alpha++; p += 4;
1737 case 3: *p = *alpha++; p += 4;
1738 case 2: *p = *alpha++; p += 4;
1739 case 1: *p = *alpha++; p += 4;
1747 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1749 // raw video case. The API will change slightly in the near future for that
1751 av_init_packet(&pkt);
1753 pkt.flags |= PKT_FLAG_KEY;
1754 pkt.stream_index= video_st->index;
1755 pkt.data= (uint8_t *)output;
1756 pkt.size= sizeof(AVPicture);
1758 ret = av_write_frame(oc, &pkt);
1759 video_pts += c->frame_size;
1764 output->quality = c->global_quality;
1766 // Set frame interlace hints
1767 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1768 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1769 output->pts = frame_count;
1772 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1774 // If zero size, it means the image was buffered
1778 av_init_packet( &pkt );
1780 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1781 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1782 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %"PRId64" frame pts %"PRId64, pkt.pts, c->coded_frame->pts );
1783 if( c->coded_frame && c->coded_frame->key_frame )
1784 pkt.flags |= PKT_FLAG_KEY;
1785 pkt.stream_index= video_st->index;
1786 pkt.data= video_outbuf;
1789 // write the compressed frame in the media file
1790 ret = av_interleaved_write_frame(oc, &pkt);
1791 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1792 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1794 // Dual pass logging
1795 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1796 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1798 else if ( out_size < 0 )
1800 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1806 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1807 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1808 goto on_fatal_error;
1810 mlt_frame_close( frame );
1819 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1821 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1822 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1825 if ( real_time_output == 1 && frames % 2 == 0 )
1827 long passed = time_difference( &ante );
1830 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
1833 if ( passed < total_time )
1835 long total = ( total_time - passed );
1836 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1837 nanosleep( &t, NULL );
1842 // Flush the encoder buffers
1843 if ( real_time_output <= 0 )
1846 // TODO: flush all audio streams
1847 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1849 AVCodecContext *c = audio_st[0]->codec;
1851 av_init_packet( &pkt );
1854 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1855 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) / sample_bytes ) )
1857 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size * sample_bytes );
1858 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, (short*) audio_buf_1 );
1860 if ( pkt.size <= 0 )
1861 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1862 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1863 if ( pkt.size <= 0 )
1866 // Write the compressed frame in the media file
1867 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1868 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1869 pkt.flags |= PKT_FLAG_KEY;
1870 pkt.stream_index = audio_st[0]->index;
1871 pkt.data = audio_outbuf;
1872 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1874 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1875 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1876 goto on_fatal_error;
1881 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1883 AVCodecContext *c = video_st->codec;
1885 av_init_packet( &pkt );
1888 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1889 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1890 if ( pkt.size <= 0 )
1893 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1894 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1895 if( c->coded_frame && c->coded_frame->key_frame )
1896 pkt.flags |= PKT_FLAG_KEY;
1897 pkt.stream_index = video_st->index;
1898 pkt.data = video_outbuf;
1900 // write the compressed frame in the media file
1901 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1903 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1904 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1905 goto on_fatal_error;
1907 // Dual pass logging
1908 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1909 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1915 // Write the trailer, if any
1916 av_write_trailer( oc );
1920 close_video(oc, video_st);
1921 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1922 close_audio( oc, audio_st[i] );
1925 for ( i = 0; i < oc->nb_streams; i++ )
1926 av_freep( &oc->streams[i] );
1928 // Close the output file
1929 if ( !( fmt->flags & AVFMT_NOFILE ) )
1931 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1932 if ( !mlt_properties_get_int( properties, "redirect" ) )
1933 avio_close( oc->pb );
1934 #elif LIBAVFORMAT_VERSION_MAJOR >= 52
1935 url_fclose( oc->pb );
1937 url_fclose( &oc->pb );
1941 // Clean up input and output frames
1943 av_free( output->data[0] );
1945 av_free( input->data[0] );
1947 av_free( video_outbuf );
1948 av_free( audio_buf_1 );
1949 av_free( audio_buf_2 );
1954 // Just in case we terminated on pause
1955 mlt_properties_set_int( properties, "running", 0 );
1957 mlt_consumer_stopped( consumer );
1958 mlt_properties_close( frame_meta_properties );
1960 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1962 // Remove the dual pass log file
1963 if ( mlt_properties_get( properties, "_logfilename" ) )
1964 remove( mlt_properties_get( properties, "_logfilename" ) );
1966 // Remove the x264 dual pass logs
1967 char *cwd = getcwd( NULL, 0 );
1968 const char *file = "x264_2pass.log";
1969 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1970 sprintf( full, "%s/%s", cwd, file );
1973 file = "x264_2pass.log.temp";
1974 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1975 sprintf( full, "%s/%s", cwd, file );
1978 file = "x264_2pass.log.mbtree";
1979 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1980 sprintf( full, "%s/%s", cwd, file );
1984 remove( "x264_2pass.log.temp" );
1987 while ( ( frame = mlt_deque_pop_back( queue ) ) )
1988 mlt_frame_close( frame );
1993 /** Close the consumer.
1996 static void consumer_close( mlt_consumer consumer )
1998 // Stop the consumer
1999 mlt_consumer_stop( consumer );
2002 mlt_consumer_close( consumer );