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__ );
673 return audio_input_frame_size;
676 static void close_audio( AVFormatContext *oc, AVStream *st )
678 if ( st && st->codec )
679 avcodec_close( st->codec );
682 /** Add a video output stream
685 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
687 // Get the properties
688 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
690 // Create a new stream
691 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
692 AVStream *st = avformat_new_stream( oc, codec );
694 AVStream *st = av_new_stream( oc, oc->nb_streams );
699 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
700 AVCodecContext *c = st->codec;
702 // Establish defaults from AVOptions
703 #if LIBAVCODEC_VERSION_MAJOR >= 53
704 avcodec_get_context_defaults3( c, codec );
706 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
709 c->codec_id = codec->id;
710 c->codec_type = CODEC_TYPE_VIDEO;
712 // Setup multi-threading
713 int thread_count = mlt_properties_get_int( properties, "threads" );
714 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
715 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
716 if ( thread_count > 1 )
717 #if LIBAVCODEC_VERSION_MAJOR >= 53
718 c->thread_count = thread_count;
720 avcodec_thread_init( c, thread_count );
723 // Process properties as AVOptions
724 char *vpre = mlt_properties_get( properties, "vpre" );
727 mlt_properties p = mlt_properties_load( vpre );
729 if ( mlt_properties_count( p ) < 1 )
731 AVCodec *codec = avcodec_find_encoder( c->codec_id );
734 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
735 strcpy( path, AVDATADIR );
736 strcat( path, codec->name );
738 strcat( path, vpre );
739 strcat( path, ".ffpreset" );
741 mlt_properties_close( p );
742 p = mlt_properties_load( path );
743 if ( mlt_properties_count( p ) > 0 )
744 mlt_properties_debug( p, path, stderr );
750 mlt_properties_debug( p, vpre, stderr );
753 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
754 mlt_properties_close( p );
756 int colorspace = mlt_properties_get_int( properties, "colorspace" );
757 mlt_properties_set( properties, "colorspace", NULL );
758 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
759 mlt_properties_set_int( properties, "colorspace", colorspace );
761 // Set options controlled by MLT
762 c->width = mlt_properties_get_int( properties, "width" );
763 c->height = mlt_properties_get_int( properties, "height" );
764 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
765 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
766 if ( st->time_base.den == 0 )
767 st->time_base = c->time_base;
768 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
769 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
771 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
774 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
775 switch ( colorspace )
778 c->colorspace = AVCOL_SPC_SMPTE170M;
781 c->colorspace = AVCOL_SPC_SMPTE240M;
784 c->colorspace = AVCOL_SPC_BT470BG;
787 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
790 c->colorspace = AVCOL_SPC_BT709;
795 if ( mlt_properties_get( properties, "aspect" ) )
797 // "-aspect" on ffmpeg command line is display aspect ratio
798 double ar = mlt_properties_get_double( properties, "aspect" );
799 AVRational rational = av_d2q( ar, 255 );
801 // Update the profile and properties as well since this is an alias
802 // for mlt properties that correspond to profile settings
803 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
804 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
805 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
808 profile->display_aspect_num = rational.num;
809 profile->display_aspect_den = rational.den;
810 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
813 // Now compute the sample aspect ratio
814 rational = av_d2q( ar * c->height / c->width, 255 );
815 c->sample_aspect_ratio = rational;
816 // Update the profile and properties as well since this is an alias
817 // for mlt properties that correspond to profile settings
818 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
819 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
822 profile->sample_aspect_num = rational.num;
823 profile->sample_aspect_den = rational.den;
824 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
829 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
830 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
832 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
833 st->sample_aspect_ratio = c->sample_aspect_ratio;
836 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
838 c->flags |= CODEC_FLAG_QSCALE;
839 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
840 #if LIBAVFORMAT_VERSION_MAJOR < 53
841 st->quality = c->global_quality;
845 // Allow the user to override the video fourcc
846 if ( mlt_properties_get( properties, "vtag" ) )
849 const char *arg = mlt_properties_get( properties, "vtag" );
850 int tag = strtol( arg, &tail, 0);
852 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
856 // Some formats want stream headers to be seperate
857 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
858 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
860 // Translate these standard mlt consumer properties to ffmpeg
861 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
862 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
864 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
865 c->flags |= CODEC_FLAG_INTERLACED_DCT;
866 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
867 c->flags |= CODEC_FLAG_INTERLACED_ME;
870 // parse the ratecontrol override string
872 char *rc_override = mlt_properties_get( properties, "rc_override" );
873 for ( i = 0; rc_override; i++ )
876 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
878 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
879 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
880 c->rc_override[i].start_frame = start;
881 c->rc_override[i].end_frame = end;
884 c->rc_override[i].qscale = q;
885 c->rc_override[i].quality_factor = 1.0;
889 c->rc_override[i].qscale = 0;
890 c->rc_override[i].quality_factor = -q / 100.0;
892 rc_override = strchr( rc_override, '/' );
896 c->rc_override_count = i;
897 if ( !c->rc_initial_buffer_occupancy )
898 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
899 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
902 i = mlt_properties_get_int( properties, "pass" );
904 c->flags |= CODEC_FLAG_PASS1;
906 c->flags |= CODEC_FLAG_PASS2;
907 if ( codec->id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
909 char logfilename[1024];
914 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
915 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
916 if ( c->flags & CODEC_FLAG_PASS1 )
918 f = fopen( logfilename, "w" );
920 perror( logfilename );
922 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
926 /* read the log file */
927 f = fopen( logfilename, "r" );
934 mlt_properties_set( properties, "_logfilename", logfilename );
935 fseek( f, 0, SEEK_END );
937 fseek( f, 0, SEEK_SET );
938 logbuffer = av_malloc( size + 1 );
940 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
943 size = fread( logbuffer, 1, size, f );
945 logbuffer[size] = '\0';
946 c->stats_in = logbuffer;
954 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
960 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
963 AVFrame *picture = avcodec_alloc_frame();
965 // Determine size of the
966 int size = avpicture_get_size(pix_fmt, width, height);
968 // Allocate the picture buf
969 uint8_t *picture_buf = av_malloc(size);
971 // If we have both, then fill the image
972 if ( picture != NULL && picture_buf != NULL )
974 // Fill the frame with the allocated buffer
975 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
979 // Something failed - clean up what we can
981 av_free( picture_buf );
988 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
991 AVCodecContext *video_enc = st->codec;
993 // find the video encoder
996 codec = avcodec_find_encoder_by_name( codec_name );
998 codec = avcodec_find_encoder( video_enc->codec_id );
1000 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1001 // Process properties as AVOptions on the AVCodec
1002 if ( codec && codec->priv_class )
1004 char *vpre = mlt_properties_get( properties, "vpre" );
1005 if ( !video_enc->priv_data && codec->priv_data_size )
1007 video_enc->priv_data = av_mallocz( codec->priv_data_size );
1008 *(const AVClass **) video_enc->priv_data = codec->priv_class;
1009 // av_opt_set_defaults( video_enc );
1013 mlt_properties p = mlt_properties_load( vpre );
1014 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1015 mlt_properties_close( p );
1017 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1021 if( codec && codec->pix_fmts )
1023 const enum PixelFormat *p = codec->pix_fmts;
1024 for( ; *p!=-1; p++ )
1026 if( *p == video_enc->pix_fmt )
1030 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1033 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1034 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1036 int result = codec && avcodec_open( video_enc, codec ) >= 0;
1042 void close_video(AVFormatContext *oc, AVStream *st)
1044 if ( st && st->codec )
1046 av_freep( &st->codec->stats_in );
1047 avcodec_close(st->codec);
1051 static inline long time_difference( struct timeval *time1 )
1053 struct timeval time2;
1054 gettimeofday( &time2, NULL );
1055 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1058 static int mlt_write(void *h, uint8_t *buf, int size)
1060 mlt_properties properties = (mlt_properties) h;
1061 mlt_events_fire( properties, "avformat-write", buf, size, NULL );
1065 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1067 listener( owner, service, (uint8_t*) args[0], (int) args[1] );
1071 /** The main thread - the argument is simply the consumer.
1074 static void *consumer_thread( void *arg )
1076 // Map the argument to the object
1077 mlt_consumer consumer = arg;
1079 // Get the properties
1080 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1082 // Get the terminate on pause property
1083 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1086 // Determine if feed is slow (for realtime stuff)
1087 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1090 struct timeval ante;
1092 // Get the frame rate
1093 double fps = mlt_properties_get_double( properties, "fps" );
1095 // Get width and height
1096 int width = mlt_properties_get_int( properties, "width" );
1097 int height = mlt_properties_get_int( properties, "height" );
1098 int img_width = width;
1099 int img_height = height;
1101 // Get default audio properties
1102 int channels = mlt_properties_get_int( properties, "channels" );
1103 int total_channels = channels;
1104 int frequency = mlt_properties_get_int( properties, "frequency" );
1108 // AVFormat audio buffer and frame size
1109 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1110 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1111 int audio_input_frame_size = 0;
1113 // AVFormat video buffer and frame count
1114 int frame_count = 0;
1115 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1116 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1118 // Used for the frame properties
1119 mlt_frame frame = NULL;
1120 mlt_properties frame_properties = NULL;
1123 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1124 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1126 // Need two av pictures for converting
1127 AVFrame *output = NULL;
1128 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
1130 // For receiving images from an mlt_frame
1132 mlt_image_format img_fmt = mlt_image_yuv422;
1134 // For receiving audio samples back from the fifo
1135 uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1136 uint8_t *audio_buf_2 = NULL;
1139 // Allocate the context
1140 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
1141 AVFormatContext *oc = avformat_alloc_context( );
1143 AVFormatContext *oc = av_alloc_format_context( );
1147 AVStream *video_st = NULL;
1148 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1151 double audio_pts = 0;
1152 double video_pts = 0;
1154 // Frames dispatched
1155 long int frames = 0;
1156 long int total_time = 0;
1158 // Determine the format
1159 AVOutputFormat *fmt = NULL;
1160 const char *filename = mlt_properties_get( properties, "target" );
1161 char *format = mlt_properties_get( properties, "f" );
1162 char *vcodec = mlt_properties_get( properties, "vcodec" );
1163 char *acodec = mlt_properties_get( properties, "acodec" );
1164 AVCodec *audio_codec = NULL;
1165 AVCodec *video_codec = NULL;
1167 // Used to store and override codec ids
1173 mlt_properties frame_meta_properties = mlt_properties_new();
1175 // Initialize audio_st
1176 int i = MAX_AUDIO_STREAMS;
1180 // Check for user selected format first
1181 if ( format != NULL )
1182 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1183 fmt = guess_format( format, NULL, NULL );
1185 fmt = av_guess_format( format, NULL, NULL );
1188 // Otherwise check on the filename
1189 if ( fmt == NULL && filename != NULL )
1190 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1191 fmt = guess_format( NULL, filename, NULL );
1193 fmt = av_guess_format( NULL, filename, NULL );
1196 // Otherwise default to mpeg
1198 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1199 fmt = guess_format( "mpeg", NULL, NULL );
1201 fmt = av_guess_format( "mpeg", NULL, NULL );
1204 // We need a filename - default to stdout?
1205 if ( filename == NULL || !strcmp( filename, "" ) )
1208 // Get the codec ids selected
1209 audio_codec_id = fmt->audio_codec;
1210 video_codec_id = fmt->video_codec;
1212 // Check for audio codec overides
1213 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1214 audio_codec_id = CODEC_ID_NONE;
1217 audio_codec = avcodec_find_encoder_by_name( acodec );
1220 audio_codec_id = audio_codec->id;
1221 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1223 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1224 acodec = mlt_properties_get( properties, "_acodec" );
1225 audio_codec = avcodec_find_encoder_by_name( acodec );
1227 else if ( !strcmp( acodec, "aac" ) )
1229 mlt_properties_set( properties, "astrict", "experimental" );
1234 audio_codec_id = CODEC_ID_NONE;
1235 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1240 audio_codec = avcodec_find_encoder( audio_codec_id );
1243 // Check for video codec overides
1244 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1245 video_codec_id = CODEC_ID_NONE;
1248 video_codec = avcodec_find_encoder_by_name( vcodec );
1251 video_codec_id = video_codec->id;
1255 video_codec_id = CODEC_ID_NONE;
1256 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1261 video_codec = avcodec_find_encoder( video_codec_id );
1265 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1266 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1268 char *name = mlt_properties_get_name( properties, i );
1269 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1271 char *key = strdup( name + 10 );
1272 char *markup = strrchr( key, '.' );
1273 if ( markup && !strcmp( markup, ".markup") )
1276 if ( !strstr( key, ".stream." ) )
1277 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1278 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1279 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1281 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1284 av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1294 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1295 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1297 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1298 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1300 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1301 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1303 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1304 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1306 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1307 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1309 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1310 if (metavalue != 0) oc->year = metavalue;
1312 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1313 if (metavalue != 0) oc->track = metavalue;
1317 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1319 // Get a frame now, so we can set some AVOptions from properties.
1320 frame = mlt_consumer_rt_frame( consumer );
1322 // Set the timecode from the MLT metadata if available.
1325 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1326 if ( timecode && strcmp( timecode, "" ) )
1328 mlt_properties_set( properties, "timecode", timecode );
1329 if ( strchr( timecode, ';' ) )
1330 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1334 // Add audio and video streams
1335 if ( video_codec_id != CODEC_ID_NONE )
1336 video_st = add_video_stream( consumer, oc, video_codec );
1337 if ( audio_codec_id != CODEC_ID_NONE )
1343 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1345 sprintf( key, "channels.%d", i );
1346 int j = mlt_properties_get_int( properties, key );
1350 total_channels += j;
1351 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1357 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1358 total_channels = channels;
1361 mlt_properties_set_int( properties, "channels", total_channels );
1363 // Audio format is determined when adding the audio stream
1364 mlt_audio_format aud_fmt = mlt_audio_none;
1366 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1367 int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1368 sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1370 // Set the parameters (even though we have none...)
1371 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1372 if ( av_set_parameters(oc, NULL) >= 0 )
1375 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1376 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1377 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1379 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1381 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1383 // Process properties as AVOptions
1384 char *fpre = mlt_properties_get( properties, "fpre" );
1387 mlt_properties p = mlt_properties_load( fpre );
1388 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1389 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1390 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1391 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1393 mlt_properties_close( p );
1395 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1396 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1397 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1398 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1401 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1403 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1405 audio_input_frame_size = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1406 acodec? acodec : NULL );
1407 if ( !audio_input_frame_size )
1411 // Setup custom I/O if redirecting
1412 if ( mlt_properties_get_int( properties, "redirect" ) )
1414 int buffer_size = 32768;
1415 unsigned char *buffer = av_malloc( buffer_size );
1416 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1417 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1419 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1424 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1425 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1427 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1428 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1429 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1434 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1437 // Open the output file, if needed
1438 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1440 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1441 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1443 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1446 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1447 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1448 goto on_fatal_error;
1452 // Write the stream header.
1453 if ( mlt_properties_get_int( properties, "running" ) )
1454 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1455 avformat_write_header( oc, NULL );
1457 av_write_header( oc );
1460 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1463 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1464 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1465 goto on_fatal_error;
1471 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1473 // Last check - need at least one stream
1474 if ( !audio_st[0] && !video_st )
1476 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1477 goto on_fatal_error;
1480 // Get the starting time (can ignore the times above)
1481 gettimeofday( &ante, NULL );
1483 // Loop while running
1484 while( mlt_properties_get_int( properties, "running" ) &&
1485 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1488 frame = mlt_consumer_rt_frame( consumer );
1490 // Check that we have a frame to work with
1491 if ( frame != NULL )
1493 // Increment frames dispatched
1496 // Default audio args
1497 frame_properties = MLT_FRAME_PROPERTIES( frame );
1499 // Check for the terminated condition
1500 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1502 // Get audio and append to the fifo
1503 if ( !terminated && audio_st[0] )
1505 samples = mlt_sample_calculator( fps, frequency, count ++ );
1506 channels = total_channels;
1507 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1509 // Save the audio channel remap properties for later
1510 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1512 // Create the fifo if we don't have one
1515 fifo = sample_fifo_init( frequency, channels );
1516 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1520 // Silence if not normal forward speed
1521 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1522 memset( pcm, 0, samples * channels * sample_bytes );
1524 // Append the samples
1525 sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1526 total_time += ( samples * 1000000 ) / frequency;
1529 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1533 if ( !terminated && video_st )
1534 mlt_deque_push_back( queue, frame );
1536 mlt_frame_close( frame );
1540 // While we have stuff to process, process...
1543 // Write interleaved audio and video frames
1544 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1547 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) / sample_bytes )
1549 int j = 0; // channel offset into interleaved source buffer
1550 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1552 // Get the audio samples
1555 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1557 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1559 // This prevents an infinite loop when some versions of vorbis do not
1560 // increment pts when encoding silence.
1561 audio_pts = video_pts;
1566 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1568 samples = n / channels;
1570 // For each output stream
1571 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1573 AVStream *stream = audio_st[i];
1574 AVCodecContext *codec = stream->codec;
1577 av_init_packet( &pkt );
1579 // Optimized for single track and no channel remap
1580 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1582 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_1 );
1586 // Extract the audio channels according to channel mapping
1587 int dest_offset = 0; // channel offset into interleaved dest buffer
1589 // Get the number of channels for this stream
1590 sprintf( key, "channels.%d", i );
1591 int current_channels = mlt_properties_get_int( properties, key );
1593 // Clear the destination audio buffer.
1595 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1597 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1599 // For each output channel
1600 while ( dest_offset < current_channels && j < total_channels )
1602 int map_start = -1, map_channels = 0;
1603 int source_offset = 0;
1606 // Look for a mapping that starts at j
1607 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1609 sprintf( key, "%d.channels", k );
1610 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1611 sprintf( key, "%d.start", k );
1612 if ( mlt_properties_get( frame_meta_properties, key ) )
1613 map_start = mlt_properties_get_int( frame_meta_properties, key );
1614 if ( map_start != j )
1615 source_offset += map_channels;
1619 if ( map_start != j )
1621 map_channels = current_channels;
1625 // Copy samples if source offset valid
1626 if ( source_offset < channels )
1628 // Interleave the audio buffer with the # channels for this stream/mapping.
1629 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1631 void *src = audio_buf_1 + source_offset * sample_bytes;
1632 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1633 int s = samples + 1;
1636 memcpy( dest, src, sample_bytes );
1637 dest += current_channels * sample_bytes;
1638 src += channels * sample_bytes;
1642 // Otherwise silence
1645 j += current_channels;
1646 dest_offset += current_channels;
1649 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1652 // Write the compressed frame in the media file
1653 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1655 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1656 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame pts %"PRId64,
1657 stream->index, pkt.pts, codec->coded_frame->pts );
1659 pkt.flags |= PKT_FLAG_KEY;
1660 pkt.stream_index = stream->index;
1661 pkt.data = audio_outbuf;
1665 if ( av_interleaved_write_frame( oc, &pkt ) )
1667 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1668 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1669 goto on_fatal_error;
1673 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1676 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1685 else if ( video_st )
1688 if ( mlt_deque_count( queue ) )
1690 int out_size, ret = 0;
1693 frame = mlt_deque_pop_front( queue );
1694 frame_properties = MLT_FRAME_PROPERTIES( frame );
1696 c = video_st->codec;
1698 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1704 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1708 // Convert the mlt frame to an AVPicture
1709 for ( i = 0; i < height; i ++ )
1711 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1712 memcpy( p, q, width * 2 );
1716 // Do the colour space conversion
1718 int flags = SWS_BICUBIC;
1720 flags |= SWS_CPU_CAPS_MMX;
1723 flags |= SWS_CPU_CAPS_MMX2;
1725 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1726 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1727 sws_scale( context, (const uint8_t* const*) input->data, input->linesize, 0, height,
1728 output->data, output->linesize);
1729 sws_freeContext( context );
1731 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1734 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1736 // Apply the alpha if applicable
1737 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1739 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1742 for ( i = 0; i < height; i ++ )
1744 n = ( width + 7 ) / 8;
1745 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1749 case 0: do { *p = *alpha++; p += 4;
1750 case 7: *p = *alpha++; p += 4;
1751 case 6: *p = *alpha++; p += 4;
1752 case 5: *p = *alpha++; p += 4;
1753 case 4: *p = *alpha++; p += 4;
1754 case 3: *p = *alpha++; p += 4;
1755 case 2: *p = *alpha++; p += 4;
1756 case 1: *p = *alpha++; p += 4;
1764 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1766 // raw video case. The API will change slightly in the near future for that
1768 av_init_packet(&pkt);
1770 pkt.flags |= PKT_FLAG_KEY;
1771 pkt.stream_index= video_st->index;
1772 pkt.data= (uint8_t *)output;
1773 pkt.size= sizeof(AVPicture);
1775 ret = av_write_frame(oc, &pkt);
1776 video_pts += c->frame_size;
1781 output->quality = c->global_quality;
1783 // Set frame interlace hints
1784 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1785 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1786 output->pts = frame_count;
1789 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1791 // If zero size, it means the image was buffered
1795 av_init_packet( &pkt );
1797 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1798 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1799 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %"PRId64" frame pts %"PRId64, pkt.pts, c->coded_frame->pts );
1800 if( c->coded_frame && c->coded_frame->key_frame )
1801 pkt.flags |= PKT_FLAG_KEY;
1802 pkt.stream_index= video_st->index;
1803 pkt.data= video_outbuf;
1806 // write the compressed frame in the media file
1807 ret = av_interleaved_write_frame(oc, &pkt);
1808 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1809 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1811 // Dual pass logging
1812 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1813 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1815 else if ( out_size < 0 )
1817 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1823 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1824 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1825 goto on_fatal_error;
1827 mlt_frame_close( frame );
1836 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1838 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1839 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1842 if ( real_time_output == 1 && frames % 2 == 0 )
1844 long passed = time_difference( &ante );
1847 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
1850 if ( passed < total_time )
1852 long total = ( total_time - passed );
1853 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1854 nanosleep( &t, NULL );
1859 // Flush the encoder buffers
1860 if ( real_time_output <= 0 )
1863 // TODO: flush all audio streams
1864 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1866 AVCodecContext *c = audio_st[0]->codec;
1868 av_init_packet( &pkt );
1872 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) / sample_bytes ) )
1874 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size * sample_bytes );
1875 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, (short*) audio_buf_1 );
1877 if ( pkt.size <= 0 )
1878 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1879 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1880 if ( pkt.size <= 0 )
1883 // Write the compressed frame in the media file
1884 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1885 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1886 pkt.flags |= PKT_FLAG_KEY;
1887 pkt.stream_index = audio_st[0]->index;
1888 pkt.data = audio_outbuf;
1889 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1891 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1892 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1893 goto on_fatal_error;
1898 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1900 AVCodecContext *c = video_st->codec;
1902 av_init_packet( &pkt );
1905 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1906 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1907 if ( pkt.size <= 0 )
1910 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1911 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1912 if( c->coded_frame && c->coded_frame->key_frame )
1913 pkt.flags |= PKT_FLAG_KEY;
1914 pkt.stream_index = video_st->index;
1915 pkt.data = video_outbuf;
1917 // write the compressed frame in the media file
1918 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1920 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1921 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1922 goto on_fatal_error;
1924 // Dual pass logging
1925 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1926 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1932 // Write the trailer, if any
1934 av_write_trailer( oc );
1938 close_video(oc, video_st);
1939 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1940 close_audio( oc, audio_st[i] );
1943 for ( i = 0; i < oc->nb_streams; i++ )
1944 av_freep( &oc->streams[i] );
1946 // Close the output file
1947 if ( !( fmt->flags & AVFMT_NOFILE ) &&
1948 !mlt_properties_get_int( properties, "redirect" ) )
1950 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1951 if ( oc->pb ) avio_close( oc->pb );
1952 #elif LIBAVFORMAT_VERSION_MAJOR >= 52
1953 if ( oc->pb ) url_fclose( oc->pb );
1955 url_fclose( &oc->pb );
1959 // Clean up input and output frames
1961 av_free( output->data[0] );
1963 av_free( input->data[0] );
1965 av_free( video_outbuf );
1966 av_free( audio_buf_1 );
1967 av_free( audio_buf_2 );
1972 // Just in case we terminated on pause
1973 mlt_consumer_stopped( consumer );
1974 mlt_properties_close( frame_meta_properties );
1976 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1978 // Remove the dual pass log file
1979 if ( mlt_properties_get( properties, "_logfilename" ) )
1980 remove( mlt_properties_get( properties, "_logfilename" ) );
1982 // Remove the x264 dual pass logs
1983 char *cwd = getcwd( NULL, 0 );
1984 const char *file = "x264_2pass.log";
1985 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1986 sprintf( full, "%s/%s", cwd, file );
1989 file = "x264_2pass.log.temp";
1990 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1991 sprintf( full, "%s/%s", cwd, file );
1994 file = "x264_2pass.log.mbtree";
1995 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1996 sprintf( full, "%s/%s", cwd, file );
2000 remove( "x264_2pass.log.temp" );
2003 while ( ( frame = mlt_deque_pop_back( queue ) ) )
2004 mlt_frame_close( frame );
2009 /** Close the consumer.
2012 static void consumer_close( mlt_consumer consumer )
2014 // Stop the consumer
2015 mlt_consumer_stop( consumer );
2018 mlt_consumer_close( consumer );