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>
42 #include <libswscale/swscale.h>
43 #include <libavutil/pixdesc.h>
44 #include <libavutil/mathematics.h>
45 #include <libavutil/samplefmt.h>
47 #if LIBAVCODEC_VERSION_MAJOR >= 53
48 #include <libavutil/opt.h>
49 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
50 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
51 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
53 #include <libavcodec/opt.h>
56 #define MAX_AUDIO_STREAMS (8)
57 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
58 #define AUDIO_BUFFER_SIZE (1024 * 42)
59 #define VIDEO_BUFFER_SIZE (2048 * 1024)
62 // This structure should be extended and made globally available in mlt
74 *sample_fifo, sample_fifo_s;
76 sample_fifo sample_fifo_init( int frequency, int channels )
78 sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
79 fifo->frequency = frequency;
80 fifo->channels = channels;
84 // count is the number of samples multiplied by the number of bytes per sample
85 void sample_fifo_append( sample_fifo fifo, uint8_t *samples, int count )
87 if ( ( fifo->size - fifo->used ) < count )
89 fifo->size += count * 5;
90 fifo->buffer = realloc( fifo->buffer, fifo->size );
93 memcpy( &fifo->buffer[ fifo->used ], samples, count );
97 int sample_fifo_used( sample_fifo fifo )
102 int sample_fifo_fetch( sample_fifo fifo, uint8_t *samples, int count )
104 if ( count > fifo->used )
107 memcpy( samples, fifo->buffer, count );
109 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used );
111 fifo->time += ( double )count / fifo->channels / fifo->frequency;
116 void sample_fifo_close( sample_fifo fifo )
118 free( fifo->buffer );
122 // Forward references.
123 static int consumer_start( mlt_consumer consumer );
124 static int consumer_stop( mlt_consumer consumer );
125 static int consumer_is_stopped( mlt_consumer consumer );
126 static void *consumer_thread( void *arg );
127 static void consumer_close( mlt_consumer consumer );
129 /** Initialise the consumer.
132 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
134 // Allocate the consumer
135 mlt_consumer consumer = mlt_consumer_new( profile );
137 // If memory allocated and initialises without error
138 if ( consumer != NULL )
140 // Get properties from the consumer
141 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
143 // Assign close callback
144 consumer->close = consumer_close;
146 // Interpret the argument
148 mlt_properties_set( properties, "target", arg );
150 // sample and frame queue
151 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
153 // Audio options not fully handled by AVOptions
154 #define QSCALE_NONE (-99999)
155 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
157 // Video options not fully handled by AVOptions
158 mlt_properties_set_int( properties, "dc", 8 );
160 // Muxer options not fully handled by AVOptions
161 mlt_properties_set_double( properties, "muxdelay", 0.7 );
162 mlt_properties_set_double( properties, "muxpreload", 0.5 );
164 // Ensure termination at end of the stream
165 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
167 // Default to separate processing threads for producer and consumer with no frame dropping!
168 mlt_properties_set_int( properties, "real_time", -1 );
169 mlt_properties_set_int( properties, "prefill", 1 );
171 // Set up start/stop/terminated callbacks
172 consumer->start = consumer_start;
173 consumer->stop = consumer_stop;
174 consumer->is_stopped = consumer_is_stopped;
176 mlt_events_register( properties, "consumer-fatal-error", NULL );
183 /** Start the consumer.
186 static int consumer_start( mlt_consumer consumer )
188 // Get the properties
189 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
192 // Report information about available muxers and codecs as YAML Tiny
193 char *s = mlt_properties_get( properties, "f" );
194 if ( s && strcmp( s, "list" ) == 0 )
196 mlt_properties doc = mlt_properties_new();
197 mlt_properties formats = mlt_properties_new();
199 AVOutputFormat *format = NULL;
201 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
202 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
203 while ( ( format = av_oformat_next( format ) ) )
205 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
206 mlt_properties_set( formats, key, format->name );
208 s = mlt_properties_serialise_yaml( doc );
209 fprintf( stdout, "%s", s );
211 mlt_properties_close( doc );
214 s = mlt_properties_get( properties, "acodec" );
215 if ( s && strcmp( s, "list" ) == 0 )
217 mlt_properties doc = mlt_properties_new();
218 mlt_properties codecs = mlt_properties_new();
220 AVCodec *codec = NULL;
222 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
223 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
224 while ( ( codec = av_codec_next( codec ) ) )
225 #if (defined(FFUDIV) && LIBAVCODEC_VERSION_INT >= ((54<<16)+(56<<8)+100)) || (LIBAVCODEC_VERSION_INT >= ((54<<16)+(27<<8)+0))
226 if ( codec->encode2 && codec->type == CODEC_TYPE_AUDIO )
227 #elif LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
228 if ( ( codec->encode || codec->encode2 ) && codec->type == CODEC_TYPE_AUDIO )
230 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
233 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
234 mlt_properties_set( codecs, key, codec->name );
236 s = mlt_properties_serialise_yaml( doc );
237 fprintf( stdout, "%s", s );
239 mlt_properties_close( doc );
242 s = mlt_properties_get( properties, "vcodec" );
243 if ( s && strcmp( s, "list" ) == 0 )
245 mlt_properties doc = mlt_properties_new();
246 mlt_properties codecs = mlt_properties_new();
248 AVCodec *codec = NULL;
250 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
251 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
252 while ( ( codec = av_codec_next( codec ) ) )
253 #if (defined(FFUDIV) && LIBAVCODEC_VERSION_INT >= ((54<<16)+(56<<8)+100)) || (LIBAVCODEC_VERSION_INT >= ((54<<16)+(27<<8)+0))
254 if ( codec->encode2 && codec->type == CODEC_TYPE_VIDEO )
255 #elif LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
256 if ( (codec->encode || codec->encode2) && codec->type == CODEC_TYPE_VIDEO )
258 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
261 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
262 mlt_properties_set( codecs, key, codec->name );
264 s = mlt_properties_serialise_yaml( doc );
265 fprintf( stdout, "%s", s );
267 mlt_properties_close( doc );
271 // Check that we're not already running
272 if ( !error && !mlt_properties_get_int( properties, "running" ) )
275 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
277 // Get the width and height
278 int width = mlt_properties_get_int( properties, "width" );
279 int height = mlt_properties_get_int( properties, "height" );
281 // Obtain the size property
282 char *size = mlt_properties_get( properties, "s" );
288 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
295 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Invalid size property %s - ignoring.\n", size );
299 // Now ensure we honour the multiple of two requested by libavformat
300 width = ( width / 2 ) * 2;
301 height = ( height / 2 ) * 2;
302 mlt_properties_set_int( properties, "width", width );
303 mlt_properties_set_int( properties, "height", height );
305 // We need to set these on the profile as well because the s property is
306 // an alias to mlt properties that correspond to profile settings.
307 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
310 profile->width = width;
311 profile->height = height;
314 if ( mlt_properties_get( properties, "aspect" ) )
316 // "-aspect" on ffmpeg command line is display aspect ratio
317 double ar = mlt_properties_get_double( properties, "aspect" );
318 AVRational rational = av_d2q( ar, 255 );
320 // Update the profile and properties as well since this is an alias
321 // for mlt properties that correspond to profile settings
322 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
323 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
326 profile->display_aspect_num = rational.num;
327 profile->display_aspect_den = rational.den;
328 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
331 // Now compute the sample aspect ratio
332 rational = av_d2q( ar * height / width, 255 );
334 // Update the profile and properties as well since this is an alias
335 // for mlt properties that correspond to profile settings
336 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
337 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
340 profile->sample_aspect_num = rational.num;
341 profile->sample_aspect_den = rational.den;
342 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
346 // Handle the ffmpeg command line "-r" property for frame rate
347 if ( mlt_properties_get( properties, "r" ) )
349 double frame_rate = mlt_properties_get_double( properties, "r" );
350 AVRational rational = av_d2q( frame_rate, 255 );
351 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
352 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
355 profile->frame_rate_num = rational.num;
356 profile->frame_rate_den = rational.den;
357 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
361 // Apply AVOptions that are synonyms for standard mlt_consumer options
362 if ( mlt_properties_get( properties, "ac" ) )
363 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
364 if ( mlt_properties_get( properties, "ar" ) )
365 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
367 // Assign the thread to properties
368 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
371 pthread_create( thread, NULL, consumer_thread, consumer );
373 // Set the running state
374 mlt_properties_set_int( properties, "running", 1 );
379 /** Stop the consumer.
382 static int consumer_stop( mlt_consumer consumer )
384 // Get the properties
385 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
386 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
388 // Check that we're running
392 mlt_properties_set_int( properties, "running", 0 );
394 // Wait for termination
395 pthread_join( *thread, NULL );
397 mlt_properties_set_data( properties, "thread", NULL, 0, NULL, NULL );
403 /** Determine if the consumer is stopped.
406 static int consumer_is_stopped( mlt_consumer consumer )
408 // Get the properties
409 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
410 return !mlt_properties_get_int( properties, "running" );
413 /** Process properties as AVOptions and apply to AV context obj
416 static void apply_properties( void *obj, mlt_properties properties, int flags )
419 int count = mlt_properties_count( properties );
420 #if LIBAVUTIL_VERSION_INT < ((51<<16)+(12<<8)+0)
424 for ( i = 0; i < count; i++ )
426 const char *opt_name = mlt_properties_get_name( properties, i );
427 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
428 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
430 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
433 // If option not found, see if it was prefixed with a or v (-vb)
435 ( opt_name[0] == 'v' && ( flags & AV_OPT_FLAG_VIDEO_PARAM ) ) ||
436 ( opt_name[0] == 'a' && ( flags & AV_OPT_FLAG_AUDIO_PARAM ) ) ) )
437 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
438 opt = av_opt_find( obj, ++opt_name, NULL, flags, flags );
440 opt = av_find_opt( obj, ++opt_name, NULL, flags, flags );
442 // Apply option if found
444 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
445 av_opt_set( obj, opt_name, mlt_properties_get_value( properties, i), 0 );
447 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
452 static int get_mlt_audio_format( int av_sample_fmt )
454 switch ( av_sample_fmt )
456 case AV_SAMPLE_FMT_U8:
458 case AV_SAMPLE_FMT_S32:
459 return mlt_audio_s32le;
460 case AV_SAMPLE_FMT_FLT:
461 return mlt_audio_f32le;
462 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
463 case AV_SAMPLE_FMT_U8P:
465 case AV_SAMPLE_FMT_S32P:
466 return mlt_audio_s32le;
467 case AV_SAMPLE_FMT_FLTP:
468 return mlt_audio_f32le;
471 return mlt_audio_s16;
475 static int pick_sample_fmt( mlt_properties properties, AVCodec *codec )
477 int sample_fmt = AV_SAMPLE_FMT_S16;
478 const char *format = mlt_properties_get( properties, "mlt_audio_format" );
479 const int *p = codec->sample_fmts;
481 // get default av_sample_fmt from mlt_audio_format
484 if ( !strcmp( format, "s32le" ) )
485 sample_fmt = AV_SAMPLE_FMT_S32;
486 else if ( !strcmp( format, "f32le" ) )
487 sample_fmt = AV_SAMPLE_FMT_FLT;
488 else if ( !strcmp( format, "u8" ) )
489 sample_fmt = AV_SAMPLE_FMT_U8;
490 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
491 else if ( !strcmp( format, "s32" ) )
492 sample_fmt = AV_SAMPLE_FMT_S32P;
493 else if ( !strcmp( format, "float" ) )
494 sample_fmt = AV_SAMPLE_FMT_FLTP;
497 // check if codec supports our mlt_audio_format
498 for ( ; *p != -1; p++ )
500 if ( *p == sample_fmt )
503 // no match - pick first one we support
504 for ( p = codec->sample_fmts; *p != -1; p++ )
508 case AV_SAMPLE_FMT_U8:
509 case AV_SAMPLE_FMT_S16:
510 case AV_SAMPLE_FMT_S32:
511 case AV_SAMPLE_FMT_FLT:
512 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
513 case AV_SAMPLE_FMT_U8P:
514 case AV_SAMPLE_FMT_S16P:
515 case AV_SAMPLE_FMT_S32P:
516 case AV_SAMPLE_FMT_FLTP:
523 mlt_log_error( properties, "audio codec sample_fmt not compatible" );
525 return AV_SAMPLE_FMT_NONE;
528 static uint8_t* interleaved_to_planar( int samples, int channels, uint8_t* audio, int bytes_per_sample )
530 int size = samples * channels * bytes_per_sample;
531 uint8_t *buffer = mlt_pool_alloc( AUDIO_ENCODE_BUFFER_SIZE );
535 memset( buffer, 0, AUDIO_ENCODE_BUFFER_SIZE );
536 for ( c = 0; c < channels; c++ )
538 uint8_t *q = audio + c * bytes_per_sample;
542 memcpy( p, q, bytes_per_sample );
543 p += bytes_per_sample;
544 q += channels * bytes_per_sample;
550 /** Add an audio output stream
553 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec, int channels )
555 // Get the properties
556 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
558 // Create a new stream
559 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
560 AVStream *st = avformat_new_stream( oc, codec );
562 AVStream *st = av_new_stream( oc, oc->nb_streams );
565 // If created, then initialise from properties
568 AVCodecContext *c = st->codec;
570 // Establish defaults from AVOptions
571 #if LIBAVCODEC_VERSION_MAJOR >= 53
572 avcodec_get_context_defaults3( c, codec );
574 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
577 c->codec_id = codec->id;
578 c->codec_type = CODEC_TYPE_AUDIO;
579 c->sample_fmt = pick_sample_fmt( properties, codec );
581 #if 0 // disabled until some audio codecs are multi-threaded
582 // Setup multi-threading
583 int thread_count = mlt_properties_get_int( properties, "threads" );
584 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
585 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
586 if ( thread_count > 1 )
587 c->thread_count = thread_count;
590 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
591 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
593 // Allow the user to override the audio fourcc
594 if ( mlt_properties_get( properties, "atag" ) )
597 char *arg = mlt_properties_get( properties, "atag" );
598 int tag = strtol( arg, &tail, 0);
600 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
604 // Process properties as AVOptions
605 char *apre = mlt_properties_get( properties, "apre" );
608 mlt_properties p = mlt_properties_load( apre );
609 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
610 mlt_properties_close( p );
612 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
614 int audio_qscale = mlt_properties_get_int( properties, "aq" );
615 if ( audio_qscale > QSCALE_NONE )
617 c->flags |= CODEC_FLAG_QSCALE;
618 c->global_quality = FF_QP2LAMBDA * audio_qscale;
619 #if LIBAVFORMAT_VERSION_MAJOR < 53
620 st->quality = c->global_quality;
624 // Set parameters controlled by MLT
625 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
626 c->time_base = ( AVRational ){ 1, c->sample_rate };
627 c->channels = channels;
629 if ( mlt_properties_get( properties, "alang" ) != NULL )
630 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
631 av_dict_set( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
633 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
638 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
644 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
646 // We will return the audio input size from here
647 int audio_input_frame_size = 0;
650 AVCodecContext *c = st->codec;
655 codec = avcodec_find_encoder_by_name( codec_name );
657 codec = avcodec_find_encoder( c->codec_id );
659 // Process properties as AVOptions on the AVCodec
660 if ( codec && codec->priv_class )
662 char *apre = mlt_properties_get( properties, "apre" );
663 if ( !c->priv_data && codec->priv_data_size )
665 c->priv_data = av_mallocz( codec->priv_data_size );
666 *(const AVClass **) c->priv_data = codec->priv_class;
667 // av_opt_set_defaults( c );
671 mlt_properties p = mlt_properties_load( apre );
672 apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
673 mlt_properties_close( p );
675 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
678 // Continue if codec found and we can open it
679 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
680 if ( codec && avcodec_open2( c, codec, NULL ) >= 0 )
682 if ( codec && avcodec_open( c, codec ) >= 0 )
685 // ugly hack for PCM codecs (will be removed ASAP with new PCM
686 // support to compute the input frame size in samples
687 if ( c->frame_size <= 1 )
689 audio_input_frame_size = audio_outbuf_size / c->channels;
690 switch(st->codec->codec_id)
692 case CODEC_ID_PCM_S16LE:
693 case CODEC_ID_PCM_S16BE:
694 case CODEC_ID_PCM_U16LE:
695 case CODEC_ID_PCM_U16BE:
696 audio_input_frame_size >>= 1;
704 audio_input_frame_size = c->frame_size;
707 // Some formats want stream headers to be seperate (hmm)
708 if ( !strcmp( oc->oformat->name, "mp4" ) ||
709 !strcmp( oc->oformat->name, "mov" ) ||
710 !strcmp( oc->oformat->name, "3gp" ) )
711 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
715 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
716 audio_input_frame_size = 0;
719 return audio_input_frame_size;
722 static void close_audio( AVFormatContext *oc, AVStream *st )
724 if ( st && st->codec )
725 avcodec_close( st->codec );
728 /** Add a video output stream
731 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
733 // Get the properties
734 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
736 // Create a new stream
737 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
738 AVStream *st = avformat_new_stream( oc, codec );
740 AVStream *st = av_new_stream( oc, oc->nb_streams );
745 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
746 AVCodecContext *c = st->codec;
748 // Establish defaults from AVOptions
749 #if LIBAVCODEC_VERSION_MAJOR >= 53
750 avcodec_get_context_defaults3( c, codec );
752 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
755 c->codec_id = codec->id;
756 c->codec_type = CODEC_TYPE_VIDEO;
758 // Setup multi-threading
759 int thread_count = mlt_properties_get_int( properties, "threads" );
760 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
761 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
762 if ( thread_count > 1 )
763 #if LIBAVCODEC_VERSION_MAJOR >= 53
764 c->thread_count = thread_count;
766 avcodec_thread_init( c, thread_count );
769 // Process properties as AVOptions
770 char *vpre = mlt_properties_get( properties, "vpre" );
773 mlt_properties p = mlt_properties_load( vpre );
775 if ( mlt_properties_count( p ) < 1 )
777 AVCodec *codec = avcodec_find_encoder( c->codec_id );
780 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
781 strcpy( path, AVDATADIR );
782 strcat( path, codec->name );
784 strcat( path, vpre );
785 strcat( path, ".ffpreset" );
787 mlt_properties_close( p );
788 p = mlt_properties_load( path );
789 if ( mlt_properties_count( p ) > 0 )
790 mlt_properties_debug( p, path, stderr );
796 mlt_properties_debug( p, vpre, stderr );
799 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
800 mlt_properties_close( p );
802 int colorspace = mlt_properties_get_int( properties, "colorspace" );
803 mlt_properties_set( properties, "colorspace", NULL );
804 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
805 mlt_properties_set_int( properties, "colorspace", colorspace );
807 // Set options controlled by MLT
808 c->width = mlt_properties_get_int( properties, "width" );
809 c->height = mlt_properties_get_int( properties, "height" );
810 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
811 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
812 if ( st->time_base.den == 0 )
813 st->time_base = c->time_base;
814 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
816 switch ( colorspace )
819 c->colorspace = AVCOL_SPC_SMPTE170M;
822 c->colorspace = AVCOL_SPC_SMPTE240M;
825 c->colorspace = AVCOL_SPC_BT470BG;
828 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
831 c->colorspace = AVCOL_SPC_BT709;
835 if ( mlt_properties_get( properties, "aspect" ) )
837 // "-aspect" on ffmpeg command line is display aspect ratio
838 double ar = mlt_properties_get_double( properties, "aspect" );
839 c->sample_aspect_ratio = av_d2q( ar * c->height / c->width, 255 );
843 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
844 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
846 st->sample_aspect_ratio = c->sample_aspect_ratio;
848 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
850 c->flags |= CODEC_FLAG_QSCALE;
851 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
852 #if LIBAVFORMAT_VERSION_MAJOR < 53
853 st->quality = c->global_quality;
857 // Allow the user to override the video fourcc
858 if ( mlt_properties_get( properties, "vtag" ) )
861 const char *arg = mlt_properties_get( properties, "vtag" );
862 int tag = strtol( arg, &tail, 0);
864 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
868 // Some formats want stream headers to be seperate
869 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
870 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
872 // Translate these standard mlt consumer properties to ffmpeg
873 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
874 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
876 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
877 c->flags |= CODEC_FLAG_INTERLACED_DCT;
878 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
879 c->flags |= CODEC_FLAG_INTERLACED_ME;
882 // parse the ratecontrol override string
884 char *rc_override = mlt_properties_get( properties, "rc_override" );
885 for ( i = 0; rc_override; i++ )
888 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
890 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
891 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
892 c->rc_override[i].start_frame = start;
893 c->rc_override[i].end_frame = end;
896 c->rc_override[i].qscale = q;
897 c->rc_override[i].quality_factor = 1.0;
901 c->rc_override[i].qscale = 0;
902 c->rc_override[i].quality_factor = -q / 100.0;
904 rc_override = strchr( rc_override, '/' );
908 c->rc_override_count = i;
909 if ( !c->rc_initial_buffer_occupancy )
910 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
911 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
914 i = mlt_properties_get_int( properties, "pass" );
916 c->flags |= CODEC_FLAG_PASS1;
918 c->flags |= CODEC_FLAG_PASS2;
919 if ( codec->id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
921 char logfilename[1024];
926 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
927 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
928 if ( c->flags & CODEC_FLAG_PASS1 )
930 f = fopen( logfilename, "w" );
932 perror( logfilename );
934 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
938 /* read the log file */
939 f = fopen( logfilename, "r" );
946 mlt_properties_set( properties, "_logfilename", logfilename );
947 fseek( f, 0, SEEK_END );
949 fseek( f, 0, SEEK_SET );
950 logbuffer = av_malloc( size + 1 );
952 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
957 size = fread( logbuffer, 1, size, f );
958 logbuffer[size] = '\0';
959 c->stats_in = logbuffer;
969 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
975 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
978 AVFrame *picture = avcodec_alloc_frame();
980 // Determine size of the
981 int size = avpicture_get_size(pix_fmt, width, height);
983 // Allocate the picture buf
984 uint8_t *picture_buf = av_malloc(size);
986 // If we have both, then fill the image
987 if ( picture != NULL && picture_buf != NULL )
989 // Fill the frame with the allocated buffer
990 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
994 // Something failed - clean up what we can
996 av_free( picture_buf );
1003 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
1006 AVCodecContext *video_enc = st->codec;
1008 // find the video encoder
1011 codec = avcodec_find_encoder_by_name( codec_name );
1013 codec = avcodec_find_encoder( video_enc->codec_id );
1015 // Process properties as AVOptions on the AVCodec
1016 if ( codec && codec->priv_class )
1018 char *vpre = mlt_properties_get( properties, "vpre" );
1019 if ( !video_enc->priv_data && codec->priv_data_size )
1021 video_enc->priv_data = av_mallocz( codec->priv_data_size );
1022 *(const AVClass **) video_enc->priv_data = codec->priv_class;
1023 // av_opt_set_defaults( video_enc );
1027 mlt_properties p = mlt_properties_load( vpre );
1028 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1029 mlt_properties_close( p );
1031 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1034 if( codec && codec->pix_fmts )
1036 const enum PixelFormat *p = codec->pix_fmts;
1037 for( ; *p!=-1; p++ )
1039 if( *p == video_enc->pix_fmt )
1043 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1046 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1047 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1049 int result = codec && avcodec_open( video_enc, codec ) >= 0;
1055 void close_video(AVFormatContext *oc, AVStream *st)
1057 if ( st && st->codec )
1059 av_freep( &st->codec->stats_in );
1060 avcodec_close(st->codec);
1064 static inline long time_difference( struct timeval *time1 )
1066 struct timeval time2;
1067 gettimeofday( &time2, NULL );
1068 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1071 static int mlt_write(void *h, uint8_t *buf, int size)
1073 mlt_properties properties = (mlt_properties) h;
1074 mlt_events_fire( properties, "avformat-write", buf, size, NULL );
1078 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1080 listener( owner, service, (uint8_t*) args[0], (int) args[1] );
1083 /** The main thread - the argument is simply the consumer.
1086 static void *consumer_thread( void *arg )
1088 // Map the argument to the object
1089 mlt_consumer consumer = arg;
1091 // Get the properties
1092 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1094 // Get the terminate on pause property
1095 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1098 // Determine if feed is slow (for realtime stuff)
1099 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1102 struct timeval ante;
1104 // Get the frame rate
1105 double fps = mlt_properties_get_double( properties, "fps" );
1107 // Get width and height
1108 int width = mlt_properties_get_int( properties, "width" );
1109 int height = mlt_properties_get_int( properties, "height" );
1110 int img_width = width;
1111 int img_height = height;
1113 // Get default audio properties
1114 int channels = mlt_properties_get_int( properties, "channels" );
1115 int total_channels = channels;
1116 int frequency = mlt_properties_get_int( properties, "frequency" );
1120 // AVFormat audio buffer and frame size
1121 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1122 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1123 int audio_input_frame_size = 0;
1125 // AVFormat video buffer and frame count
1126 int frame_count = 0;
1127 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1128 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1130 // Used for the frame properties
1131 mlt_frame frame = NULL;
1132 mlt_properties frame_properties = NULL;
1135 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1136 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1138 // Need two av pictures for converting
1139 AVFrame *output = NULL;
1140 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
1142 // For receiving images from an mlt_frame
1144 mlt_image_format img_fmt = mlt_image_yuv422;
1146 // For receiving audio samples back from the fifo
1147 uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1148 uint8_t *audio_buf_2 = NULL;
1151 // Allocate the context
1152 AVFormatContext *oc = avformat_alloc_context( );
1155 AVStream *video_st = NULL;
1156 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1159 double audio_pts = 0;
1160 double video_pts = 0;
1162 // Frames dispatched
1163 long int frames = 0;
1164 long int total_time = 0;
1166 // Determine the format
1167 AVOutputFormat *fmt = NULL;
1168 const char *filename = mlt_properties_get( properties, "target" );
1169 char *format = mlt_properties_get( properties, "f" );
1170 char *vcodec = mlt_properties_get( properties, "vcodec" );
1171 char *acodec = mlt_properties_get( properties, "acodec" );
1172 AVCodec *audio_codec = NULL;
1173 AVCodec *video_codec = NULL;
1175 // Used to store and override codec ids
1181 mlt_properties frame_meta_properties = mlt_properties_new();
1183 // Initialize audio_st
1184 int i = MAX_AUDIO_STREAMS;
1188 // Check for user selected format first
1189 if ( format != NULL )
1190 fmt = av_guess_format( format, NULL, NULL );
1192 // Otherwise check on the filename
1193 if ( fmt == NULL && filename != NULL )
1194 fmt = av_guess_format( NULL, filename, NULL );
1196 // Otherwise default to mpeg
1198 fmt = av_guess_format( "mpeg", NULL, NULL );
1200 // We need a filename - default to stdout?
1201 if ( filename == NULL || !strcmp( filename, "" ) )
1204 // Get the codec ids selected
1205 audio_codec_id = fmt->audio_codec;
1206 video_codec_id = fmt->video_codec;
1208 // Check for audio codec overides
1209 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1210 audio_codec_id = CODEC_ID_NONE;
1213 audio_codec = avcodec_find_encoder_by_name( acodec );
1216 audio_codec_id = audio_codec->id;
1217 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1219 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1220 acodec = mlt_properties_get( properties, "_acodec" );
1221 audio_codec = avcodec_find_encoder_by_name( acodec );
1223 else if ( !strcmp( acodec, "aac" ) )
1225 mlt_properties_set( properties, "astrict", "experimental" );
1230 audio_codec_id = CODEC_ID_NONE;
1231 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1236 audio_codec = avcodec_find_encoder( audio_codec_id );
1239 // Check for video codec overides
1240 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1241 video_codec_id = CODEC_ID_NONE;
1244 video_codec = avcodec_find_encoder_by_name( vcodec );
1247 video_codec_id = video_codec->id;
1251 video_codec_id = CODEC_ID_NONE;
1252 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1257 video_codec = avcodec_find_encoder( video_codec_id );
1261 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1263 char *name = mlt_properties_get_name( properties, i );
1264 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1266 char *key = strdup( name + 10 );
1267 char *markup = strrchr( key, '.' );
1268 if ( markup && !strcmp( markup, ".markup") )
1271 if ( !strstr( key, ".stream." ) )
1272 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1273 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1275 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1283 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1285 // Get a frame now, so we can set some AVOptions from properties.
1286 frame = mlt_consumer_rt_frame( consumer );
1288 // Set the timecode from the MLT metadata if available.
1291 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1292 if ( timecode && strcmp( timecode, "" ) )
1294 mlt_properties_set( properties, "timecode", timecode );
1295 if ( strchr( timecode, ';' ) )
1296 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1300 // Add audio and video streams
1301 if ( video_codec_id != CODEC_ID_NONE )
1302 video_st = add_video_stream( consumer, oc, video_codec );
1303 if ( audio_codec_id != CODEC_ID_NONE )
1309 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1311 sprintf( key, "channels.%d", i );
1312 int j = mlt_properties_get_int( properties, key );
1316 total_channels += j;
1317 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1323 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1324 total_channels = channels;
1327 mlt_properties_set_int( properties, "channels", total_channels );
1329 // Audio format is determined when adding the audio stream
1330 mlt_audio_format aud_fmt = mlt_audio_none;
1332 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1333 int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1334 sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1336 // Set the parameters (even though we have none...)
1337 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1338 if ( av_set_parameters(oc, NULL) >= 0 )
1341 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1342 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1343 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1345 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1347 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1349 // Process properties as AVOptions
1350 char *fpre = mlt_properties_get( properties, "fpre" );
1353 mlt_properties p = mlt_properties_load( fpre );
1354 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1355 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1356 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1357 mlt_properties_close( p );
1359 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1360 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1361 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1363 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1365 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1367 audio_input_frame_size = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1368 acodec? acodec : NULL );
1369 if ( !audio_input_frame_size )
1371 // Remove the audio stream from the output context
1373 for ( j = 0; j < oc->nb_streams; j++ )
1375 if ( oc->streams[j] == audio_st[i] )
1376 av_freep( &oc->streams[j] );
1383 // Setup custom I/O if redirecting
1384 if ( mlt_properties_get_int( properties, "redirect" ) )
1386 int buffer_size = 32768;
1387 unsigned char *buffer = av_malloc( buffer_size );
1388 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1389 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1391 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1396 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1397 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1399 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1400 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1401 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1406 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1409 // Open the output file, if needed
1410 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1412 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1413 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1415 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1418 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1419 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1420 goto on_fatal_error;
1424 // Write the stream header.
1425 if ( mlt_properties_get_int( properties, "running" ) )
1426 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1427 avformat_write_header( oc, NULL );
1429 av_write_header( oc );
1432 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1435 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1436 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1437 goto on_fatal_error;
1443 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1445 // Last check - need at least one stream
1446 if ( !audio_st[0] && !video_st )
1448 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1449 goto on_fatal_error;
1452 // Get the starting time (can ignore the times above)
1453 gettimeofday( &ante, NULL );
1455 // Loop while running
1456 while( mlt_properties_get_int( properties, "running" ) &&
1457 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1460 frame = mlt_consumer_rt_frame( consumer );
1462 // Check that we have a frame to work with
1463 if ( frame != NULL )
1465 // Increment frames dispatched
1468 // Default audio args
1469 frame_properties = MLT_FRAME_PROPERTIES( frame );
1471 // Check for the terminated condition
1472 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1474 // Get audio and append to the fifo
1475 if ( !terminated && audio_st[0] )
1477 samples = mlt_sample_calculator( fps, frequency, count ++ );
1478 channels = total_channels;
1479 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1481 // Save the audio channel remap properties for later
1482 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1484 // Create the fifo if we don't have one
1487 fifo = sample_fifo_init( frequency, channels );
1488 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1492 // Silence if not normal forward speed
1493 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1494 memset( pcm, 0, samples * channels * sample_bytes );
1496 // Append the samples
1497 sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1498 total_time += ( samples * 1000000 ) / frequency;
1501 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1505 if ( !terminated && video_st )
1506 mlt_deque_push_back( queue, frame );
1508 mlt_frame_close( frame );
1512 // While we have stuff to process, process...
1515 // Write interleaved audio and video frames
1516 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1519 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) / sample_bytes )
1521 int j = 0; // channel offset into interleaved source buffer
1522 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1524 // Get the audio samples
1527 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1529 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1531 // This prevents an infinite loop when some versions of vorbis do not
1532 // increment pts when encoding silence.
1533 audio_pts = video_pts;
1538 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1540 samples = n / channels;
1542 // For each output stream
1543 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1545 AVStream *stream = audio_st[i];
1546 AVCodecContext *codec = stream->codec;
1549 av_init_packet( &pkt );
1551 // Optimized for single track and no channel remap
1552 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1554 void* p = audio_buf_1;
1555 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1556 if ( codec->sample_fmt == AV_SAMPLE_FMT_FLTP )
1557 p = interleaved_to_planar( samples, channels, p, sizeof( float ) );
1558 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S16P )
1559 p = interleaved_to_planar( samples, channels, p, sizeof( int16_t ) );
1560 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S32P )
1561 p = interleaved_to_planar( samples, channels, p, sizeof( int32_t ) );
1562 else if ( codec->sample_fmt == AV_SAMPLE_FMT_U8P )
1563 p = interleaved_to_planar( samples, channels, p, sizeof( uint8_t ) );
1565 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, p );
1567 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1568 if ( p != audio_buf_1 )
1569 mlt_pool_release( p );
1574 // Extract the audio channels according to channel mapping
1575 int dest_offset = 0; // channel offset into interleaved dest buffer
1577 // Get the number of channels for this stream
1578 sprintf( key, "channels.%d", i );
1579 int current_channels = mlt_properties_get_int( properties, key );
1581 // Clear the destination audio buffer.
1583 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1585 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1587 // For each output channel
1588 while ( dest_offset < current_channels && j < total_channels )
1590 int map_start = -1, map_channels = 0;
1591 int source_offset = 0;
1594 // Look for a mapping that starts at j
1595 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1597 sprintf( key, "%d.channels", k );
1598 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1599 sprintf( key, "%d.start", k );
1600 if ( mlt_properties_get( frame_meta_properties, key ) )
1601 map_start = mlt_properties_get_int( frame_meta_properties, key );
1602 if ( map_start != j )
1603 source_offset += map_channels;
1607 if ( map_start != j )
1609 map_channels = current_channels;
1613 // Copy samples if source offset valid
1614 if ( source_offset < channels )
1616 // Interleave the audio buffer with the # channels for this stream/mapping.
1617 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1619 void *src = audio_buf_1 + source_offset * sample_bytes;
1620 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1621 int s = samples + 1;
1624 memcpy( dest, src, sample_bytes );
1625 dest += current_channels * sample_bytes;
1626 src += channels * sample_bytes;
1630 // Otherwise silence
1633 j += current_channels;
1634 dest_offset += current_channels;
1637 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1640 // Write the compressed frame in the media file
1641 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1643 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1644 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame pts %"PRId64,
1645 stream->index, pkt.pts, codec->coded_frame->pts );
1647 pkt.flags |= PKT_FLAG_KEY;
1648 pkt.stream_index = stream->index;
1649 pkt.data = audio_outbuf;
1653 if ( av_interleaved_write_frame( oc, &pkt ) )
1655 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1656 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1657 goto on_fatal_error;
1661 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1664 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1673 else if ( video_st )
1676 if ( mlt_deque_count( queue ) )
1678 int out_size, ret = 0;
1681 frame = mlt_deque_pop_front( queue );
1682 frame_properties = MLT_FRAME_PROPERTIES( frame );
1684 c = video_st->codec;
1686 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1692 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1696 // Convert the mlt frame to an AVPicture
1697 for ( i = 0; i < height; i ++ )
1699 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1700 memcpy( p, q, width * 2 );
1704 // Do the colour space conversion
1705 int flags = SWS_BICUBIC;
1707 flags |= SWS_CPU_CAPS_MMX;
1710 flags |= SWS_CPU_CAPS_MMX2;
1712 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1713 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1714 sws_scale( context, (const uint8_t* const*) input->data, input->linesize, 0, height,
1715 output->data, output->linesize);
1716 sws_freeContext( context );
1718 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1720 // Apply the alpha if applicable
1721 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1723 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1726 for ( i = 0; i < height; i ++ )
1728 n = ( width + 7 ) / 8;
1729 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1733 case 0: do { *p = *alpha++; p += 4;
1734 case 7: *p = *alpha++; p += 4;
1735 case 6: *p = *alpha++; p += 4;
1736 case 5: *p = *alpha++; p += 4;
1737 case 4: *p = *alpha++; p += 4;
1738 case 3: *p = *alpha++; p += 4;
1739 case 2: *p = *alpha++; p += 4;
1740 case 1: *p = *alpha++; p += 4;
1748 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1750 // raw video case. The API will change slightly in the near future for that
1752 av_init_packet(&pkt);
1754 // Set frame interlace hints
1755 c->coded_frame->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1756 c->coded_frame->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1757 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(61<<8)+100)
1758 if ( mlt_properties_get_int( frame_properties, "progressive" ) )
1759 c->field_order = AV_FIELD_PROGRESSIVE;
1761 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TT : AV_FIELD_BB;
1763 pkt.flags |= PKT_FLAG_KEY;
1764 pkt.stream_index= video_st->index;
1765 pkt.data= (uint8_t *)output;
1766 pkt.size= sizeof(AVPicture);
1768 ret = av_write_frame(oc, &pkt);
1769 video_pts += c->frame_size;
1774 output->quality = c->global_quality;
1776 // Set frame interlace hints
1777 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1778 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1779 output->pts = frame_count;
1782 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1784 // If zero size, it means the image was buffered
1788 av_init_packet( &pkt );
1790 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1791 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1792 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %"PRId64" frame pts %"PRId64, pkt.pts, c->coded_frame->pts );
1793 if( c->coded_frame && c->coded_frame->key_frame )
1794 pkt.flags |= PKT_FLAG_KEY;
1795 pkt.stream_index= video_st->index;
1796 pkt.data= video_outbuf;
1799 // write the compressed frame in the media file
1800 ret = av_interleaved_write_frame(oc, &pkt);
1801 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1802 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1804 // Dual pass logging
1805 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1806 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1808 else if ( out_size < 0 )
1810 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1816 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1817 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1818 goto on_fatal_error;
1820 mlt_frame_close( frame );
1829 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1831 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1832 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1835 if ( real_time_output == 1 && frames % 2 == 0 )
1837 long passed = time_difference( &ante );
1840 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
1843 if ( passed < total_time )
1845 long total = ( total_time - passed );
1846 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1847 nanosleep( &t, NULL );
1852 // Flush the encoder buffers
1853 if ( real_time_output <= 0 )
1856 // TODO: flush all audio streams
1857 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1859 AVCodecContext *c = audio_st[0]->codec;
1861 av_init_packet( &pkt );
1865 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) / sample_bytes ) )
1867 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size * sample_bytes );
1868 void* p = audio_buf_1;
1869 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1870 if ( c->sample_fmt == AV_SAMPLE_FMT_FLTP )
1871 p = interleaved_to_planar( audio_input_frame_size, channels, p, sizeof( float ) );
1872 else if ( c->sample_fmt == AV_SAMPLE_FMT_S16P )
1873 p = interleaved_to_planar( audio_input_frame_size, channels, p, sizeof( int16_t ) );
1874 else if ( c->sample_fmt == AV_SAMPLE_FMT_S32P )
1875 p = interleaved_to_planar( audio_input_frame_size, channels, p, sizeof( int32_t ) );
1876 else if ( c->sample_fmt == AV_SAMPLE_FMT_U8P )
1877 p = interleaved_to_planar( audio_input_frame_size, channels, p, sizeof( uint8_t ) );
1879 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, p );
1880 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1881 if ( p != audio_buf_1 )
1882 mlt_pool_release( p );
1885 if ( pkt.size <= 0 )
1886 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1887 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1888 if ( pkt.size <= 0 )
1891 // Write the compressed frame in the media file
1892 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1893 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1894 pkt.flags |= PKT_FLAG_KEY;
1895 pkt.stream_index = audio_st[0]->index;
1896 pkt.data = audio_outbuf;
1897 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1899 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1900 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1901 goto on_fatal_error;
1906 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1908 AVCodecContext *c = video_st->codec;
1910 av_init_packet( &pkt );
1913 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1914 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1915 if ( pkt.size <= 0 )
1918 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1919 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1920 if( c->coded_frame && c->coded_frame->key_frame )
1921 pkt.flags |= PKT_FLAG_KEY;
1922 pkt.stream_index = video_st->index;
1923 pkt.data = video_outbuf;
1925 // write the compressed frame in the media file
1926 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1928 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1929 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1930 goto on_fatal_error;
1932 // Dual pass logging
1933 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1934 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1940 // Write the trailer, if any
1942 av_write_trailer( oc );
1946 close_video(oc, video_st);
1947 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1948 close_audio( oc, audio_st[i] );
1951 for ( i = 0; i < oc->nb_streams; i++ )
1952 av_freep( &oc->streams[i] );
1954 // Close the output file
1955 if ( !( fmt->flags & AVFMT_NOFILE ) &&
1956 !mlt_properties_get_int( properties, "redirect" ) )
1958 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1959 if ( oc->pb ) avio_close( oc->pb );
1961 if ( oc->pb ) url_fclose( oc->pb );
1965 // Clean up input and output frames
1967 av_free( output->data[0] );
1969 av_free( input->data[0] );
1971 av_free( video_outbuf );
1972 av_free( audio_buf_1 );
1973 av_free( audio_buf_2 );
1978 // Just in case we terminated on pause
1979 mlt_consumer_stopped( consumer );
1980 mlt_properties_close( frame_meta_properties );
1982 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1984 // Remove the dual pass log file
1985 if ( mlt_properties_get( properties, "_logfilename" ) )
1986 remove( mlt_properties_get( properties, "_logfilename" ) );
1988 // Remove the x264 dual pass logs
1989 char *cwd = getcwd( NULL, 0 );
1990 const char *file = "x264_2pass.log";
1991 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1992 sprintf( full, "%s/%s", cwd, file );
1995 file = "x264_2pass.log.temp";
1996 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1997 sprintf( full, "%s/%s", cwd, file );
2000 file = "x264_2pass.log.mbtree";
2001 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2002 sprintf( full, "%s/%s", cwd, file );
2006 remove( "x264_2pass.log.temp" );
2009 while ( ( frame = mlt_deque_pop_back( queue ) ) )
2010 mlt_frame_close( frame );
2015 /** Close the consumer.
2018 static void consumer_close( mlt_consumer consumer )
2020 // Stop the consumer
2021 mlt_consumer_stop( consumer );
2024 mlt_consumer_close( consumer );