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 LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
241 if ( ( codec->encode || codec->encode2 ) && codec->type == CODEC_TYPE_AUDIO )
243 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
246 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
247 mlt_properties_set( codecs, key, codec->name );
249 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
250 mlt_properties_close( doc );
253 s = mlt_properties_get( properties, "vcodec" );
254 if ( s && strcmp( s, "list" ) == 0 )
256 mlt_properties doc = mlt_properties_new();
257 mlt_properties codecs = mlt_properties_new();
259 AVCodec *codec = NULL;
261 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
262 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
263 while ( ( codec = av_codec_next( codec ) ) )
264 #if LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
265 if ( (codec->encode || codec->encode2) && codec->type == CODEC_TYPE_VIDEO )
267 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
270 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
271 mlt_properties_set( codecs, key, codec->name );
273 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
274 mlt_properties_close( doc );
278 // Check that we're not already running
279 if ( !error && !mlt_properties_get_int( properties, "running" ) )
282 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
284 // Get the width and height
285 int width = mlt_properties_get_int( properties, "width" );
286 int height = mlt_properties_get_int( properties, "height" );
288 // Obtain the size property
289 char *size = mlt_properties_get( properties, "s" );
295 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
302 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Invalid size property %s - ignoring.\n", size );
306 // Now ensure we honour the multiple of two requested by libavformat
307 width = ( width / 2 ) * 2;
308 height = ( height / 2 ) * 2;
309 mlt_properties_set_int( properties, "width", width );
310 mlt_properties_set_int( properties, "height", height );
312 // We need to set these on the profile as well because the s property is
313 // an alias to mlt properties that correspond to profile settings.
314 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
317 profile->width = width;
318 profile->height = height;
321 // Handle the ffmpeg command line "-r" property for frame rate
322 if ( mlt_properties_get( properties, "r" ) )
324 double frame_rate = mlt_properties_get_double( properties, "r" );
325 AVRational rational = av_d2q( frame_rate, 255 );
326 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
327 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
330 profile->frame_rate_num = rational.num;
331 profile->frame_rate_den = rational.den;
332 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
336 // Apply AVOptions that are synonyms for standard mlt_consumer options
337 if ( mlt_properties_get( properties, "ac" ) )
338 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
339 if ( mlt_properties_get( properties, "ar" ) )
340 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
342 // Assign the thread to properties
343 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
346 pthread_create( thread, NULL, consumer_thread, consumer );
348 // Set the running state
349 mlt_properties_set_int( properties, "running", 1 );
354 /** Stop the consumer.
357 static int consumer_stop( mlt_consumer consumer )
359 // Get the properties
360 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
361 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
363 // Check that we're running
367 mlt_properties_set_int( properties, "running", 0 );
369 // Wait for termination
370 pthread_join( *thread, NULL );
372 mlt_properties_set_data( properties, "thread", NULL, 0, NULL, NULL );
378 /** Determine if the consumer is stopped.
381 static int consumer_is_stopped( mlt_consumer consumer )
383 // Get the properties
384 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
385 return !mlt_properties_get_int( properties, "running" );
388 /** Process properties as AVOptions and apply to AV context obj
391 static void apply_properties( void *obj, mlt_properties properties, int flags )
394 int count = mlt_properties_count( properties );
395 #if LIBAVUTIL_VERSION_INT < ((51<<16)+(12<<8)+0)
399 for ( i = 0; i < count; i++ )
401 const char *opt_name = mlt_properties_get_name( properties, i );
402 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
403 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
405 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
408 // If option not found, see if it was prefixed with a or v (-vb)
410 ( opt_name[0] == 'v' && ( flags & AV_OPT_FLAG_VIDEO_PARAM ) ) ||
411 ( opt_name[0] == 'a' && ( flags & AV_OPT_FLAG_AUDIO_PARAM ) ) ) )
412 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
413 opt = av_opt_find( obj, ++opt_name, NULL, flags, flags );
415 opt = av_find_opt( obj, ++opt_name, NULL, flags, flags );
417 // Apply option if found
419 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
420 av_opt_set( obj, opt_name, mlt_properties_get_value( properties, i), 0 );
421 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
422 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
423 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
424 av_set_string2( obj, opt_name, mlt_properties_get_value( properties, i), alloc );
426 av_set_string( obj, opt_name, mlt_properties_get_value( properties, i) );
431 static int get_mlt_audio_format( int av_sample_fmt )
433 switch ( av_sample_fmt )
435 case AV_SAMPLE_FMT_S32:
436 return mlt_audio_s32le;
437 case AV_SAMPLE_FMT_FLT:
438 return mlt_audio_f32le;
439 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
440 case AV_SAMPLE_FMT_S32P:
441 return mlt_audio_s32;
442 case AV_SAMPLE_FMT_FLTP:
443 return mlt_audio_float;
446 return mlt_audio_s16;
450 static int pick_sample_fmt( mlt_properties properties, AVCodec *codec )
452 int sample_fmt = AV_SAMPLE_FMT_S16;
453 const char *format = mlt_properties_get( properties, "mlt_audio_format" );
454 const int *p = codec->sample_fmts;
456 // get default av_sample_fmt from mlt_audio_format
459 if ( !strcmp( format, "s32le" ) )
460 sample_fmt = AV_SAMPLE_FMT_S32;
461 else if ( !strcmp( format, "f32le" ) )
462 sample_fmt = AV_SAMPLE_FMT_FLT;
463 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
464 else if ( !strcmp( format, "s32" ) )
465 sample_fmt = AV_SAMPLE_FMT_S32P;
466 else if ( !strcmp( format, "float" ) )
467 sample_fmt = AV_SAMPLE_FMT_FLTP;
470 // check if codec supports our mlt_audio_format
471 for ( ; *p != -1; p++ )
473 if ( *p == sample_fmt )
476 // no match - pick first one we support
477 for ( p = codec->sample_fmts; *p != -1; p++ )
481 case AV_SAMPLE_FMT_S16:
482 case AV_SAMPLE_FMT_S32:
483 case AV_SAMPLE_FMT_FLT:
484 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
485 case AV_SAMPLE_FMT_S32P:
486 case AV_SAMPLE_FMT_FLTP:
493 mlt_log_error( properties, "audio codec sample_fmt not compatible" );
495 return AV_SAMPLE_FMT_NONE;
498 /** Add an audio output stream
501 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec, int channels )
503 // Get the properties
504 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
506 // Create a new stream
507 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
508 AVStream *st = avformat_new_stream( oc, codec );
510 AVStream *st = av_new_stream( oc, oc->nb_streams );
513 // If created, then initialise from properties
516 AVCodecContext *c = st->codec;
518 // Establish defaults from AVOptions
519 #if LIBAVCODEC_VERSION_MAJOR >= 53
520 avcodec_get_context_defaults3( c, codec );
522 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
525 c->codec_id = codec->id;
526 c->codec_type = CODEC_TYPE_AUDIO;
527 c->sample_fmt = pick_sample_fmt( properties, codec );
529 #if 0 // disabled until some audio codecs are multi-threaded
530 // Setup multi-threading
531 int thread_count = mlt_properties_get_int( properties, "threads" );
532 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
533 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
534 if ( thread_count > 1 )
535 c->thread_count = thread_count;
538 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
539 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
541 // Allow the user to override the audio fourcc
542 if ( mlt_properties_get( properties, "atag" ) )
545 char *arg = mlt_properties_get( properties, "atag" );
546 int tag = strtol( arg, &tail, 0);
548 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
552 // Process properties as AVOptions
553 char *apre = mlt_properties_get( properties, "apre" );
556 mlt_properties p = mlt_properties_load( apre );
557 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
558 mlt_properties_close( p );
560 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
562 int audio_qscale = mlt_properties_get_int( properties, "aq" );
563 if ( audio_qscale > QSCALE_NONE )
565 c->flags |= CODEC_FLAG_QSCALE;
566 c->global_quality = FF_QP2LAMBDA * audio_qscale;
567 #if LIBAVFORMAT_VERSION_MAJOR < 53
568 st->quality = c->global_quality;
572 // Set parameters controlled by MLT
573 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
574 c->time_base = ( AVRational ){ 1, c->sample_rate };
575 c->channels = channels;
577 if ( mlt_properties_get( properties, "alang" ) != NULL )
578 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
579 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
580 av_dict_set( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
582 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
586 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
591 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
597 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
599 // We will return the audio input size from here
600 int audio_input_frame_size = 0;
603 AVCodecContext *c = st->codec;
608 codec = avcodec_find_encoder_by_name( codec_name );
610 codec = avcodec_find_encoder( c->codec_id );
612 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
613 // Process properties as AVOptions on the AVCodec
614 if ( codec && codec->priv_class )
616 char *apre = mlt_properties_get( properties, "apre" );
617 if ( !c->priv_data && codec->priv_data_size )
619 c->priv_data = av_mallocz( codec->priv_data_size );
620 *(const AVClass **) c->priv_data = codec->priv_class;
621 // av_opt_set_defaults( c );
625 mlt_properties p = mlt_properties_load( apre );
626 apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
627 mlt_properties_close( p );
629 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
633 // Continue if codec found and we can open it
634 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
635 if ( codec && avcodec_open2( c, codec, NULL ) >= 0 )
637 if ( codec && avcodec_open( c, codec ) >= 0 )
640 // ugly hack for PCM codecs (will be removed ASAP with new PCM
641 // support to compute the input frame size in samples
642 if ( c->frame_size <= 1 )
644 audio_input_frame_size = audio_outbuf_size / c->channels;
645 switch(st->codec->codec_id)
647 case CODEC_ID_PCM_S16LE:
648 case CODEC_ID_PCM_S16BE:
649 case CODEC_ID_PCM_U16LE:
650 case CODEC_ID_PCM_U16BE:
651 audio_input_frame_size >>= 1;
659 audio_input_frame_size = c->frame_size;
662 // Some formats want stream headers to be seperate (hmm)
663 if ( !strcmp( oc->oformat->name, "mp4" ) ||
664 !strcmp( oc->oformat->name, "mov" ) ||
665 !strcmp( oc->oformat->name, "3gp" ) )
666 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
670 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
671 audio_input_frame_size = 0;
674 return audio_input_frame_size;
677 static void close_audio( AVFormatContext *oc, AVStream *st )
679 if ( st && st->codec )
680 avcodec_close( st->codec );
683 /** Add a video output stream
686 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
688 // Get the properties
689 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
691 // Create a new stream
692 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
693 AVStream *st = avformat_new_stream( oc, codec );
695 AVStream *st = av_new_stream( oc, oc->nb_streams );
700 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
701 AVCodecContext *c = st->codec;
703 // Establish defaults from AVOptions
704 #if LIBAVCODEC_VERSION_MAJOR >= 53
705 avcodec_get_context_defaults3( c, codec );
707 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
710 c->codec_id = codec->id;
711 c->codec_type = CODEC_TYPE_VIDEO;
713 // Setup multi-threading
714 int thread_count = mlt_properties_get_int( properties, "threads" );
715 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
716 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
717 if ( thread_count > 1 )
718 #if LIBAVCODEC_VERSION_MAJOR >= 53
719 c->thread_count = thread_count;
721 avcodec_thread_init( c, thread_count );
724 // Process properties as AVOptions
725 char *vpre = mlt_properties_get( properties, "vpre" );
728 mlt_properties p = mlt_properties_load( vpre );
730 if ( mlt_properties_count( p ) < 1 )
732 AVCodec *codec = avcodec_find_encoder( c->codec_id );
735 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
736 strcpy( path, AVDATADIR );
737 strcat( path, codec->name );
739 strcat( path, vpre );
740 strcat( path, ".ffpreset" );
742 mlt_properties_close( p );
743 p = mlt_properties_load( path );
744 if ( mlt_properties_count( p ) > 0 )
745 mlt_properties_debug( p, path, stderr );
751 mlt_properties_debug( p, vpre, stderr );
754 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
755 mlt_properties_close( p );
757 int colorspace = mlt_properties_get_int( properties, "colorspace" );
758 mlt_properties_set( properties, "colorspace", NULL );
759 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
760 mlt_properties_set_int( properties, "colorspace", colorspace );
762 // Set options controlled by MLT
763 c->width = mlt_properties_get_int( properties, "width" );
764 c->height = mlt_properties_get_int( properties, "height" );
765 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
766 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
767 if ( st->time_base.den == 0 )
768 st->time_base = c->time_base;
769 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
770 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
772 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
775 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
776 switch ( colorspace )
779 c->colorspace = AVCOL_SPC_SMPTE170M;
782 c->colorspace = AVCOL_SPC_SMPTE240M;
785 c->colorspace = AVCOL_SPC_BT470BG;
788 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
791 c->colorspace = AVCOL_SPC_BT709;
796 if ( mlt_properties_get( properties, "aspect" ) )
798 // "-aspect" on ffmpeg command line is display aspect ratio
799 double ar = mlt_properties_get_double( properties, "aspect" );
800 AVRational rational = av_d2q( ar, 255 );
802 // Update the profile and properties as well since this is an alias
803 // for mlt properties that correspond to profile settings
804 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
805 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
806 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
809 profile->display_aspect_num = rational.num;
810 profile->display_aspect_den = rational.den;
811 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
814 // Now compute the sample aspect ratio
815 rational = av_d2q( ar * c->height / c->width, 255 );
816 c->sample_aspect_ratio = rational;
817 // Update the profile and properties as well since this is an alias
818 // for mlt properties that correspond to profile settings
819 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
820 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
823 profile->sample_aspect_num = rational.num;
824 profile->sample_aspect_den = rational.den;
825 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
830 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
831 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
833 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
834 st->sample_aspect_ratio = c->sample_aspect_ratio;
837 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
839 c->flags |= CODEC_FLAG_QSCALE;
840 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
841 #if LIBAVFORMAT_VERSION_MAJOR < 53
842 st->quality = c->global_quality;
846 // Allow the user to override the video fourcc
847 if ( mlt_properties_get( properties, "vtag" ) )
850 const char *arg = mlt_properties_get( properties, "vtag" );
851 int tag = strtol( arg, &tail, 0);
853 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
857 // Some formats want stream headers to be seperate
858 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
859 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
861 // Translate these standard mlt consumer properties to ffmpeg
862 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
863 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
865 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
866 c->flags |= CODEC_FLAG_INTERLACED_DCT;
867 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
868 c->flags |= CODEC_FLAG_INTERLACED_ME;
871 // parse the ratecontrol override string
873 char *rc_override = mlt_properties_get( properties, "rc_override" );
874 for ( i = 0; rc_override; i++ )
877 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
879 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
880 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
881 c->rc_override[i].start_frame = start;
882 c->rc_override[i].end_frame = end;
885 c->rc_override[i].qscale = q;
886 c->rc_override[i].quality_factor = 1.0;
890 c->rc_override[i].qscale = 0;
891 c->rc_override[i].quality_factor = -q / 100.0;
893 rc_override = strchr( rc_override, '/' );
897 c->rc_override_count = i;
898 if ( !c->rc_initial_buffer_occupancy )
899 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
900 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
903 i = mlt_properties_get_int( properties, "pass" );
905 c->flags |= CODEC_FLAG_PASS1;
907 c->flags |= CODEC_FLAG_PASS2;
908 if ( codec->id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
910 char logfilename[1024];
915 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
916 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
917 if ( c->flags & CODEC_FLAG_PASS1 )
919 f = fopen( logfilename, "w" );
921 perror( logfilename );
923 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
927 /* read the log file */
928 f = fopen( logfilename, "r" );
935 mlt_properties_set( properties, "_logfilename", logfilename );
936 fseek( f, 0, SEEK_END );
938 fseek( f, 0, SEEK_SET );
939 logbuffer = av_malloc( size + 1 );
941 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
944 size = fread( logbuffer, 1, size, f );
945 logbuffer[size] = '\0';
946 c->stats_in = logbuffer;
955 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
961 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
964 AVFrame *picture = avcodec_alloc_frame();
966 // Determine size of the
967 int size = avpicture_get_size(pix_fmt, width, height);
969 // Allocate the picture buf
970 uint8_t *picture_buf = av_malloc(size);
972 // If we have both, then fill the image
973 if ( picture != NULL && picture_buf != NULL )
975 // Fill the frame with the allocated buffer
976 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
980 // Something failed - clean up what we can
982 av_free( picture_buf );
989 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
992 AVCodecContext *video_enc = st->codec;
994 // find the video encoder
997 codec = avcodec_find_encoder_by_name( codec_name );
999 codec = avcodec_find_encoder( video_enc->codec_id );
1001 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1002 // Process properties as AVOptions on the AVCodec
1003 if ( codec && codec->priv_class )
1005 char *vpre = mlt_properties_get( properties, "vpre" );
1006 if ( !video_enc->priv_data && codec->priv_data_size )
1008 video_enc->priv_data = av_mallocz( codec->priv_data_size );
1009 *(const AVClass **) video_enc->priv_data = codec->priv_class;
1010 // av_opt_set_defaults( video_enc );
1014 mlt_properties p = mlt_properties_load( vpre );
1015 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1016 mlt_properties_close( p );
1018 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1022 if( codec && codec->pix_fmts )
1024 const enum PixelFormat *p = codec->pix_fmts;
1025 for( ; *p!=-1; p++ )
1027 if( *p == video_enc->pix_fmt )
1031 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1034 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1035 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1037 int result = codec && avcodec_open( video_enc, codec ) >= 0;
1043 void close_video(AVFormatContext *oc, AVStream *st)
1045 if ( st && st->codec )
1047 av_freep( &st->codec->stats_in );
1048 avcodec_close(st->codec);
1052 static inline long time_difference( struct timeval *time1 )
1054 struct timeval time2;
1055 gettimeofday( &time2, NULL );
1056 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1059 static int mlt_write(void *h, uint8_t *buf, int size)
1061 mlt_properties properties = (mlt_properties) h;
1062 mlt_events_fire( properties, "avformat-write", buf, size, NULL );
1066 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1068 listener( owner, service, (uint8_t*) args[0], (int) args[1] );
1072 /** The main thread - the argument is simply the consumer.
1075 static void *consumer_thread( void *arg )
1077 // Map the argument to the object
1078 mlt_consumer consumer = arg;
1080 // Get the properties
1081 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1083 // Get the terminate on pause property
1084 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1087 // Determine if feed is slow (for realtime stuff)
1088 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1091 struct timeval ante;
1093 // Get the frame rate
1094 double fps = mlt_properties_get_double( properties, "fps" );
1096 // Get width and height
1097 int width = mlt_properties_get_int( properties, "width" );
1098 int height = mlt_properties_get_int( properties, "height" );
1099 int img_width = width;
1100 int img_height = height;
1102 // Get default audio properties
1103 int channels = mlt_properties_get_int( properties, "channels" );
1104 int total_channels = channels;
1105 int frequency = mlt_properties_get_int( properties, "frequency" );
1109 // AVFormat audio buffer and frame size
1110 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1111 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1112 int audio_input_frame_size = 0;
1114 // AVFormat video buffer and frame count
1115 int frame_count = 0;
1116 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1117 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1119 // Used for the frame properties
1120 mlt_frame frame = NULL;
1121 mlt_properties frame_properties = NULL;
1124 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1125 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1127 // Need two av pictures for converting
1128 AVFrame *output = NULL;
1129 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
1131 // For receiving images from an mlt_frame
1133 mlt_image_format img_fmt = mlt_image_yuv422;
1135 // For receiving audio samples back from the fifo
1136 uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1137 uint8_t *audio_buf_2 = NULL;
1140 // Allocate the context
1141 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
1142 AVFormatContext *oc = avformat_alloc_context( );
1144 AVFormatContext *oc = av_alloc_format_context( );
1148 AVStream *video_st = NULL;
1149 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1152 double audio_pts = 0;
1153 double video_pts = 0;
1155 // Frames dispatched
1156 long int frames = 0;
1157 long int total_time = 0;
1159 // Determine the format
1160 AVOutputFormat *fmt = NULL;
1161 const char *filename = mlt_properties_get( properties, "target" );
1162 char *format = mlt_properties_get( properties, "f" );
1163 char *vcodec = mlt_properties_get( properties, "vcodec" );
1164 char *acodec = mlt_properties_get( properties, "acodec" );
1165 AVCodec *audio_codec = NULL;
1166 AVCodec *video_codec = NULL;
1168 // Used to store and override codec ids
1174 mlt_properties frame_meta_properties = mlt_properties_new();
1176 // Initialize audio_st
1177 int i = MAX_AUDIO_STREAMS;
1181 // Check for user selected format first
1182 if ( format != NULL )
1183 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1184 fmt = guess_format( format, NULL, NULL );
1186 fmt = av_guess_format( format, NULL, NULL );
1189 // Otherwise check on the filename
1190 if ( fmt == NULL && filename != NULL )
1191 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1192 fmt = guess_format( NULL, filename, NULL );
1194 fmt = av_guess_format( NULL, filename, NULL );
1197 // Otherwise default to mpeg
1199 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1200 fmt = guess_format( "mpeg", NULL, NULL );
1202 fmt = av_guess_format( "mpeg", NULL, NULL );
1205 // We need a filename - default to stdout?
1206 if ( filename == NULL || !strcmp( filename, "" ) )
1209 // Get the codec ids selected
1210 audio_codec_id = fmt->audio_codec;
1211 video_codec_id = fmt->video_codec;
1213 // Check for audio codec overides
1214 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1215 audio_codec_id = CODEC_ID_NONE;
1218 audio_codec = avcodec_find_encoder_by_name( acodec );
1221 audio_codec_id = audio_codec->id;
1222 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1224 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1225 acodec = mlt_properties_get( properties, "_acodec" );
1226 audio_codec = avcodec_find_encoder_by_name( acodec );
1228 else if ( !strcmp( acodec, "aac" ) )
1230 mlt_properties_set( properties, "astrict", "experimental" );
1235 audio_codec_id = CODEC_ID_NONE;
1236 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1241 audio_codec = avcodec_find_encoder( audio_codec_id );
1244 // Check for video codec overides
1245 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1246 video_codec_id = CODEC_ID_NONE;
1249 video_codec = avcodec_find_encoder_by_name( vcodec );
1252 video_codec_id = video_codec->id;
1256 video_codec_id = CODEC_ID_NONE;
1257 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1262 video_codec = avcodec_find_encoder( video_codec_id );
1266 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1267 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1269 char *name = mlt_properties_get_name( properties, i );
1270 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1272 char *key = strdup( name + 10 );
1273 char *markup = strrchr( key, '.' );
1274 if ( markup && !strcmp( markup, ".markup") )
1277 if ( !strstr( key, ".stream." ) )
1278 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1279 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1280 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1282 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1285 av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1295 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1296 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1298 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1299 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1301 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1302 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1304 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1305 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1307 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1308 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1310 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1311 if (metavalue != 0) oc->year = metavalue;
1313 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1314 if (metavalue != 0) oc->track = metavalue;
1318 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1320 // Get a frame now, so we can set some AVOptions from properties.
1321 frame = mlt_consumer_rt_frame( consumer );
1323 // Set the timecode from the MLT metadata if available.
1326 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1327 if ( timecode && strcmp( timecode, "" ) )
1329 mlt_properties_set( properties, "timecode", timecode );
1330 if ( strchr( timecode, ';' ) )
1331 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1335 // Add audio and video streams
1336 if ( video_codec_id != CODEC_ID_NONE )
1337 video_st = add_video_stream( consumer, oc, video_codec );
1338 if ( audio_codec_id != CODEC_ID_NONE )
1344 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1346 sprintf( key, "channels.%d", i );
1347 int j = mlt_properties_get_int( properties, key );
1351 total_channels += j;
1352 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1358 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1359 total_channels = channels;
1362 mlt_properties_set_int( properties, "channels", total_channels );
1364 // Audio format is determined when adding the audio stream
1365 mlt_audio_format aud_fmt = mlt_audio_none;
1367 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1368 int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1369 sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1371 // Set the parameters (even though we have none...)
1372 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1373 if ( av_set_parameters(oc, NULL) >= 0 )
1376 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1377 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1378 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1380 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1382 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1384 // Process properties as AVOptions
1385 char *fpre = mlt_properties_get( properties, "fpre" );
1388 mlt_properties p = mlt_properties_load( fpre );
1389 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1390 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1391 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1392 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1394 mlt_properties_close( p );
1396 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1397 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1398 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1399 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1402 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1404 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1406 audio_input_frame_size = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1407 acodec? acodec : NULL );
1408 if ( !audio_input_frame_size )
1410 // Remove the audio stream from the output context
1412 for ( j = 0; j < oc->nb_streams; j++ )
1414 if ( oc->streams[j] == audio_st[i] )
1415 av_freep( &oc->streams[j] );
1422 // Setup custom I/O if redirecting
1423 if ( mlt_properties_get_int( properties, "redirect" ) )
1425 int buffer_size = 32768;
1426 unsigned char *buffer = av_malloc( buffer_size );
1427 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1428 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1430 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1435 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1436 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1438 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1439 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1440 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1445 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1448 // Open the output file, if needed
1449 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1451 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1452 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1454 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1457 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1458 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1459 goto on_fatal_error;
1463 // Write the stream header.
1464 if ( mlt_properties_get_int( properties, "running" ) )
1465 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1466 avformat_write_header( oc, NULL );
1468 av_write_header( oc );
1471 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1474 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1475 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1476 goto on_fatal_error;
1482 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1484 // Last check - need at least one stream
1485 if ( !audio_st[0] && !video_st )
1487 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1488 goto on_fatal_error;
1491 // Get the starting time (can ignore the times above)
1492 gettimeofday( &ante, NULL );
1494 // Loop while running
1495 while( mlt_properties_get_int( properties, "running" ) &&
1496 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1499 frame = mlt_consumer_rt_frame( consumer );
1501 // Check that we have a frame to work with
1502 if ( frame != NULL )
1504 // Increment frames dispatched
1507 // Default audio args
1508 frame_properties = MLT_FRAME_PROPERTIES( frame );
1510 // Check for the terminated condition
1511 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1513 // Get audio and append to the fifo
1514 if ( !terminated && audio_st[0] )
1516 samples = mlt_sample_calculator( fps, frequency, count ++ );
1517 channels = total_channels;
1518 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1520 // Save the audio channel remap properties for later
1521 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1523 // Create the fifo if we don't have one
1526 fifo = sample_fifo_init( frequency, channels );
1527 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1531 // Silence if not normal forward speed
1532 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1533 memset( pcm, 0, samples * channels * sample_bytes );
1535 // Append the samples
1536 sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1537 total_time += ( samples * 1000000 ) / frequency;
1540 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1544 if ( !terminated && video_st )
1545 mlt_deque_push_back( queue, frame );
1547 mlt_frame_close( frame );
1551 // While we have stuff to process, process...
1554 // Write interleaved audio and video frames
1555 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1558 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) / sample_bytes )
1560 int j = 0; // channel offset into interleaved source buffer
1561 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1563 // Get the audio samples
1566 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1568 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1570 // This prevents an infinite loop when some versions of vorbis do not
1571 // increment pts when encoding silence.
1572 audio_pts = video_pts;
1577 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1579 samples = n / channels;
1581 // For each output stream
1582 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1584 AVStream *stream = audio_st[i];
1585 AVCodecContext *codec = stream->codec;
1588 av_init_packet( &pkt );
1590 // Optimized for single track and no channel remap
1591 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1593 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_1 );
1597 // Extract the audio channels according to channel mapping
1598 int dest_offset = 0; // channel offset into interleaved dest buffer
1600 // Get the number of channels for this stream
1601 sprintf( key, "channels.%d", i );
1602 int current_channels = mlt_properties_get_int( properties, key );
1604 // Clear the destination audio buffer.
1606 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1608 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1610 // For each output channel
1611 while ( dest_offset < current_channels && j < total_channels )
1613 int map_start = -1, map_channels = 0;
1614 int source_offset = 0;
1617 // Look for a mapping that starts at j
1618 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1620 sprintf( key, "%d.channels", k );
1621 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1622 sprintf( key, "%d.start", k );
1623 if ( mlt_properties_get( frame_meta_properties, key ) )
1624 map_start = mlt_properties_get_int( frame_meta_properties, key );
1625 if ( map_start != j )
1626 source_offset += map_channels;
1630 if ( map_start != j )
1632 map_channels = current_channels;
1636 // Copy samples if source offset valid
1637 if ( source_offset < channels )
1639 // Interleave the audio buffer with the # channels for this stream/mapping.
1640 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1642 void *src = audio_buf_1 + source_offset * sample_bytes;
1643 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1644 int s = samples + 1;
1647 memcpy( dest, src, sample_bytes );
1648 dest += current_channels * sample_bytes;
1649 src += channels * sample_bytes;
1653 // Otherwise silence
1656 j += current_channels;
1657 dest_offset += current_channels;
1660 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1663 // Write the compressed frame in the media file
1664 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1666 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1667 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame pts %"PRId64,
1668 stream->index, pkt.pts, codec->coded_frame->pts );
1670 pkt.flags |= PKT_FLAG_KEY;
1671 pkt.stream_index = stream->index;
1672 pkt.data = audio_outbuf;
1676 if ( av_interleaved_write_frame( oc, &pkt ) )
1678 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1679 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1680 goto on_fatal_error;
1684 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1687 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1696 else if ( video_st )
1699 if ( mlt_deque_count( queue ) )
1701 int out_size, ret = 0;
1704 frame = mlt_deque_pop_front( queue );
1705 frame_properties = MLT_FRAME_PROPERTIES( frame );
1707 c = video_st->codec;
1709 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1715 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1719 // Convert the mlt frame to an AVPicture
1720 for ( i = 0; i < height; i ++ )
1722 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1723 memcpy( p, q, width * 2 );
1727 // Do the colour space conversion
1729 int flags = SWS_BICUBIC;
1731 flags |= SWS_CPU_CAPS_MMX;
1734 flags |= SWS_CPU_CAPS_MMX2;
1736 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1737 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1738 sws_scale( context, (const uint8_t* const*) input->data, input->linesize, 0, height,
1739 output->data, output->linesize);
1740 sws_freeContext( context );
1742 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1745 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1747 // Apply the alpha if applicable
1748 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1750 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1753 for ( i = 0; i < height; i ++ )
1755 n = ( width + 7 ) / 8;
1756 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1760 case 0: do { *p = *alpha++; p += 4;
1761 case 7: *p = *alpha++; p += 4;
1762 case 6: *p = *alpha++; p += 4;
1763 case 5: *p = *alpha++; p += 4;
1764 case 4: *p = *alpha++; p += 4;
1765 case 3: *p = *alpha++; p += 4;
1766 case 2: *p = *alpha++; p += 4;
1767 case 1: *p = *alpha++; p += 4;
1775 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1777 // raw video case. The API will change slightly in the near future for that
1779 av_init_packet(&pkt);
1781 pkt.flags |= PKT_FLAG_KEY;
1782 pkt.stream_index= video_st->index;
1783 pkt.data= (uint8_t *)output;
1784 pkt.size= sizeof(AVPicture);
1786 ret = av_write_frame(oc, &pkt);
1787 video_pts += c->frame_size;
1792 output->quality = c->global_quality;
1794 // Set frame interlace hints
1795 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1796 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1797 output->pts = frame_count;
1800 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1802 // If zero size, it means the image was buffered
1806 av_init_packet( &pkt );
1808 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1809 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1810 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %"PRId64" frame pts %"PRId64, pkt.pts, c->coded_frame->pts );
1811 if( c->coded_frame && c->coded_frame->key_frame )
1812 pkt.flags |= PKT_FLAG_KEY;
1813 pkt.stream_index= video_st->index;
1814 pkt.data= video_outbuf;
1817 // write the compressed frame in the media file
1818 ret = av_interleaved_write_frame(oc, &pkt);
1819 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1820 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1822 // Dual pass logging
1823 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1824 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1826 else if ( out_size < 0 )
1828 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1834 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1835 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1836 goto on_fatal_error;
1838 mlt_frame_close( frame );
1847 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1849 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1850 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1853 if ( real_time_output == 1 && frames % 2 == 0 )
1855 long passed = time_difference( &ante );
1858 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
1861 if ( passed < total_time )
1863 long total = ( total_time - passed );
1864 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1865 nanosleep( &t, NULL );
1870 // Flush the encoder buffers
1871 if ( real_time_output <= 0 )
1874 // TODO: flush all audio streams
1875 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1877 AVCodecContext *c = audio_st[0]->codec;
1879 av_init_packet( &pkt );
1883 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) / sample_bytes ) )
1885 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size * sample_bytes );
1886 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, (short*) audio_buf_1 );
1888 if ( pkt.size <= 0 )
1889 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1890 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1891 if ( pkt.size <= 0 )
1894 // Write the compressed frame in the media file
1895 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1896 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1897 pkt.flags |= PKT_FLAG_KEY;
1898 pkt.stream_index = audio_st[0]->index;
1899 pkt.data = audio_outbuf;
1900 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1902 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1903 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1904 goto on_fatal_error;
1909 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1911 AVCodecContext *c = video_st->codec;
1913 av_init_packet( &pkt );
1916 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1917 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1918 if ( pkt.size <= 0 )
1921 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1922 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1923 if( c->coded_frame && c->coded_frame->key_frame )
1924 pkt.flags |= PKT_FLAG_KEY;
1925 pkt.stream_index = video_st->index;
1926 pkt.data = video_outbuf;
1928 // write the compressed frame in the media file
1929 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1931 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1932 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1933 goto on_fatal_error;
1935 // Dual pass logging
1936 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1937 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1943 // Write the trailer, if any
1945 av_write_trailer( oc );
1949 close_video(oc, video_st);
1950 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1951 close_audio( oc, audio_st[i] );
1954 for ( i = 0; i < oc->nb_streams; i++ )
1955 av_freep( &oc->streams[i] );
1957 // Close the output file
1958 if ( !( fmt->flags & AVFMT_NOFILE ) &&
1959 !mlt_properties_get_int( properties, "redirect" ) )
1961 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1962 if ( oc->pb ) avio_close( oc->pb );
1963 #elif LIBAVFORMAT_VERSION_MAJOR >= 52
1964 if ( oc->pb ) url_fclose( oc->pb );
1966 url_fclose( &oc->pb );
1970 // Clean up input and output frames
1972 av_free( output->data[0] );
1974 av_free( input->data[0] );
1976 av_free( video_outbuf );
1977 av_free( audio_buf_1 );
1978 av_free( audio_buf_2 );
1983 // Just in case we terminated on pause
1984 mlt_consumer_stopped( consumer );
1985 mlt_properties_close( frame_meta_properties );
1987 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1989 // Remove the dual pass log file
1990 if ( mlt_properties_get( properties, "_logfilename" ) )
1991 remove( mlt_properties_get( properties, "_logfilename" ) );
1993 // Remove the x264 dual pass logs
1994 char *cwd = getcwd( NULL, 0 );
1995 const char *file = "x264_2pass.log";
1996 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1997 sprintf( full, "%s/%s", cwd, file );
2000 file = "x264_2pass.log.temp";
2001 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2002 sprintf( full, "%s/%s", cwd, file );
2005 file = "x264_2pass.log.mbtree";
2006 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2007 sprintf( full, "%s/%s", cwd, file );
2011 remove( "x264_2pass.log.temp" );
2014 while ( ( frame = mlt_deque_pop_back( queue ) ) )
2015 mlt_frame_close( frame );
2020 /** Close the consumer.
2023 static void consumer_close( mlt_consumer consumer )
2025 // Stop the consumer
2026 mlt_consumer_stop( consumer );
2029 mlt_consumer_close( consumer );