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 #if LIBAVCODEC_VERSION_MAJOR < 55
57 #define AV_CODEC_ID_PCM_S16LE CODEC_ID_PCM_S16LE
58 #define AV_CODEC_ID_PCM_S16BE CODEC_ID_PCM_S16BE
59 #define AV_CODEC_ID_PCM_U16LE CODEC_ID_PCM_U16LE
60 #define AV_CODEC_ID_PCM_U16BE CODEC_ID_PCM_U16BE
61 #define AV_CODEC_ID_H264 CODEC_ID_H264
62 #define AV_CODEC_ID_NONE CODEC_ID_NONE
63 #define AV_CODEC_ID_AC3 CODEC_ID_AC3
64 #define AV_CODEC_ID_VORBIS CODEC_ID_VORBIS
65 #define AV_CODEC_ID_RAWVIDEO CODEC_ID_RAWVIDEO
68 #define MAX_AUDIO_STREAMS (8)
69 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
70 #define AUDIO_BUFFER_SIZE (1024 * 42)
71 #define VIDEO_BUFFER_SIZE (2048 * 1024)
74 // This structure should be extended and made globally available in mlt
86 *sample_fifo, sample_fifo_s;
88 sample_fifo sample_fifo_init( int frequency, int channels )
90 sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
91 fifo->frequency = frequency;
92 fifo->channels = channels;
96 // count is the number of samples multiplied by the number of bytes per sample
97 void sample_fifo_append( sample_fifo fifo, uint8_t *samples, int count )
99 if ( ( fifo->size - fifo->used ) < count )
101 fifo->size += count * 5;
102 fifo->buffer = realloc( fifo->buffer, fifo->size );
105 memcpy( &fifo->buffer[ fifo->used ], samples, count );
109 int sample_fifo_used( sample_fifo fifo )
114 int sample_fifo_fetch( sample_fifo fifo, uint8_t *samples, int count )
116 if ( count > fifo->used )
119 memcpy( samples, fifo->buffer, count );
121 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used );
123 fifo->time += ( double )count / fifo->channels / fifo->frequency;
128 void sample_fifo_close( sample_fifo fifo )
130 free( fifo->buffer );
134 // Forward references.
135 static void property_changed( mlt_properties owner, mlt_consumer self, char *name );
136 static int consumer_start( mlt_consumer consumer );
137 static int consumer_stop( mlt_consumer consumer );
138 static int consumer_is_stopped( mlt_consumer consumer );
139 static void *consumer_thread( void *arg );
140 static void consumer_close( mlt_consumer consumer );
142 /** Initialise the consumer.
145 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
147 // Allocate the consumer
148 mlt_consumer consumer = mlt_consumer_new( profile );
150 // If memory allocated and initialises without error
151 if ( consumer != NULL )
153 // Get properties from the consumer
154 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
156 // Assign close callback
157 consumer->close = consumer_close;
159 // Interpret the argument
161 mlt_properties_set( properties, "target", arg );
163 // sample and frame queue
164 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
166 // Audio options not fully handled by AVOptions
167 #define QSCALE_NONE (-99999)
168 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
170 // Video options not fully handled by AVOptions
171 mlt_properties_set_int( properties, "dc", 8 );
173 // Muxer options not fully handled by AVOptions
174 mlt_properties_set_double( properties, "muxdelay", 0.7 );
175 mlt_properties_set_double( properties, "muxpreload", 0.5 );
177 // Ensure termination at end of the stream
178 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
180 // Default to separate processing threads for producer and consumer with no frame dropping!
181 mlt_properties_set_int( properties, "real_time", -1 );
182 mlt_properties_set_int( properties, "prefill", 1 );
184 // Set up start/stop/terminated callbacks
185 consumer->start = consumer_start;
186 consumer->stop = consumer_stop;
187 consumer->is_stopped = consumer_is_stopped;
189 mlt_events_register( properties, "consumer-fatal-error", NULL );
190 mlt_event event = mlt_events_listen( properties, consumer, "property-changed", ( mlt_listener )property_changed );
191 mlt_properties_set_data( properties, "property-changed event", event, 0, NULL, NULL );
198 static void property_changed( mlt_properties owner, mlt_consumer self, char *name )
200 mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
202 if ( !strcmp( name, "s" ) )
204 // Obtain the size property
205 char *size = mlt_properties_get( properties, "s" );
206 int width = mlt_properties_get_int( properties, "width" );
207 int height = mlt_properties_get_int( properties, "height" );
210 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
217 mlt_log_warning( MLT_CONSUMER_SERVICE(self), "Invalid size property %s - ignoring.\n", size );
220 // Now ensure we honour the multiple of two requested by libavformat
221 width = ( width / 2 ) * 2;
222 height = ( height / 2 ) * 2;
223 mlt_properties_set_int( properties, "width", width );
224 mlt_properties_set_int( properties, "height", height );
226 // "-aspect" on ffmpeg command line is display aspect ratio
227 else if ( !strcmp( name, "aspect" ) )
229 double ar = mlt_properties_get_double( properties, "aspect" );
230 AVRational rational = av_d2q( ar, 255 );
231 int width = mlt_properties_get_int( properties, "width" );
232 int height = mlt_properties_get_int( properties, "height" );
234 // Update the profile and properties as well since this is an alias
235 // for mlt properties that correspond to profile settings
236 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
237 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
239 // Now compute the sample aspect ratio
240 rational = av_d2q( ar * height / FFMAX(width, 1), 255 );
242 // Update the profile and properties as well since this is an alias
243 // for mlt properties that correspond to profile settings
244 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
245 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
247 // Handle the ffmpeg command line "-r" property for frame rate
248 else if ( !strcmp( name, "r" ) )
250 double frame_rate = mlt_properties_get_double( properties, "r" );
251 AVRational rational = av_d2q( frame_rate, 255 );
252 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
253 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
257 /** Start the consumer.
260 static int consumer_start( mlt_consumer consumer )
262 // Get the properties
263 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
266 // Report information about available muxers and codecs as YAML Tiny
267 char *s = mlt_properties_get( properties, "f" );
268 if ( s && strcmp( s, "list" ) == 0 )
270 mlt_properties doc = mlt_properties_new();
271 mlt_properties formats = mlt_properties_new();
273 AVOutputFormat *format = NULL;
275 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
276 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
277 while ( ( format = av_oformat_next( format ) ) )
279 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
280 mlt_properties_set( formats, key, format->name );
282 s = mlt_properties_serialise_yaml( doc );
283 fprintf( stdout, "%s", s );
285 mlt_properties_close( doc );
288 s = mlt_properties_get( properties, "acodec" );
289 if ( s && strcmp( s, "list" ) == 0 )
291 mlt_properties doc = mlt_properties_new();
292 mlt_properties codecs = mlt_properties_new();
294 AVCodec *codec = NULL;
296 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
297 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
298 while ( ( codec = av_codec_next( codec ) ) )
299 #if (defined(FFUDIV) && LIBAVCODEC_VERSION_INT >= ((54<<16)+(56<<8)+100)) || (LIBAVCODEC_VERSION_INT >= ((54<<16)+(27<<8)+0))
300 if ( codec->encode2 && codec->type == CODEC_TYPE_AUDIO )
301 #elif LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
302 if ( ( codec->encode || codec->encode2 ) && codec->type == CODEC_TYPE_AUDIO )
304 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
307 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
308 mlt_properties_set( codecs, key, codec->name );
310 s = mlt_properties_serialise_yaml( doc );
311 fprintf( stdout, "%s", s );
313 mlt_properties_close( doc );
316 s = mlt_properties_get( properties, "vcodec" );
317 if ( s && strcmp( s, "list" ) == 0 )
319 mlt_properties doc = mlt_properties_new();
320 mlt_properties codecs = mlt_properties_new();
322 AVCodec *codec = NULL;
324 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
325 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
326 while ( ( codec = av_codec_next( codec ) ) )
327 #if (defined(FFUDIV) && LIBAVCODEC_VERSION_INT >= ((54<<16)+(56<<8)+100)) || (LIBAVCODEC_VERSION_INT >= ((54<<16)+(27<<8)+0))
328 if ( codec->encode2 && codec->type == CODEC_TYPE_VIDEO )
329 #elif LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
330 if ( (codec->encode || codec->encode2) && codec->type == CODEC_TYPE_VIDEO )
332 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
335 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
336 mlt_properties_set( codecs, key, codec->name );
338 s = mlt_properties_serialise_yaml( doc );
339 fprintf( stdout, "%s", s );
341 mlt_properties_close( doc );
345 // Check that we're not already running
346 if ( !error && !mlt_properties_get_int( properties, "running" ) )
349 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
351 mlt_event_block( mlt_properties_get_data( properties, "property-changed event", NULL ) );
353 // Apply AVOptions that are synonyms for standard mlt_consumer options
354 if ( mlt_properties_get( properties, "ac" ) )
355 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
356 if ( mlt_properties_get( properties, "ar" ) )
357 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
359 // Assign the thread to properties
360 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
363 pthread_create( thread, NULL, consumer_thread, consumer );
365 // Set the running state
366 mlt_properties_set_int( properties, "running", 1 );
371 /** Stop the consumer.
374 static int consumer_stop( mlt_consumer consumer )
376 // Get the properties
377 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
378 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
380 // Check that we're running
384 mlt_properties_set_int( properties, "running", 0 );
386 // Wait for termination
387 pthread_join( *thread, NULL );
389 mlt_properties_set_data( properties, "thread", NULL, 0, NULL, NULL );
390 mlt_event_unblock( mlt_properties_get_data( properties, "property-changed event", NULL ) );
396 /** Determine if the consumer is stopped.
399 static int consumer_is_stopped( mlt_consumer consumer )
401 // Get the properties
402 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
403 return !mlt_properties_get_int( properties, "running" );
406 /** Process properties as AVOptions and apply to AV context obj
409 static void apply_properties( void *obj, mlt_properties properties, int flags )
412 int count = mlt_properties_count( properties );
413 #if LIBAVUTIL_VERSION_INT < ((51<<16)+(12<<8)+0)
417 for ( i = 0; i < count; i++ )
419 const char *opt_name = mlt_properties_get_name( properties, i );
420 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
421 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
423 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
426 // If option not found, see if it was prefixed with a or v (-vb)
428 ( opt_name[0] == 'v' && ( flags & AV_OPT_FLAG_VIDEO_PARAM ) ) ||
429 ( opt_name[0] == 'a' && ( flags & AV_OPT_FLAG_AUDIO_PARAM ) ) ) )
430 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
431 opt = av_opt_find( obj, ++opt_name, NULL, flags, flags );
433 opt = av_find_opt( obj, ++opt_name, NULL, flags, flags );
435 // Apply option if found
437 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
438 av_opt_set( obj, opt_name, mlt_properties_get_value( properties, i), 0 );
440 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
445 static enum PixelFormat pick_pix_fmt( mlt_image_format img_fmt )
449 case mlt_image_rgb24:
450 return PIX_FMT_RGB24;
451 case mlt_image_rgb24a:
453 case mlt_image_yuv420p:
454 return PIX_FMT_YUV420P;
456 return PIX_FMT_YUYV422;
460 static int get_mlt_audio_format( int av_sample_fmt )
462 switch ( av_sample_fmt )
464 case AV_SAMPLE_FMT_U8:
466 case AV_SAMPLE_FMT_S32:
467 return mlt_audio_s32le;
468 case AV_SAMPLE_FMT_FLT:
469 return mlt_audio_f32le;
470 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
471 case AV_SAMPLE_FMT_U8P:
473 case AV_SAMPLE_FMT_S32P:
474 return mlt_audio_s32le;
475 case AV_SAMPLE_FMT_FLTP:
476 return mlt_audio_f32le;
479 return mlt_audio_s16;
483 static int pick_sample_fmt( mlt_properties properties, AVCodec *codec )
485 int sample_fmt = AV_SAMPLE_FMT_S16;
486 const char *format = mlt_properties_get( properties, "mlt_audio_format" );
487 const int *p = codec->sample_fmts;
489 // get default av_sample_fmt from mlt_audio_format
492 if ( !strcmp( format, "s32le" ) )
493 sample_fmt = AV_SAMPLE_FMT_S32;
494 else if ( !strcmp( format, "f32le" ) )
495 sample_fmt = AV_SAMPLE_FMT_FLT;
496 else if ( !strcmp( format, "u8" ) )
497 sample_fmt = AV_SAMPLE_FMT_U8;
498 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
499 else if ( !strcmp( format, "s32" ) )
500 sample_fmt = AV_SAMPLE_FMT_S32P;
501 else if ( !strcmp( format, "float" ) )
502 sample_fmt = AV_SAMPLE_FMT_FLTP;
505 // check if codec supports our mlt_audio_format
506 for ( ; *p != -1; p++ )
508 if ( *p == sample_fmt )
511 // no match - pick first one we support
512 for ( p = codec->sample_fmts; *p != -1; p++ )
516 case AV_SAMPLE_FMT_U8:
517 case AV_SAMPLE_FMT_S16:
518 case AV_SAMPLE_FMT_S32:
519 case AV_SAMPLE_FMT_FLT:
520 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
521 case AV_SAMPLE_FMT_U8P:
522 case AV_SAMPLE_FMT_S16P:
523 case AV_SAMPLE_FMT_S32P:
524 case AV_SAMPLE_FMT_FLTP:
531 mlt_log_error( properties, "audio codec sample_fmt not compatible" );
533 return AV_SAMPLE_FMT_NONE;
536 static uint8_t* interleaved_to_planar( int samples, int channels, uint8_t* audio, int bytes_per_sample )
538 uint8_t *buffer = mlt_pool_alloc( AUDIO_ENCODE_BUFFER_SIZE );
542 memset( buffer, 0, AUDIO_ENCODE_BUFFER_SIZE );
543 for ( c = 0; c < channels; c++ )
545 uint8_t *q = audio + c * bytes_per_sample;
549 memcpy( p, q, bytes_per_sample );
550 p += bytes_per_sample;
551 q += channels * bytes_per_sample;
557 /** Add an audio output stream
560 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec, int channels )
562 // Get the properties
563 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
565 // Create a new stream
566 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
567 AVStream *st = avformat_new_stream( oc, codec );
569 AVStream *st = av_new_stream( oc, oc->nb_streams );
572 // If created, then initialise from properties
575 AVCodecContext *c = st->codec;
577 // Establish defaults from AVOptions
578 #if LIBAVCODEC_VERSION_MAJOR >= 53
579 avcodec_get_context_defaults3( c, codec );
581 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
584 c->codec_id = codec->id;
585 c->codec_type = CODEC_TYPE_AUDIO;
586 c->sample_fmt = pick_sample_fmt( properties, codec );
588 #if 0 // disabled until some audio codecs are multi-threaded
589 // Setup multi-threading
590 int thread_count = mlt_properties_get_int( properties, "threads" );
591 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
592 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
593 if ( thread_count > 1 )
594 c->thread_count = thread_count;
597 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
598 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
600 // Allow the user to override the audio fourcc
601 if ( mlt_properties_get( properties, "atag" ) )
604 char *arg = mlt_properties_get( properties, "atag" );
605 int tag = strtol( arg, &tail, 0);
607 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
611 // Process properties as AVOptions
612 char *apre = mlt_properties_get( properties, "apre" );
615 mlt_properties p = mlt_properties_load( apre );
616 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
617 mlt_properties_close( p );
619 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
621 int audio_qscale = mlt_properties_get_int( properties, "aq" );
622 if ( audio_qscale > QSCALE_NONE )
624 c->flags |= CODEC_FLAG_QSCALE;
625 c->global_quality = FF_QP2LAMBDA * audio_qscale;
626 #if LIBAVFORMAT_VERSION_MAJOR < 53
627 st->quality = c->global_quality;
631 // Set parameters controlled by MLT
632 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
633 c->time_base = ( AVRational ){ 1, c->sample_rate };
634 c->channels = channels;
636 if ( mlt_properties_get( properties, "alang" ) != NULL )
637 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
638 av_dict_set( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
640 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
645 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
651 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
653 // We will return the audio input size from here
654 int audio_input_frame_size = 0;
657 AVCodecContext *c = st->codec;
662 codec = avcodec_find_encoder_by_name( codec_name );
664 codec = avcodec_find_encoder( c->codec_id );
666 // Process properties as AVOptions on the AVCodec
667 if ( codec && codec->priv_class )
669 char *apre = mlt_properties_get( properties, "apre" );
670 if ( !c->priv_data && codec->priv_data_size )
672 c->priv_data = av_mallocz( codec->priv_data_size );
673 *(const AVClass **) c->priv_data = codec->priv_class;
674 // av_opt_set_defaults( c );
678 mlt_properties p = mlt_properties_load( apre );
679 apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
680 mlt_properties_close( p );
682 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
685 // Continue if codec found and we can open it
686 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
687 if ( codec && avcodec_open2( c, codec, NULL ) >= 0 )
689 if ( codec && avcodec_open( c, codec ) >= 0 )
692 // ugly hack for PCM codecs (will be removed ASAP with new PCM
693 // support to compute the input frame size in samples
694 if ( c->frame_size <= 1 )
696 audio_input_frame_size = audio_outbuf_size / c->channels;
697 switch(st->codec->codec_id)
699 case AV_CODEC_ID_PCM_S16LE:
700 case AV_CODEC_ID_PCM_S16BE:
701 case AV_CODEC_ID_PCM_U16LE:
702 case AV_CODEC_ID_PCM_U16BE:
703 audio_input_frame_size >>= 1;
711 audio_input_frame_size = c->frame_size;
714 // Some formats want stream headers to be seperate (hmm)
715 if ( !strcmp( oc->oformat->name, "mp4" ) ||
716 !strcmp( oc->oformat->name, "mov" ) ||
717 !strcmp( oc->oformat->name, "3gp" ) )
718 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
722 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
723 audio_input_frame_size = 0;
726 return audio_input_frame_size;
729 static void close_audio( AVFormatContext *oc, AVStream *st )
731 if ( st && st->codec )
732 avcodec_close( st->codec );
735 /** Add a video output stream
738 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
740 // Get the properties
741 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
743 // Create a new stream
744 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
745 AVStream *st = avformat_new_stream( oc, codec );
747 AVStream *st = av_new_stream( oc, oc->nb_streams );
752 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
753 AVCodecContext *c = st->codec;
755 // Establish defaults from AVOptions
756 #if LIBAVCODEC_VERSION_MAJOR >= 53
757 avcodec_get_context_defaults3( c, codec );
759 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
762 c->codec_id = codec->id;
763 c->codec_type = CODEC_TYPE_VIDEO;
765 // Setup multi-threading
766 int thread_count = mlt_properties_get_int( properties, "threads" );
767 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
768 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
769 if ( thread_count > 1 )
770 #if LIBAVCODEC_VERSION_MAJOR >= 53
771 c->thread_count = thread_count;
773 avcodec_thread_init( c, thread_count );
776 // Process properties as AVOptions
777 char *vpre = mlt_properties_get( properties, "vpre" );
780 mlt_properties p = mlt_properties_load( vpre );
782 if ( mlt_properties_count( p ) < 1 )
784 AVCodec *codec = avcodec_find_encoder( c->codec_id );
787 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
788 strcpy( path, AVDATADIR );
789 strcat( path, codec->name );
791 strcat( path, vpre );
792 strcat( path, ".ffpreset" );
794 mlt_properties_close( p );
795 p = mlt_properties_load( path );
796 if ( mlt_properties_count( p ) > 0 )
797 mlt_properties_debug( p, path, stderr );
803 mlt_properties_debug( p, vpre, stderr );
806 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
807 mlt_properties_close( p );
809 int colorspace = mlt_properties_get_int( properties, "colorspace" );
810 mlt_properties_set( properties, "colorspace", NULL );
811 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
812 mlt_properties_set_int( properties, "colorspace", colorspace );
814 // Set options controlled by MLT
815 c->width = mlt_properties_get_int( properties, "width" );
816 c->height = mlt_properties_get_int( properties, "height" );
817 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
818 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
819 if ( st->time_base.den == 0 )
820 st->time_base = c->time_base;
821 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
823 switch ( colorspace )
826 c->colorspace = AVCOL_SPC_SMPTE170M;
829 c->colorspace = AVCOL_SPC_SMPTE240M;
832 c->colorspace = AVCOL_SPC_BT470BG;
835 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
838 c->colorspace = AVCOL_SPC_BT709;
842 if ( mlt_properties_get( properties, "aspect" ) )
844 // "-aspect" on ffmpeg command line is display aspect ratio
845 double ar = mlt_properties_get_double( properties, "aspect" );
846 c->sample_aspect_ratio = av_d2q( ar * c->height / c->width, 255 );
850 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
851 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
853 st->sample_aspect_ratio = c->sample_aspect_ratio;
855 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
857 c->flags |= CODEC_FLAG_QSCALE;
858 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
859 #if LIBAVFORMAT_VERSION_MAJOR < 53
860 st->quality = c->global_quality;
864 // Allow the user to override the video fourcc
865 if ( mlt_properties_get( properties, "vtag" ) )
868 const char *arg = mlt_properties_get( properties, "vtag" );
869 int tag = strtol( arg, &tail, 0);
871 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
875 // Some formats want stream headers to be seperate
876 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
877 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
879 // Translate these standard mlt consumer properties to ffmpeg
880 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
881 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
883 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
884 c->flags |= CODEC_FLAG_INTERLACED_DCT;
885 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
886 c->flags |= CODEC_FLAG_INTERLACED_ME;
889 // parse the ratecontrol override string
891 char *rc_override = mlt_properties_get( properties, "rc_override" );
892 for ( i = 0; rc_override; i++ )
895 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
897 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
898 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
899 c->rc_override[i].start_frame = start;
900 c->rc_override[i].end_frame = end;
903 c->rc_override[i].qscale = q;
904 c->rc_override[i].quality_factor = 1.0;
908 c->rc_override[i].qscale = 0;
909 c->rc_override[i].quality_factor = -q / 100.0;
911 rc_override = strchr( rc_override, '/' );
915 c->rc_override_count = i;
916 if ( !c->rc_initial_buffer_occupancy )
917 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
918 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
921 i = mlt_properties_get_int( properties, "pass" );
923 c->flags |= CODEC_FLAG_PASS1;
925 c->flags |= CODEC_FLAG_PASS2;
926 if ( codec->id != AV_CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
928 char logfilename[1024];
933 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
934 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
935 if ( c->flags & CODEC_FLAG_PASS1 )
937 f = fopen( logfilename, "w" );
939 perror( logfilename );
941 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
945 /* read the log file */
946 f = fopen( logfilename, "r" );
953 mlt_properties_set( properties, "_logfilename", logfilename );
954 fseek( f, 0, SEEK_END );
956 fseek( f, 0, SEEK_SET );
957 logbuffer = av_malloc( size + 1 );
959 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
964 size = fread( logbuffer, 1, size, f );
965 logbuffer[size] = '\0';
966 c->stats_in = logbuffer;
976 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
982 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
985 AVFrame *picture = avcodec_alloc_frame();
987 // Determine size of the
988 int size = avpicture_get_size(pix_fmt, width, height);
990 // Allocate the picture buf
991 uint8_t *picture_buf = av_malloc(size);
993 // If we have both, then fill the image
994 if ( picture != NULL && picture_buf != NULL )
996 // Fill the frame with the allocated buffer
997 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
1001 // Something failed - clean up what we can
1003 av_free( picture_buf );
1010 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
1013 AVCodecContext *video_enc = st->codec;
1015 // find the video encoder
1018 codec = avcodec_find_encoder_by_name( codec_name );
1020 codec = avcodec_find_encoder( video_enc->codec_id );
1022 // Process properties as AVOptions on the AVCodec
1023 if ( codec && codec->priv_class )
1025 char *vpre = mlt_properties_get( properties, "vpre" );
1026 if ( !video_enc->priv_data && codec->priv_data_size )
1028 video_enc->priv_data = av_mallocz( codec->priv_data_size );
1029 *(const AVClass **) video_enc->priv_data = codec->priv_class;
1030 // av_opt_set_defaults( video_enc );
1034 mlt_properties p = mlt_properties_load( vpre );
1035 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1036 mlt_properties_close( p );
1038 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1041 if( codec && codec->pix_fmts )
1043 const enum PixelFormat *p = codec->pix_fmts;
1044 for( ; *p!=-1; p++ )
1046 if( *p == video_enc->pix_fmt )
1050 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1053 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1054 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1056 int result = codec && avcodec_open( video_enc, codec ) >= 0;
1062 void close_video(AVFormatContext *oc, AVStream *st)
1064 if ( st && st->codec )
1066 av_freep( &st->codec->stats_in );
1067 avcodec_close(st->codec);
1071 static inline long time_difference( struct timeval *time1 )
1073 struct timeval time2;
1074 gettimeofday( &time2, NULL );
1075 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1078 static int mlt_write(void *h, uint8_t *buf, int size)
1080 mlt_properties properties = (mlt_properties) h;
1081 mlt_events_fire( properties, "avformat-write", buf, &size, NULL );
1085 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1087 int *p_size = (int*) args[1];
1088 listener( owner, service, (uint8_t*) args[0], *p_size );
1091 /** The main thread - the argument is simply the consumer.
1094 static void *consumer_thread( void *arg )
1096 // Map the argument to the object
1097 mlt_consumer consumer = arg;
1099 // Get the properties
1100 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1102 // Get the terminate on pause property
1103 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1106 // Determine if feed is slow (for realtime stuff)
1107 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1110 struct timeval ante;
1112 // Get the frame rate
1113 double fps = mlt_properties_get_double( properties, "fps" );
1115 // Get width and height
1116 int width = mlt_properties_get_int( properties, "width" );
1117 int height = mlt_properties_get_int( properties, "height" );
1118 int img_width = width;
1119 int img_height = height;
1121 // Get default audio properties
1122 int channels = mlt_properties_get_int( properties, "channels" );
1123 int total_channels = channels;
1124 int frequency = mlt_properties_get_int( properties, "frequency" );
1128 // AVFormat audio buffer and frame size
1129 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1130 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1131 int audio_input_nb_samples = 0;
1133 // AVFormat video buffer and frame count
1134 int frame_count = 0;
1135 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1136 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1138 // Used for the frame properties
1139 mlt_frame frame = NULL;
1140 mlt_properties frame_properties = NULL;
1143 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1144 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1146 // For receiving images from an mlt_frame
1148 mlt_image_format img_fmt = mlt_image_yuv422;
1149 // Get the image format to use for rendering threads
1150 const char* img_fmt_name = mlt_properties_get( properties, "mlt_image_format" );
1153 if ( !strcmp( img_fmt_name, "rgb24" ) )
1154 img_fmt = mlt_image_rgb24;
1155 else if ( !strcmp( img_fmt_name, "rgb24a" ) )
1156 img_fmt = mlt_image_rgb24a;
1157 else if ( !strcmp( img_fmt_name, "yuv420p" ) )
1158 img_fmt = mlt_image_yuv420p;
1160 else if ( mlt_properties_get( properties, "pix_fmt" ) )
1162 img_fmt_name = mlt_properties_get( properties, "pix_fmt" );
1163 if ( !strcmp( img_fmt_name, "rgba" ) ||
1164 !strcmp( img_fmt_name, "argb" ) ||
1165 !strcmp( img_fmt_name, "bgra" ) )
1166 img_fmt = mlt_image_rgb24a;
1169 // Need two av pictures for converting
1170 AVFrame *converted_avframe = NULL;
1171 AVFrame *audio_avframe = NULL;
1172 AVFrame *video_avframe = alloc_picture( pick_pix_fmt( img_fmt ), width, height );
1174 // For receiving audio samples back from the fifo
1175 uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1176 uint8_t *audio_buf_2 = NULL;
1179 // Allocate the context
1180 AVFormatContext *oc = avformat_alloc_context( );
1183 AVStream *video_st = NULL;
1184 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1187 double audio_pts = 0;
1188 double video_pts = 0;
1190 // Frames dispatched
1191 long int frames = 0;
1192 long int total_time = 0;
1194 // Determine the format
1195 AVOutputFormat *fmt = NULL;
1196 const char *filename = mlt_properties_get( properties, "target" );
1197 char *format = mlt_properties_get( properties, "f" );
1198 char *vcodec = mlt_properties_get( properties, "vcodec" );
1199 char *acodec = mlt_properties_get( properties, "acodec" );
1200 AVCodec *audio_codec = NULL;
1201 AVCodec *video_codec = NULL;
1203 // Used to store and override codec ids
1209 mlt_properties frame_meta_properties = mlt_properties_new();
1210 int error_count = 0;
1211 int64_t synth_audio_pts = 0;
1213 // Initialize audio_st
1214 int i = MAX_AUDIO_STREAMS;
1218 // Check for user selected format first
1219 if ( format != NULL )
1220 fmt = av_guess_format( format, NULL, NULL );
1222 // Otherwise check on the filename
1223 if ( fmt == NULL && filename != NULL )
1224 fmt = av_guess_format( NULL, filename, NULL );
1226 // Otherwise default to mpeg
1228 fmt = av_guess_format( "mpeg", NULL, NULL );
1230 // We need a filename - default to stdout?
1231 if ( filename == NULL || !strcmp( filename, "" ) )
1234 // Get the codec ids selected
1235 audio_codec_id = fmt->audio_codec;
1236 video_codec_id = fmt->video_codec;
1238 // Check for audio codec overides
1239 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1240 audio_codec_id = AV_CODEC_ID_NONE;
1243 audio_codec = avcodec_find_encoder_by_name( acodec );
1246 audio_codec_id = audio_codec->id;
1247 if ( audio_codec_id == AV_CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1249 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1250 acodec = mlt_properties_get( properties, "_acodec" );
1251 audio_codec = avcodec_find_encoder_by_name( acodec );
1253 else if ( !strcmp( acodec, "aac" ) || !strcmp( acodec, "vorbis" ) )
1255 mlt_properties_set( properties, "astrict", "experimental" );
1260 audio_codec_id = AV_CODEC_ID_NONE;
1261 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1266 audio_codec = avcodec_find_encoder( audio_codec_id );
1269 // Check for video codec overides
1270 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1271 video_codec_id = AV_CODEC_ID_NONE;
1274 video_codec = avcodec_find_encoder_by_name( vcodec );
1277 video_codec_id = video_codec->id;
1281 video_codec_id = AV_CODEC_ID_NONE;
1282 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1287 video_codec = avcodec_find_encoder( video_codec_id );
1291 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1293 char *name = mlt_properties_get_name( properties, i );
1294 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1296 char *key = strdup( name + 10 );
1297 char *markup = strrchr( key, '.' );
1298 if ( markup && !strcmp( markup, ".markup") )
1301 if ( !strstr( key, ".stream." ) )
1302 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1303 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1305 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1313 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1315 // Get a frame now, so we can set some AVOptions from properties.
1316 frame = mlt_consumer_rt_frame( consumer );
1318 // Set the timecode from the MLT metadata if available.
1321 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1322 if ( timecode && strcmp( timecode, "" ) )
1324 mlt_properties_set( properties, "timecode", timecode );
1325 if ( strchr( timecode, ';' ) )
1326 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1330 // Add audio and video streams
1331 if ( video_codec_id != AV_CODEC_ID_NONE )
1332 video_st = add_video_stream( consumer, oc, video_codec );
1333 if ( audio_codec_id != AV_CODEC_ID_NONE )
1339 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1341 sprintf( key, "channels.%d", i );
1342 int j = mlt_properties_get_int( properties, key );
1346 total_channels += j;
1347 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1353 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1354 total_channels = channels;
1357 mlt_properties_set_int( properties, "channels", total_channels );
1359 // Audio format is determined when adding the audio stream
1360 mlt_audio_format aud_fmt = mlt_audio_none;
1362 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1363 int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1364 sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1366 // Set the parameters (even though we have none...)
1367 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1368 if ( av_set_parameters(oc, NULL) >= 0 )
1371 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1372 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1373 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1375 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1377 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1379 // Process properties as AVOptions
1380 char *fpre = mlt_properties_get( properties, "fpre" );
1383 mlt_properties p = mlt_properties_load( fpre );
1384 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1385 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1386 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1387 mlt_properties_close( p );
1389 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1390 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1391 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1393 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1395 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1397 audio_input_nb_samples = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1398 acodec? acodec : NULL );
1399 if ( !audio_input_nb_samples )
1401 // Remove the audio stream from the output context
1403 for ( j = 0; j < oc->nb_streams; j++ )
1405 if ( oc->streams[j] == audio_st[i] )
1406 av_freep( &oc->streams[j] );
1413 // Setup custom I/O if redirecting
1414 if ( mlt_properties_get_int( properties, "redirect" ) )
1416 int buffer_size = 32768;
1417 unsigned char *buffer = av_malloc( buffer_size );
1418 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1419 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1421 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1426 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1427 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1429 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1430 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1431 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1436 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1439 // Open the output file, if needed
1440 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1442 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1443 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1445 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1448 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1449 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1450 goto on_fatal_error;
1454 // Write the stream header.
1455 if ( mlt_properties_get_int( properties, "running" ) )
1456 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1457 avformat_write_header( oc, NULL );
1459 av_write_header( oc );
1462 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1465 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1466 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1467 goto on_fatal_error;
1471 // Last check - need at least one stream
1472 if ( !audio_st[0] && !video_st )
1474 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1475 goto on_fatal_error;
1480 converted_avframe = alloc_picture( video_st->codec->pix_fmt, width, height );
1482 #if LIBAVCODEC_VERSION_MAJOR >= 55
1483 // Allocate audio AVFrame
1486 audio_avframe = avcodec_alloc_frame();
1487 if ( audio_avframe ) {
1488 AVCodecContext *c = audio_st[0]->codec;
1489 audio_avframe->format = c->sample_fmt;
1490 audio_avframe->nb_samples = audio_input_nb_samples;
1491 audio_avframe->channel_layout = c->channel_layout;
1493 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to allocate audio AVFrame\n" );
1494 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1495 goto on_fatal_error;
1500 // Get the starting time (can ignore the times above)
1501 gettimeofday( &ante, NULL );
1503 // Loop while running
1504 while( mlt_properties_get_int( properties, "running" ) &&
1505 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1508 frame = mlt_consumer_rt_frame( consumer );
1510 // Check that we have a frame to work with
1511 if ( frame != NULL )
1513 // Increment frames dispatched
1516 // Default audio args
1517 frame_properties = MLT_FRAME_PROPERTIES( frame );
1519 // Check for the terminated condition
1520 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1522 // Get audio and append to the fifo
1523 if ( !terminated && audio_st[0] )
1525 samples = mlt_sample_calculator( fps, frequency, count ++ );
1526 channels = total_channels;
1527 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1529 // Save the audio channel remap properties for later
1530 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1532 // Create the fifo if we don't have one
1535 fifo = sample_fifo_init( frequency, channels );
1536 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1540 // Silence if not normal forward speed
1541 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1542 memset( pcm, 0, samples * channels * sample_bytes );
1544 // Append the samples
1545 sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1546 total_time += ( samples * 1000000 ) / frequency;
1549 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1553 if ( !terminated && video_st )
1554 mlt_deque_push_back( queue, frame );
1556 mlt_frame_close( frame );
1560 // While we have stuff to process, process...
1563 // Write interleaved audio and video frames
1564 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1567 if ( ( video_st && terminated ) || ( channels * audio_input_nb_samples ) < sample_fifo_used( fifo ) / sample_bytes )
1569 int j = 0; // channel offset into interleaved source buffer
1570 int n = FFMIN( FFMIN( channels * audio_input_nb_samples, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1572 // Get the audio samples
1575 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1577 else if ( audio_codec_id == AV_CODEC_ID_VORBIS && terminated )
1579 // This prevents an infinite loop when some versions of vorbis do not
1580 // increment pts when encoding silence.
1581 audio_pts = video_pts;
1586 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1588 samples = n / channels;
1590 // For each output stream
1591 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1593 AVStream *stream = audio_st[i];
1594 AVCodecContext *codec = stream->codec;
1597 av_init_packet( &pkt );
1598 pkt.data = audio_outbuf;
1599 pkt.size = audio_outbuf_size;
1601 // Optimized for single track and no channel remap
1602 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1604 void* p = audio_buf_1;
1605 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1606 if ( codec->sample_fmt == AV_SAMPLE_FMT_FLTP )
1607 p = interleaved_to_planar( samples, channels, p, sizeof( float ) );
1608 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S16P )
1609 p = interleaved_to_planar( samples, channels, p, sizeof( int16_t ) );
1610 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S32P )
1611 p = interleaved_to_planar( samples, channels, p, sizeof( int32_t ) );
1612 else if ( codec->sample_fmt == AV_SAMPLE_FMT_U8P )
1613 p = interleaved_to_planar( samples, channels, p, sizeof( uint8_t ) );
1615 #if LIBAVCODEC_VERSION_MAJOR >= 55
1616 audio_avframe->nb_samples = FFMAX( samples, audio_input_nb_samples );
1617 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
1618 audio_avframe->pts = synth_audio_pts;
1619 synth_audio_pts += audio_avframe->nb_samples;
1620 avcodec_fill_audio_frame( audio_avframe, codec->channels, codec->sample_fmt,
1621 (const uint8_t*) p, AUDIO_ENCODE_BUFFER_SIZE, 0 );
1623 int ret = avcodec_encode_audio2( codec, &pkt, audio_avframe, &got_packet );
1626 else if ( !got_packet )
1629 codec->frame_size = FFMAX( samples, audio_input_nb_samples );
1630 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, p );
1631 pkt.pts = codec->coded_frame? codec->coded_frame->pts : AV_NOPTS_VALUE;
1632 pkt.flags |= PKT_FLAG_KEY;
1635 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1636 if ( p != audio_buf_1 )
1637 mlt_pool_release( p );
1642 // Extract the audio channels according to channel mapping
1643 int dest_offset = 0; // channel offset into interleaved dest buffer
1645 // Get the number of channels for this stream
1646 sprintf( key, "channels.%d", i );
1647 int current_channels = mlt_properties_get_int( properties, key );
1649 // Clear the destination audio buffer.
1651 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1653 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1655 // For each output channel
1656 while ( dest_offset < current_channels && j < total_channels )
1658 int map_start = -1, map_channels = 0;
1659 int source_offset = 0;
1662 // Look for a mapping that starts at j
1663 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1665 sprintf( key, "%d.channels", k );
1666 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1667 sprintf( key, "%d.start", k );
1668 if ( mlt_properties_get( frame_meta_properties, key ) )
1669 map_start = mlt_properties_get_int( frame_meta_properties, key );
1670 if ( map_start != j )
1671 source_offset += map_channels;
1675 if ( map_start != j )
1677 map_channels = current_channels;
1681 // Copy samples if source offset valid
1682 if ( source_offset < channels )
1684 // Interleave the audio buffer with the # channels for this stream/mapping.
1685 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1687 void *src = audio_buf_1 + source_offset * sample_bytes;
1688 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1689 int s = samples + 1;
1692 memcpy( dest, src, sample_bytes );
1693 dest += current_channels * sample_bytes;
1694 src += channels * sample_bytes;
1698 // Otherwise silence
1701 j += current_channels;
1702 dest_offset += current_channels;
1705 #if LIBAVCODEC_VERSION_MAJOR >= 55
1706 audio_avframe->nb_samples = FFMAX( samples, audio_input_nb_samples );
1707 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
1708 audio_avframe->pts = synth_audio_pts;
1709 synth_audio_pts += audio_avframe->nb_samples;
1710 avcodec_fill_audio_frame( audio_avframe, codec->channels, codec->sample_fmt,
1711 (const uint8_t*) audio_buf_2, AUDIO_ENCODE_BUFFER_SIZE, 0 );
1713 int ret = avcodec_encode_audio2( codec, &pkt, audio_avframe, &got_packet );
1716 else if ( !got_packet )
1719 codec->frame_size = FFMAX( samples, audio_input_nb_samples );
1720 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1721 pkt.pts = codec->coded_frame? codec->coded_frame->pts : AV_NOPTS_VALUE;
1722 pkt.flags |= PKT_FLAG_KEY;
1728 // Write the compressed frame in the media file
1729 if ( pkt.pts != AV_NOPTS_VALUE )
1730 pkt.pts = av_rescale_q( pkt.pts, codec->time_base, stream->time_base );
1731 #if LIBAVCODEC_VERSION_MAJOR >= 55
1732 if ( pkt.dts != AV_NOPTS_VALUE )
1733 pkt.dts = av_rescale_q( pkt.dts, codec->time_base, stream->time_base );
1734 if ( pkt.duration > 0 )
1735 pkt.duration = av_rescale_q( pkt.duration, codec->time_base, stream->time_base );
1737 pkt.stream_index = stream->index;
1738 if ( av_interleaved_write_frame( oc, &pkt ) )
1740 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1741 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1742 goto on_fatal_error;
1745 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame_size %d stream pts %"PRId64"\n",
1746 stream->index, pkt.pts, codec->frame_size, stream->pts.val );
1748 else if ( pkt.size < 0 )
1750 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with audio encode %d\n", frame_count );
1751 if ( ++error_count > 2 )
1752 goto on_fatal_error;
1757 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1766 else if ( video_st )
1769 if ( mlt_deque_count( queue ) )
1772 AVCodecContext *c = video_st->codec;
1774 frame = mlt_deque_pop_front( queue );
1775 frame_properties = MLT_FRAME_PROPERTIES( frame );
1777 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1782 int stride = mlt_image_format_size( img_fmt, width, 0, NULL );
1784 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1787 // Convert the mlt frame to an AVPicture
1788 if ( img_fmt == mlt_image_yuv420p )
1790 memcpy( video_avframe->data[0], q, video_avframe->linesize[0] );
1792 memcpy( video_avframe->data[1], q, video_avframe->linesize[1] );
1794 memcpy( video_avframe->data[2], q, video_avframe->linesize[2] );
1796 else for ( i = 0; i < height; i ++ )
1798 p = video_avframe->data[0] + i * video_avframe->linesize[0];
1799 memcpy( p, q, stride );
1803 // Do the colour space conversion
1804 int flags = SWS_BICUBIC;
1806 flags |= SWS_CPU_CAPS_MMX;
1809 flags |= SWS_CPU_CAPS_MMX2;
1811 struct SwsContext *context = sws_getContext( width, height, pick_pix_fmt( img_fmt ),
1812 width, height, c->pix_fmt, flags, NULL, NULL, NULL);
1813 sws_scale( context, (const uint8_t* const*) video_avframe->data, video_avframe->linesize, 0, height,
1814 converted_avframe->data, converted_avframe->linesize);
1815 sws_freeContext( context );
1817 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1819 // Apply the alpha if applicable
1820 if ( !mlt_properties_get( properties, "mlt_image_format" ) ||
1821 strcmp( mlt_properties_get( properties, "mlt_image_format" ), "rgb24a" ) )
1822 if ( c->pix_fmt == PIX_FMT_RGBA ||
1823 c->pix_fmt == PIX_FMT_ARGB ||
1824 c->pix_fmt == PIX_FMT_BGRA )
1826 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1829 for ( i = 0; i < height; i ++ )
1831 n = ( width + 7 ) / 8;
1832 p = converted_avframe->data[ 0 ] + i * converted_avframe->linesize[ 0 ] + 3;
1836 case 0: do { *p = *alpha++; p += 4;
1837 case 7: *p = *alpha++; p += 4;
1838 case 6: *p = *alpha++; p += 4;
1839 case 5: *p = *alpha++; p += 4;
1840 case 4: *p = *alpha++; p += 4;
1841 case 3: *p = *alpha++; p += 4;
1842 case 2: *p = *alpha++; p += 4;
1843 case 1: *p = *alpha++; p += 4;
1851 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1853 // raw video case. The API will change slightly in the near future for that
1855 av_init_packet(&pkt);
1857 // Set frame interlace hints
1858 c->coded_frame->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1859 c->coded_frame->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1860 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(61<<8)+100)
1861 if ( mlt_properties_get_int( frame_properties, "progressive" ) )
1862 c->field_order = AV_FIELD_PROGRESSIVE;
1864 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TT : AV_FIELD_BB;
1866 pkt.flags |= PKT_FLAG_KEY;
1867 pkt.stream_index = video_st->index;
1868 pkt.data = (uint8_t *)converted_avframe;
1869 pkt.size = sizeof(AVPicture);
1871 ret = av_write_frame(oc, &pkt);
1872 video_pts += c->frame_size;
1877 av_init_packet( &pkt );
1878 if ( c->codec->id == AV_CODEC_ID_RAWVIDEO ) {
1882 pkt.data = video_outbuf;
1883 pkt.size = video_outbuf_size;
1887 converted_avframe->quality = c->global_quality;
1888 converted_avframe->pts = frame_count;
1890 // Set frame interlace hints
1891 converted_avframe->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1892 converted_avframe->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1893 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(61<<8)+100)
1894 if ( mlt_properties_get_int( frame_properties, "progressive" ) )
1895 c->field_order = AV_FIELD_PROGRESSIVE;
1896 else if ( c->codec_id == AV_CODEC_ID_MJPEG )
1897 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TT : AV_FIELD_BB;
1899 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TB : AV_FIELD_BT;
1903 #if LIBAVCODEC_VERSION_MAJOR >= 55
1905 ret = avcodec_encode_video2( c, &pkt, converted_avframe, &got_packet );
1908 else if ( !got_packet )
1911 pkt.size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, converted_avframe );
1912 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
1913 if ( c->coded_frame && c->coded_frame->key_frame )
1914 pkt.flags |= PKT_FLAG_KEY;
1917 // If zero size, it means the image was buffered
1920 if ( pkt.pts != AV_NOPTS_VALUE )
1921 pkt.pts = av_rescale_q( pkt.pts, c->time_base, video_st->time_base );
1922 #if LIBAVCODEC_VERSION_MAJOR >= 55
1923 if ( pkt.dts != AV_NOPTS_VALUE )
1924 pkt.dts = av_rescale_q( pkt.dts, c->time_base, video_st->time_base );
1926 pkt.stream_index = video_st->index;
1928 // write the compressed frame in the media file
1929 ret = av_interleaved_write_frame(oc, &pkt);
1930 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1931 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1933 // Dual pass logging
1934 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1935 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1939 else if ( pkt.size < 0 )
1941 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1942 if ( ++error_count > 2 )
1943 goto on_fatal_error;
1950 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1951 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1952 goto on_fatal_error;
1954 mlt_frame_close( frame );
1963 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1965 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1966 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1969 if ( real_time_output == 1 && frames % 2 == 0 )
1971 long passed = time_difference( &ante );
1974 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
1977 if ( passed < total_time )
1979 long total = ( total_time - passed );
1980 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1981 nanosleep( &t, NULL );
1986 // Flush the encoder buffers
1987 if ( real_time_output <= 0 )
1990 // TODO: flush all audio streams
1991 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1993 AVCodecContext *c = audio_st[0]->codec;
1995 av_init_packet( &pkt );
1996 pkt.data = audio_outbuf;
1999 if ( fifo && sample_fifo_used( fifo ) > 0 )
2001 // Drain the MLT FIFO
2002 int samples = FFMIN( FFMIN( channels * audio_input_nb_samples, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
2003 sample_fifo_fetch( fifo, audio_buf_1, samples * sample_bytes );
2004 void* p = audio_buf_1;
2005 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2006 if ( c->sample_fmt == AV_SAMPLE_FMT_FLTP )
2007 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( float ) );
2008 else if ( c->sample_fmt == AV_SAMPLE_FMT_S16P )
2009 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( int16_t ) );
2010 else if ( c->sample_fmt == AV_SAMPLE_FMT_S32P )
2011 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( int32_t ) );
2012 else if ( c->sample_fmt == AV_SAMPLE_FMT_U8P )
2013 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( uint8_t ) );
2015 #if LIBAVCODEC_VERSION_MAJOR >= 55
2016 pkt.size = audio_outbuf_size;
2017 audio_avframe->nb_samples = FFMAX( samples / channels, audio_input_nb_samples );
2018 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
2019 audio_avframe->pts = synth_audio_pts;
2020 synth_audio_pts += audio_avframe->nb_samples;
2021 avcodec_fill_audio_frame( audio_avframe, c->channels, c->sample_fmt,
2022 (const uint8_t*) p, AUDIO_ENCODE_BUFFER_SIZE, 0 );
2024 int ret = avcodec_encode_audio2( c, &pkt, audio_avframe, &got_packet );
2027 else if ( !got_packet )
2030 c->frame_size = FFMAX( samples / channels, audio_input_nb_samples );
2031 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, p );
2033 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2034 if ( p != audio_buf_1 )
2035 mlt_pool_release( p );
2037 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
2042 if ( pkt.size <= 0 ) {
2043 #if LIBAVCODEC_VERSION_MAJOR >= 55
2044 pkt.size = audio_outbuf_size;
2046 int ret = avcodec_encode_audio2( c, &pkt, NULL, &got_packet );
2049 else if ( !got_packet )
2052 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
2053 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
2054 pkt.flags |= PKT_FLAG_KEY;
2057 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
2058 if ( pkt.size <= 0 )
2062 // Write the compressed frame in the media file
2063 if ( pkt.pts != AV_NOPTS_VALUE )
2064 pkt.pts = av_rescale_q( pkt.pts, c->time_base, audio_st[0]->time_base );
2065 #if LIBAVCODEC_VERSION_MAJOR >= 55
2066 if ( pkt.dts != AV_NOPTS_VALUE )
2067 pkt.dts = av_rescale_q( pkt.dts, c->time_base, audio_st[0]->time_base );
2068 if ( pkt.duration > 0 )
2069 pkt.duration = av_rescale_q( pkt.duration, c->time_base, audio_st[0]->time_base );
2071 pkt.stream_index = audio_st[0]->index;
2072 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
2074 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
2080 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
2082 AVCodecContext *c = video_st->codec;
2084 av_init_packet( &pkt );
2085 if ( c->codec->id == AV_CODEC_ID_RAWVIDEO ) {
2089 pkt.data = video_outbuf;
2090 pkt.size = video_outbuf_size;
2094 #if LIBAVCODEC_VERSION_MAJOR >= 55
2096 int ret = avcodec_encode_video2( c, &pkt, NULL, &got_packet );
2099 else if ( !got_packet )
2102 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
2103 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
2104 if( c->coded_frame && c->coded_frame->key_frame )
2105 pkt.flags |= PKT_FLAG_KEY;
2107 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
2108 if ( pkt.size <= 0 )
2111 if ( pkt.pts != AV_NOPTS_VALUE )
2112 pkt.pts = av_rescale_q( pkt.pts, c->time_base, video_st->time_base );
2113 #if LIBAVCODEC_VERSION_MAJOR >= 55
2114 if ( pkt.dts != AV_NOPTS_VALUE )
2115 pkt.dts = av_rescale_q( pkt.dts, c->time_base, video_st->time_base );
2117 pkt.stream_index = video_st->index;
2119 // write the compressed frame in the media file
2120 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
2122 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
2123 mlt_events_fire( properties, "consumer-fatal-error", NULL );
2124 goto on_fatal_error;
2126 // Dual pass logging
2127 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
2128 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
2134 // Write the trailer, if any
2136 av_write_trailer( oc );
2140 close_video(oc, video_st);
2141 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
2142 close_audio( oc, audio_st[i] );
2145 for ( i = 0; i < oc->nb_streams; i++ )
2146 av_freep( &oc->streams[i] );
2148 // Close the output file
2149 if ( !( fmt->flags & AVFMT_NOFILE ) &&
2150 !mlt_properties_get_int( properties, "redirect" ) )
2152 #if LIBAVFORMAT_VERSION_MAJOR >= 53
2153 if ( oc->pb ) avio_close( oc->pb );
2155 if ( oc->pb ) url_fclose( oc->pb );
2159 // Clean up input and output frames
2160 if ( converted_avframe )
2161 av_free( converted_avframe->data[0] );
2162 av_free( converted_avframe );
2163 av_free( video_avframe->data[0] );
2164 av_free( video_avframe );
2165 av_free( video_outbuf );
2166 av_free( audio_avframe );
2167 av_free( audio_buf_1 );
2168 av_free( audio_buf_2 );
2173 // Just in case we terminated on pause
2174 mlt_consumer_stopped( consumer );
2175 mlt_properties_close( frame_meta_properties );
2177 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
2179 // Remove the dual pass log file
2180 if ( mlt_properties_get( properties, "_logfilename" ) )
2181 remove( mlt_properties_get( properties, "_logfilename" ) );
2183 // Remove the x264 dual pass logs
2184 char *cwd = getcwd( NULL, 0 );
2185 const char *file = "x264_2pass.log";
2186 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2187 sprintf( full, "%s/%s", cwd, file );
2190 file = "x264_2pass.log.temp";
2191 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2192 sprintf( full, "%s/%s", cwd, file );
2195 file = "x264_2pass.log.mbtree";
2196 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2197 sprintf( full, "%s/%s", cwd, file );
2201 remove( "x264_2pass.log.temp" );
2204 while ( ( frame = mlt_deque_pop_back( queue ) ) )
2205 mlt_frame_close( frame );
2210 /** Close the consumer.
2213 static void consumer_close( mlt_consumer consumer )
2215 // Stop the consumer
2216 mlt_consumer_stop( consumer );
2219 mlt_consumer_close( consumer );