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
67 #define MAX_AUDIO_STREAMS (8)
68 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
69 #define AUDIO_BUFFER_SIZE (1024 * 42)
70 #define VIDEO_BUFFER_SIZE (2048 * 1024)
73 // This structure should be extended and made globally available in mlt
85 *sample_fifo, sample_fifo_s;
87 sample_fifo sample_fifo_init( int frequency, int channels )
89 sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
90 fifo->frequency = frequency;
91 fifo->channels = channels;
95 // count is the number of samples multiplied by the number of bytes per sample
96 void sample_fifo_append( sample_fifo fifo, uint8_t *samples, int count )
98 if ( ( fifo->size - fifo->used ) < count )
100 fifo->size += count * 5;
101 fifo->buffer = realloc( fifo->buffer, fifo->size );
104 memcpy( &fifo->buffer[ fifo->used ], samples, count );
108 int sample_fifo_used( sample_fifo fifo )
113 int sample_fifo_fetch( sample_fifo fifo, uint8_t *samples, int count )
115 if ( count > fifo->used )
118 memcpy( samples, fifo->buffer, count );
120 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used );
122 fifo->time += ( double )count / fifo->channels / fifo->frequency;
127 void sample_fifo_close( sample_fifo fifo )
129 free( fifo->buffer );
133 // Forward references.
134 static void property_changed( mlt_properties owner, mlt_consumer self, char *name );
135 static int consumer_start( mlt_consumer consumer );
136 static int consumer_stop( mlt_consumer consumer );
137 static int consumer_is_stopped( mlt_consumer consumer );
138 static void *consumer_thread( void *arg );
139 static void consumer_close( mlt_consumer consumer );
141 /** Initialise the consumer.
144 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
146 // Allocate the consumer
147 mlt_consumer consumer = mlt_consumer_new( profile );
149 // If memory allocated and initialises without error
150 if ( consumer != NULL )
152 // Get properties from the consumer
153 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
155 // Assign close callback
156 consumer->close = consumer_close;
158 // Interpret the argument
160 mlt_properties_set( properties, "target", arg );
162 // sample and frame queue
163 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
165 // Audio options not fully handled by AVOptions
166 #define QSCALE_NONE (-99999)
167 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
169 // Video options not fully handled by AVOptions
170 mlt_properties_set_int( properties, "dc", 8 );
172 // Muxer options not fully handled by AVOptions
173 mlt_properties_set_double( properties, "muxdelay", 0.7 );
174 mlt_properties_set_double( properties, "muxpreload", 0.5 );
176 // Ensure termination at end of the stream
177 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
179 // Default to separate processing threads for producer and consumer with no frame dropping!
180 mlt_properties_set_int( properties, "real_time", -1 );
181 mlt_properties_set_int( properties, "prefill", 1 );
183 // Set up start/stop/terminated callbacks
184 consumer->start = consumer_start;
185 consumer->stop = consumer_stop;
186 consumer->is_stopped = consumer_is_stopped;
188 mlt_events_register( properties, "consumer-fatal-error", NULL );
189 mlt_event event = mlt_events_listen( properties, consumer, "property-changed", ( mlt_listener )property_changed );
190 mlt_properties_set_data( properties, "property-changed event", event, 0, NULL, NULL );
197 static void property_changed( mlt_properties owner, mlt_consumer self, char *name )
199 mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
201 if ( !strcmp( name, "s" ) )
203 // Obtain the size property
204 char *size = mlt_properties_get( properties, "s" );
205 int width = mlt_properties_get_int( properties, "width" );
206 int height = mlt_properties_get_int( properties, "height" );
209 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
216 mlt_log_warning( MLT_CONSUMER_SERVICE(self), "Invalid size property %s - ignoring.\n", size );
219 // Now ensure we honour the multiple of two requested by libavformat
220 width = ( width / 2 ) * 2;
221 height = ( height / 2 ) * 2;
222 mlt_properties_set_int( properties, "width", width );
223 mlt_properties_set_int( properties, "height", height );
225 // "-aspect" on ffmpeg command line is display aspect ratio
226 else if ( !strcmp( name, "aspect" ) )
228 double ar = mlt_properties_get_double( properties, "aspect" );
229 AVRational rational = av_d2q( ar, 255 );
230 int width = mlt_properties_get_int( properties, "width" );
231 int height = mlt_properties_get_int( properties, "height" );
233 // Update the profile and properties as well since this is an alias
234 // for mlt properties that correspond to profile settings
235 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
236 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
238 // Now compute the sample aspect ratio
239 rational = av_d2q( ar * height / width, 255 );
241 // Update the profile and properties as well since this is an alias
242 // for mlt properties that correspond to profile settings
243 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
244 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
246 // Handle the ffmpeg command line "-r" property for frame rate
247 else if ( !strcmp( name, "r" ) )
249 double frame_rate = mlt_properties_get_double( properties, "r" );
250 AVRational rational = av_d2q( frame_rate, 255 );
251 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
252 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
256 /** Start the consumer.
259 static int consumer_start( mlt_consumer consumer )
261 // Get the properties
262 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
265 // Report information about available muxers and codecs as YAML Tiny
266 char *s = mlt_properties_get( properties, "f" );
267 if ( s && strcmp( s, "list" ) == 0 )
269 mlt_properties doc = mlt_properties_new();
270 mlt_properties formats = mlt_properties_new();
272 AVOutputFormat *format = NULL;
274 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
275 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
276 while ( ( format = av_oformat_next( format ) ) )
278 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
279 mlt_properties_set( formats, key, format->name );
281 s = mlt_properties_serialise_yaml( doc );
282 fprintf( stdout, "%s", s );
284 mlt_properties_close( doc );
287 s = mlt_properties_get( properties, "acodec" );
288 if ( s && strcmp( s, "list" ) == 0 )
290 mlt_properties doc = mlt_properties_new();
291 mlt_properties codecs = mlt_properties_new();
293 AVCodec *codec = NULL;
295 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
296 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
297 while ( ( codec = av_codec_next( codec ) ) )
298 #if (defined(FFUDIV) && LIBAVCODEC_VERSION_INT >= ((54<<16)+(56<<8)+100)) || (LIBAVCODEC_VERSION_INT >= ((54<<16)+(27<<8)+0))
299 if ( codec->encode2 && codec->type == CODEC_TYPE_AUDIO )
300 #elif LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
301 if ( ( codec->encode || codec->encode2 ) && codec->type == CODEC_TYPE_AUDIO )
303 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
306 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
307 mlt_properties_set( codecs, key, codec->name );
309 s = mlt_properties_serialise_yaml( doc );
310 fprintf( stdout, "%s", s );
312 mlt_properties_close( doc );
315 s = mlt_properties_get( properties, "vcodec" );
316 if ( s && strcmp( s, "list" ) == 0 )
318 mlt_properties doc = mlt_properties_new();
319 mlt_properties codecs = mlt_properties_new();
321 AVCodec *codec = NULL;
323 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
324 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
325 while ( ( codec = av_codec_next( codec ) ) )
326 #if (defined(FFUDIV) && LIBAVCODEC_VERSION_INT >= ((54<<16)+(56<<8)+100)) || (LIBAVCODEC_VERSION_INT >= ((54<<16)+(27<<8)+0))
327 if ( codec->encode2 && codec->type == CODEC_TYPE_VIDEO )
328 #elif LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
329 if ( (codec->encode || codec->encode2) && codec->type == CODEC_TYPE_VIDEO )
331 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
334 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
335 mlt_properties_set( codecs, key, codec->name );
337 s = mlt_properties_serialise_yaml( doc );
338 fprintf( stdout, "%s", s );
340 mlt_properties_close( doc );
344 // Check that we're not already running
345 if ( !error && !mlt_properties_get_int( properties, "running" ) )
348 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
350 mlt_event_block( mlt_properties_get_data( properties, "property-changed event", NULL ) );
352 // Apply AVOptions that are synonyms for standard mlt_consumer options
353 if ( mlt_properties_get( properties, "ac" ) )
354 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
355 if ( mlt_properties_get( properties, "ar" ) )
356 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
358 // Assign the thread to properties
359 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
362 pthread_create( thread, NULL, consumer_thread, consumer );
364 // Set the running state
365 mlt_properties_set_int( properties, "running", 1 );
370 /** Stop the consumer.
373 static int consumer_stop( mlt_consumer consumer )
375 // Get the properties
376 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
377 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
379 // Check that we're running
383 mlt_properties_set_int( properties, "running", 0 );
385 // Wait for termination
386 pthread_join( *thread, NULL );
388 mlt_properties_set_data( properties, "thread", NULL, 0, NULL, NULL );
389 mlt_event_unblock( mlt_properties_get_data( properties, "property-changed event", NULL ) );
395 /** Determine if the consumer is stopped.
398 static int consumer_is_stopped( mlt_consumer consumer )
400 // Get the properties
401 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
402 return !mlt_properties_get_int( properties, "running" );
405 /** Process properties as AVOptions and apply to AV context obj
408 static void apply_properties( void *obj, mlt_properties properties, int flags )
411 int count = mlt_properties_count( properties );
412 #if LIBAVUTIL_VERSION_INT < ((51<<16)+(12<<8)+0)
416 for ( i = 0; i < count; i++ )
418 const char *opt_name = mlt_properties_get_name( properties, i );
419 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
420 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
422 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
425 // If option not found, see if it was prefixed with a or v (-vb)
427 ( opt_name[0] == 'v' && ( flags & AV_OPT_FLAG_VIDEO_PARAM ) ) ||
428 ( opt_name[0] == 'a' && ( flags & AV_OPT_FLAG_AUDIO_PARAM ) ) ) )
429 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
430 opt = av_opt_find( obj, ++opt_name, NULL, flags, flags );
432 opt = av_find_opt( obj, ++opt_name, NULL, flags, flags );
434 // Apply option if found
436 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
437 av_opt_set( obj, opt_name, mlt_properties_get_value( properties, i), 0 );
439 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
444 static enum PixelFormat pick_pix_fmt( mlt_image_format img_fmt )
448 case mlt_image_rgb24:
449 return PIX_FMT_RGB24;
450 case mlt_image_rgb24a:
452 case mlt_image_yuv420p:
453 return PIX_FMT_YUV420P;
455 return PIX_FMT_YUYV422;
459 static int get_mlt_audio_format( int av_sample_fmt )
461 switch ( av_sample_fmt )
463 case AV_SAMPLE_FMT_U8:
465 case AV_SAMPLE_FMT_S32:
466 return mlt_audio_s32le;
467 case AV_SAMPLE_FMT_FLT:
468 return mlt_audio_f32le;
469 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
470 case AV_SAMPLE_FMT_U8P:
472 case AV_SAMPLE_FMT_S32P:
473 return mlt_audio_s32le;
474 case AV_SAMPLE_FMT_FLTP:
475 return mlt_audio_f32le;
478 return mlt_audio_s16;
482 static int pick_sample_fmt( mlt_properties properties, AVCodec *codec )
484 int sample_fmt = AV_SAMPLE_FMT_S16;
485 const char *format = mlt_properties_get( properties, "mlt_audio_format" );
486 const int *p = codec->sample_fmts;
488 // get default av_sample_fmt from mlt_audio_format
491 if ( !strcmp( format, "s32le" ) )
492 sample_fmt = AV_SAMPLE_FMT_S32;
493 else if ( !strcmp( format, "f32le" ) )
494 sample_fmt = AV_SAMPLE_FMT_FLT;
495 else if ( !strcmp( format, "u8" ) )
496 sample_fmt = AV_SAMPLE_FMT_U8;
497 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
498 else if ( !strcmp( format, "s32" ) )
499 sample_fmt = AV_SAMPLE_FMT_S32P;
500 else if ( !strcmp( format, "float" ) )
501 sample_fmt = AV_SAMPLE_FMT_FLTP;
504 // check if codec supports our mlt_audio_format
505 for ( ; *p != -1; p++ )
507 if ( *p == sample_fmt )
510 // no match - pick first one we support
511 for ( p = codec->sample_fmts; *p != -1; p++ )
515 case AV_SAMPLE_FMT_U8:
516 case AV_SAMPLE_FMT_S16:
517 case AV_SAMPLE_FMT_S32:
518 case AV_SAMPLE_FMT_FLT:
519 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
520 case AV_SAMPLE_FMT_U8P:
521 case AV_SAMPLE_FMT_S16P:
522 case AV_SAMPLE_FMT_S32P:
523 case AV_SAMPLE_FMT_FLTP:
530 mlt_log_error( properties, "audio codec sample_fmt not compatible" );
532 return AV_SAMPLE_FMT_NONE;
535 static uint8_t* interleaved_to_planar( int samples, int channels, uint8_t* audio, int bytes_per_sample )
537 uint8_t *buffer = mlt_pool_alloc( AUDIO_ENCODE_BUFFER_SIZE );
541 memset( buffer, 0, AUDIO_ENCODE_BUFFER_SIZE );
542 for ( c = 0; c < channels; c++ )
544 uint8_t *q = audio + c * bytes_per_sample;
548 memcpy( p, q, bytes_per_sample );
549 p += bytes_per_sample;
550 q += channels * bytes_per_sample;
556 /** Add an audio output stream
559 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec, int channels )
561 // Get the properties
562 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
564 // Create a new stream
565 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
566 AVStream *st = avformat_new_stream( oc, codec );
568 AVStream *st = av_new_stream( oc, oc->nb_streams );
571 // If created, then initialise from properties
574 AVCodecContext *c = st->codec;
576 // Establish defaults from AVOptions
577 #if LIBAVCODEC_VERSION_MAJOR >= 53
578 avcodec_get_context_defaults3( c, codec );
580 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
583 c->codec_id = codec->id;
584 c->codec_type = CODEC_TYPE_AUDIO;
585 c->sample_fmt = pick_sample_fmt( properties, codec );
587 #if 0 // disabled until some audio codecs are multi-threaded
588 // Setup multi-threading
589 int thread_count = mlt_properties_get_int( properties, "threads" );
590 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
591 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
592 if ( thread_count > 1 )
593 c->thread_count = thread_count;
596 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
597 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
599 // Allow the user to override the audio fourcc
600 if ( mlt_properties_get( properties, "atag" ) )
603 char *arg = mlt_properties_get( properties, "atag" );
604 int tag = strtol( arg, &tail, 0);
606 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
610 // Process properties as AVOptions
611 char *apre = mlt_properties_get( properties, "apre" );
614 mlt_properties p = mlt_properties_load( apre );
615 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
616 mlt_properties_close( p );
618 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
620 int audio_qscale = mlt_properties_get_int( properties, "aq" );
621 if ( audio_qscale > QSCALE_NONE )
623 c->flags |= CODEC_FLAG_QSCALE;
624 c->global_quality = FF_QP2LAMBDA * audio_qscale;
625 #if LIBAVFORMAT_VERSION_MAJOR < 53
626 st->quality = c->global_quality;
630 // Set parameters controlled by MLT
631 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
632 c->time_base = ( AVRational ){ 1, c->sample_rate };
633 c->channels = channels;
635 if ( mlt_properties_get( properties, "alang" ) != NULL )
636 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
637 av_dict_set( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
639 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
644 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
650 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
652 // We will return the audio input size from here
653 int audio_input_frame_size = 0;
656 AVCodecContext *c = st->codec;
661 codec = avcodec_find_encoder_by_name( codec_name );
663 codec = avcodec_find_encoder( c->codec_id );
665 // Process properties as AVOptions on the AVCodec
666 if ( codec && codec->priv_class )
668 char *apre = mlt_properties_get( properties, "apre" );
669 if ( !c->priv_data && codec->priv_data_size )
671 c->priv_data = av_mallocz( codec->priv_data_size );
672 *(const AVClass **) c->priv_data = codec->priv_class;
673 // av_opt_set_defaults( c );
677 mlt_properties p = mlt_properties_load( apre );
678 apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
679 mlt_properties_close( p );
681 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
684 // Continue if codec found and we can open it
685 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
686 if ( codec && avcodec_open2( c, codec, NULL ) >= 0 )
688 if ( codec && avcodec_open( c, codec ) >= 0 )
691 // ugly hack for PCM codecs (will be removed ASAP with new PCM
692 // support to compute the input frame size in samples
693 if ( c->frame_size <= 1 )
695 audio_input_frame_size = audio_outbuf_size / c->channels;
696 switch(st->codec->codec_id)
698 case AV_CODEC_ID_PCM_S16LE:
699 case AV_CODEC_ID_PCM_S16BE:
700 case AV_CODEC_ID_PCM_U16LE:
701 case AV_CODEC_ID_PCM_U16BE:
702 audio_input_frame_size >>= 1;
710 audio_input_frame_size = c->frame_size;
713 // Some formats want stream headers to be seperate (hmm)
714 if ( !strcmp( oc->oformat->name, "mp4" ) ||
715 !strcmp( oc->oformat->name, "mov" ) ||
716 !strcmp( oc->oformat->name, "3gp" ) )
717 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
721 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
722 audio_input_frame_size = 0;
725 return audio_input_frame_size;
728 static void close_audio( AVFormatContext *oc, AVStream *st )
730 if ( st && st->codec )
731 avcodec_close( st->codec );
734 /** Add a video output stream
737 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
739 // Get the properties
740 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
742 // Create a new stream
743 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
744 AVStream *st = avformat_new_stream( oc, codec );
746 AVStream *st = av_new_stream( oc, oc->nb_streams );
751 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
752 AVCodecContext *c = st->codec;
754 // Establish defaults from AVOptions
755 #if LIBAVCODEC_VERSION_MAJOR >= 53
756 avcodec_get_context_defaults3( c, codec );
758 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
761 c->codec_id = codec->id;
762 c->codec_type = CODEC_TYPE_VIDEO;
764 // Setup multi-threading
765 int thread_count = mlt_properties_get_int( properties, "threads" );
766 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
767 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
768 if ( thread_count > 1 )
769 #if LIBAVCODEC_VERSION_MAJOR >= 53
770 c->thread_count = thread_count;
772 avcodec_thread_init( c, thread_count );
775 // Process properties as AVOptions
776 char *vpre = mlt_properties_get( properties, "vpre" );
779 mlt_properties p = mlt_properties_load( vpre );
781 if ( mlt_properties_count( p ) < 1 )
783 AVCodec *codec = avcodec_find_encoder( c->codec_id );
786 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
787 strcpy( path, AVDATADIR );
788 strcat( path, codec->name );
790 strcat( path, vpre );
791 strcat( path, ".ffpreset" );
793 mlt_properties_close( p );
794 p = mlt_properties_load( path );
795 if ( mlt_properties_count( p ) > 0 )
796 mlt_properties_debug( p, path, stderr );
802 mlt_properties_debug( p, vpre, stderr );
805 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
806 mlt_properties_close( p );
808 int colorspace = mlt_properties_get_int( properties, "colorspace" );
809 mlt_properties_set( properties, "colorspace", NULL );
810 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
811 mlt_properties_set_int( properties, "colorspace", colorspace );
813 // Set options controlled by MLT
814 c->width = mlt_properties_get_int( properties, "width" );
815 c->height = mlt_properties_get_int( properties, "height" );
816 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
817 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
818 if ( st->time_base.den == 0 )
819 st->time_base = c->time_base;
820 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
822 switch ( colorspace )
825 c->colorspace = AVCOL_SPC_SMPTE170M;
828 c->colorspace = AVCOL_SPC_SMPTE240M;
831 c->colorspace = AVCOL_SPC_BT470BG;
834 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
837 c->colorspace = AVCOL_SPC_BT709;
841 if ( mlt_properties_get( properties, "aspect" ) )
843 // "-aspect" on ffmpeg command line is display aspect ratio
844 double ar = mlt_properties_get_double( properties, "aspect" );
845 c->sample_aspect_ratio = av_d2q( ar * c->height / c->width, 255 );
849 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
850 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
852 st->sample_aspect_ratio = c->sample_aspect_ratio;
854 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
856 c->flags |= CODEC_FLAG_QSCALE;
857 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
858 #if LIBAVFORMAT_VERSION_MAJOR < 53
859 st->quality = c->global_quality;
863 // Allow the user to override the video fourcc
864 if ( mlt_properties_get( properties, "vtag" ) )
867 const char *arg = mlt_properties_get( properties, "vtag" );
868 int tag = strtol( arg, &tail, 0);
870 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
874 // Some formats want stream headers to be seperate
875 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
876 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
878 // Translate these standard mlt consumer properties to ffmpeg
879 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
880 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
882 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
883 c->flags |= CODEC_FLAG_INTERLACED_DCT;
884 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
885 c->flags |= CODEC_FLAG_INTERLACED_ME;
888 // parse the ratecontrol override string
890 char *rc_override = mlt_properties_get( properties, "rc_override" );
891 for ( i = 0; rc_override; i++ )
894 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
896 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
897 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
898 c->rc_override[i].start_frame = start;
899 c->rc_override[i].end_frame = end;
902 c->rc_override[i].qscale = q;
903 c->rc_override[i].quality_factor = 1.0;
907 c->rc_override[i].qscale = 0;
908 c->rc_override[i].quality_factor = -q / 100.0;
910 rc_override = strchr( rc_override, '/' );
914 c->rc_override_count = i;
915 if ( !c->rc_initial_buffer_occupancy )
916 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
917 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
920 i = mlt_properties_get_int( properties, "pass" );
922 c->flags |= CODEC_FLAG_PASS1;
924 c->flags |= CODEC_FLAG_PASS2;
925 if ( codec->id != AV_CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
927 char logfilename[1024];
932 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
933 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
934 if ( c->flags & CODEC_FLAG_PASS1 )
936 f = fopen( logfilename, "w" );
938 perror( logfilename );
940 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
944 /* read the log file */
945 f = fopen( logfilename, "r" );
952 mlt_properties_set( properties, "_logfilename", logfilename );
953 fseek( f, 0, SEEK_END );
955 fseek( f, 0, SEEK_SET );
956 logbuffer = av_malloc( size + 1 );
958 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
963 size = fread( logbuffer, 1, size, f );
964 logbuffer[size] = '\0';
965 c->stats_in = logbuffer;
975 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
981 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
984 AVFrame *picture = avcodec_alloc_frame();
986 // Determine size of the
987 int size = avpicture_get_size(pix_fmt, width, height);
989 // Allocate the picture buf
990 uint8_t *picture_buf = av_malloc(size);
992 // If we have both, then fill the image
993 if ( picture != NULL && picture_buf != NULL )
995 // Fill the frame with the allocated buffer
996 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
1000 // Something failed - clean up what we can
1002 av_free( picture_buf );
1009 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
1012 AVCodecContext *video_enc = st->codec;
1014 // find the video encoder
1017 codec = avcodec_find_encoder_by_name( codec_name );
1019 codec = avcodec_find_encoder( video_enc->codec_id );
1021 // Process properties as AVOptions on the AVCodec
1022 if ( codec && codec->priv_class )
1024 char *vpre = mlt_properties_get( properties, "vpre" );
1025 if ( !video_enc->priv_data && codec->priv_data_size )
1027 video_enc->priv_data = av_mallocz( codec->priv_data_size );
1028 *(const AVClass **) video_enc->priv_data = codec->priv_class;
1029 // av_opt_set_defaults( video_enc );
1033 mlt_properties p = mlt_properties_load( vpre );
1034 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1035 mlt_properties_close( p );
1037 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1040 if( codec && codec->pix_fmts )
1042 const enum PixelFormat *p = codec->pix_fmts;
1043 for( ; *p!=-1; p++ )
1045 if( *p == video_enc->pix_fmt )
1049 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1052 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1053 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1055 int result = codec && avcodec_open( video_enc, codec ) >= 0;
1061 void close_video(AVFormatContext *oc, AVStream *st)
1063 if ( st && st->codec )
1065 av_freep( &st->codec->stats_in );
1066 avcodec_close(st->codec);
1070 static inline long time_difference( struct timeval *time1 )
1072 struct timeval time2;
1073 gettimeofday( &time2, NULL );
1074 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1077 static int mlt_write(void *h, uint8_t *buf, int size)
1079 mlt_properties properties = (mlt_properties) h;
1080 mlt_events_fire( properties, "avformat-write", buf, size, NULL );
1084 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1086 listener( owner, service, (uint8_t*) args[0], (int) args[1] );
1089 /** The main thread - the argument is simply the consumer.
1092 static void *consumer_thread( void *arg )
1094 // Map the argument to the object
1095 mlt_consumer consumer = arg;
1097 // Get the properties
1098 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1100 // Get the terminate on pause property
1101 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1104 // Determine if feed is slow (for realtime stuff)
1105 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1108 struct timeval ante;
1110 // Get the frame rate
1111 double fps = mlt_properties_get_double( properties, "fps" );
1113 // Get width and height
1114 int width = mlt_properties_get_int( properties, "width" );
1115 int height = mlt_properties_get_int( properties, "height" );
1116 int img_width = width;
1117 int img_height = height;
1119 // Get default audio properties
1120 int channels = mlt_properties_get_int( properties, "channels" );
1121 int total_channels = channels;
1122 int frequency = mlt_properties_get_int( properties, "frequency" );
1126 // AVFormat audio buffer and frame size
1127 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1128 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1129 int audio_input_nb_samples = 0;
1131 // AVFormat video buffer and frame count
1132 int frame_count = 0;
1133 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1134 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1136 // Used for the frame properties
1137 mlt_frame frame = NULL;
1138 mlt_properties frame_properties = NULL;
1141 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1142 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1144 // For receiving images from an mlt_frame
1146 mlt_image_format img_fmt = mlt_image_yuv422;
1147 // Get the image format to use for rendering threads
1148 const char* img_fmt_name = mlt_properties_get( properties, "mlt_image_format" );
1151 if ( !strcmp( img_fmt_name, "rgb24" ) )
1152 img_fmt = mlt_image_rgb24;
1153 else if ( !strcmp( img_fmt_name, "rgb24a" ) )
1154 img_fmt = mlt_image_rgb24a;
1155 else if ( !strcmp( img_fmt_name, "yuv420p" ) )
1156 img_fmt = mlt_image_yuv420p;
1158 else if ( mlt_properties_get( properties, "pix_fmt" ) )
1160 img_fmt_name = mlt_properties_get( properties, "pix_fmt" );
1161 if ( !strcmp( img_fmt_name, "rgba" ) ||
1162 !strcmp( img_fmt_name, "argb" ) ||
1163 !strcmp( img_fmt_name, "bgra" ) )
1164 img_fmt = mlt_image_rgb24a;
1167 // Need two av pictures for converting
1168 AVFrame *converted_avframe = NULL;
1169 AVFrame *audio_avframe = NULL;
1170 AVFrame *video_avframe = alloc_picture( pick_pix_fmt( img_fmt ), width, height );
1172 // For receiving audio samples back from the fifo
1173 uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1174 uint8_t *audio_buf_2 = NULL;
1177 // Allocate the context
1178 AVFormatContext *oc = avformat_alloc_context( );
1181 AVStream *video_st = NULL;
1182 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1185 double audio_pts = 0;
1186 double video_pts = 0;
1188 // Frames dispatched
1189 long int frames = 0;
1190 long int total_time = 0;
1192 // Determine the format
1193 AVOutputFormat *fmt = NULL;
1194 const char *filename = mlt_properties_get( properties, "target" );
1195 char *format = mlt_properties_get( properties, "f" );
1196 char *vcodec = mlt_properties_get( properties, "vcodec" );
1197 char *acodec = mlt_properties_get( properties, "acodec" );
1198 AVCodec *audio_codec = NULL;
1199 AVCodec *video_codec = NULL;
1201 // Used to store and override codec ids
1207 mlt_properties frame_meta_properties = mlt_properties_new();
1208 int error_count = 0;
1210 // Initialize audio_st
1211 int i = MAX_AUDIO_STREAMS;
1215 // Check for user selected format first
1216 if ( format != NULL )
1217 fmt = av_guess_format( format, NULL, NULL );
1219 // Otherwise check on the filename
1220 if ( fmt == NULL && filename != NULL )
1221 fmt = av_guess_format( NULL, filename, NULL );
1223 // Otherwise default to mpeg
1225 fmt = av_guess_format( "mpeg", NULL, NULL );
1227 // We need a filename - default to stdout?
1228 if ( filename == NULL || !strcmp( filename, "" ) )
1231 // Get the codec ids selected
1232 audio_codec_id = fmt->audio_codec;
1233 video_codec_id = fmt->video_codec;
1235 // Check for audio codec overides
1236 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1237 audio_codec_id = AV_CODEC_ID_NONE;
1240 audio_codec = avcodec_find_encoder_by_name( acodec );
1243 audio_codec_id = audio_codec->id;
1244 if ( audio_codec_id == AV_CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1246 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1247 acodec = mlt_properties_get( properties, "_acodec" );
1248 audio_codec = avcodec_find_encoder_by_name( acodec );
1250 else if ( !strcmp( acodec, "aac" ) || !strcmp( acodec, "vorbis" ) )
1252 mlt_properties_set( properties, "astrict", "experimental" );
1257 audio_codec_id = AV_CODEC_ID_NONE;
1258 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1263 audio_codec = avcodec_find_encoder( audio_codec_id );
1266 // Check for video codec overides
1267 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1268 video_codec_id = AV_CODEC_ID_NONE;
1271 video_codec = avcodec_find_encoder_by_name( vcodec );
1274 video_codec_id = video_codec->id;
1278 video_codec_id = AV_CODEC_ID_NONE;
1279 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1284 video_codec = avcodec_find_encoder( video_codec_id );
1288 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1290 char *name = mlt_properties_get_name( properties, i );
1291 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1293 char *key = strdup( name + 10 );
1294 char *markup = strrchr( key, '.' );
1295 if ( markup && !strcmp( markup, ".markup") )
1298 if ( !strstr( key, ".stream." ) )
1299 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1300 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1302 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1310 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1312 // Get a frame now, so we can set some AVOptions from properties.
1313 frame = mlt_consumer_rt_frame( consumer );
1315 // Set the timecode from the MLT metadata if available.
1318 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1319 if ( timecode && strcmp( timecode, "" ) )
1321 mlt_properties_set( properties, "timecode", timecode );
1322 if ( strchr( timecode, ';' ) )
1323 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1327 // Add audio and video streams
1328 if ( video_codec_id != AV_CODEC_ID_NONE )
1329 video_st = add_video_stream( consumer, oc, video_codec );
1330 if ( audio_codec_id != AV_CODEC_ID_NONE )
1336 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1338 sprintf( key, "channels.%d", i );
1339 int j = mlt_properties_get_int( properties, key );
1343 total_channels += j;
1344 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1350 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1351 total_channels = channels;
1354 mlt_properties_set_int( properties, "channels", total_channels );
1356 // Audio format is determined when adding the audio stream
1357 mlt_audio_format aud_fmt = mlt_audio_none;
1359 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1360 int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1361 sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1363 // Set the parameters (even though we have none...)
1364 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1365 if ( av_set_parameters(oc, NULL) >= 0 )
1368 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1369 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1370 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1372 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1374 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1376 // Process properties as AVOptions
1377 char *fpre = mlt_properties_get( properties, "fpre" );
1380 mlt_properties p = mlt_properties_load( fpre );
1381 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1382 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1383 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1384 mlt_properties_close( p );
1386 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1387 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1388 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1390 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1392 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1394 audio_input_nb_samples = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1395 acodec? acodec : NULL );
1396 if ( !audio_input_nb_samples )
1398 // Remove the audio stream from the output context
1400 for ( j = 0; j < oc->nb_streams; j++ )
1402 if ( oc->streams[j] == audio_st[i] )
1403 av_freep( &oc->streams[j] );
1410 // Setup custom I/O if redirecting
1411 if ( mlt_properties_get_int( properties, "redirect" ) )
1413 int buffer_size = 32768;
1414 unsigned char *buffer = av_malloc( buffer_size );
1415 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1416 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1418 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1423 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1424 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1426 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1427 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1428 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1433 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1436 // Open the output file, if needed
1437 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1439 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1440 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1442 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1445 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1446 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1447 goto on_fatal_error;
1451 // Write the stream header.
1452 if ( mlt_properties_get_int( properties, "running" ) )
1453 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1454 avformat_write_header( oc, NULL );
1456 av_write_header( oc );
1459 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1462 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1463 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1464 goto on_fatal_error;
1468 // Last check - need at least one stream
1469 if ( !audio_st[0] && !video_st )
1471 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1472 goto on_fatal_error;
1477 converted_avframe = alloc_picture( video_st->codec->pix_fmt, width, height );
1479 #if LIBAVCODEC_VERSION_MAJOR >= 55
1480 // Allocate audio AVFrame
1483 audio_avframe = avcodec_alloc_frame();
1484 if ( audio_avframe ) {
1485 AVCodecContext *c = audio_st[0]->codec;
1486 audio_avframe->format = c->sample_fmt;
1487 audio_avframe->nb_samples = audio_input_nb_samples;
1488 audio_avframe->channel_layout = c->channel_layout;
1490 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to allocate audio AVFrame\n" );
1491 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1492 goto on_fatal_error;
1497 // Get the starting time (can ignore the times above)
1498 gettimeofday( &ante, NULL );
1500 // Loop while running
1501 while( mlt_properties_get_int( properties, "running" ) &&
1502 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1505 frame = mlt_consumer_rt_frame( consumer );
1507 // Check that we have a frame to work with
1508 if ( frame != NULL )
1510 // Increment frames dispatched
1513 // Default audio args
1514 frame_properties = MLT_FRAME_PROPERTIES( frame );
1516 // Check for the terminated condition
1517 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1519 // Get audio and append to the fifo
1520 if ( !terminated && audio_st[0] )
1522 samples = mlt_sample_calculator( fps, frequency, count ++ );
1523 channels = total_channels;
1524 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1526 // Save the audio channel remap properties for later
1527 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1529 // Create the fifo if we don't have one
1532 fifo = sample_fifo_init( frequency, channels );
1533 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1537 // Silence if not normal forward speed
1538 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1539 memset( pcm, 0, samples * channels * sample_bytes );
1541 // Append the samples
1542 sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1543 total_time += ( samples * 1000000 ) / frequency;
1546 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1550 if ( !terminated && video_st )
1551 mlt_deque_push_back( queue, frame );
1553 mlt_frame_close( frame );
1557 // While we have stuff to process, process...
1560 // Write interleaved audio and video frames
1561 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1564 if ( ( video_st && terminated ) || ( channels * audio_input_nb_samples ) < sample_fifo_used( fifo ) / sample_bytes )
1566 int j = 0; // channel offset into interleaved source buffer
1567 int n = FFMIN( FFMIN( channels * audio_input_nb_samples, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1569 // Get the audio samples
1572 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1574 else if ( audio_codec_id == AV_CODEC_ID_VORBIS && terminated )
1576 // This prevents an infinite loop when some versions of vorbis do not
1577 // increment pts when encoding silence.
1578 audio_pts = video_pts;
1583 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1585 samples = n / channels;
1587 // For each output stream
1588 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1590 AVStream *stream = audio_st[i];
1591 AVCodecContext *codec = stream->codec;
1594 av_init_packet( &pkt );
1595 pkt.data = audio_outbuf;
1596 pkt.size = audio_outbuf_size;
1598 // Optimized for single track and no channel remap
1599 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1601 void* p = audio_buf_1;
1602 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1603 if ( codec->sample_fmt == AV_SAMPLE_FMT_FLTP )
1604 p = interleaved_to_planar( samples, channels, p, sizeof( float ) );
1605 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S16P )
1606 p = interleaved_to_planar( samples, channels, p, sizeof( int16_t ) );
1607 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S32P )
1608 p = interleaved_to_planar( samples, channels, p, sizeof( int32_t ) );
1609 else if ( codec->sample_fmt == AV_SAMPLE_FMT_U8P )
1610 p = interleaved_to_planar( samples, channels, p, sizeof( uint8_t ) );
1612 #if LIBAVCODEC_VERSION_MAJOR >= 55
1613 audio_avframe->nb_samples = FFMAX( samples, audio_input_nb_samples );
1614 avcodec_fill_audio_frame( audio_avframe, codec->channels, codec->sample_fmt,
1615 (const uint8_t*) p, AUDIO_ENCODE_BUFFER_SIZE, 0 );
1617 int ret = avcodec_encode_audio2( codec, &pkt, audio_avframe, &got_packet );
1620 else if ( !got_packet )
1623 codec->frame_size = FFMAX( samples, audio_input_nb_samples );
1624 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, p );
1625 pkt.pts = codec->coded_frame? codec->coded_frame->pts : AV_NOPTS_VALUE;
1626 pkt.flags |= PKT_FLAG_KEY;
1629 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1630 if ( p != audio_buf_1 )
1631 mlt_pool_release( p );
1636 // Extract the audio channels according to channel mapping
1637 int dest_offset = 0; // channel offset into interleaved dest buffer
1639 // Get the number of channels for this stream
1640 sprintf( key, "channels.%d", i );
1641 int current_channels = mlt_properties_get_int( properties, key );
1643 // Clear the destination audio buffer.
1645 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1647 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1649 // For each output channel
1650 while ( dest_offset < current_channels && j < total_channels )
1652 int map_start = -1, map_channels = 0;
1653 int source_offset = 0;
1656 // Look for a mapping that starts at j
1657 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1659 sprintf( key, "%d.channels", k );
1660 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1661 sprintf( key, "%d.start", k );
1662 if ( mlt_properties_get( frame_meta_properties, key ) )
1663 map_start = mlt_properties_get_int( frame_meta_properties, key );
1664 if ( map_start != j )
1665 source_offset += map_channels;
1669 if ( map_start != j )
1671 map_channels = current_channels;
1675 // Copy samples if source offset valid
1676 if ( source_offset < channels )
1678 // Interleave the audio buffer with the # channels for this stream/mapping.
1679 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1681 void *src = audio_buf_1 + source_offset * sample_bytes;
1682 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1683 int s = samples + 1;
1686 memcpy( dest, src, sample_bytes );
1687 dest += current_channels * sample_bytes;
1688 src += channels * sample_bytes;
1692 // Otherwise silence
1695 j += current_channels;
1696 dest_offset += current_channels;
1699 #if LIBAVCODEC_VERSION_MAJOR >= 55
1700 audio_avframe->nb_samples = FFMAX( samples, audio_input_nb_samples );
1701 avcodec_fill_audio_frame( audio_avframe, codec->channels, codec->sample_fmt,
1702 (const uint8_t*) audio_buf_2, AUDIO_ENCODE_BUFFER_SIZE, 0 );
1704 int ret = avcodec_encode_audio2( codec, &pkt, audio_avframe, &got_packet );
1707 else if ( !got_packet )
1710 codec->frame_size = FFMAX( samples, audio_input_nb_samples );
1711 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1712 pkt.pts = codec->coded_frame? codec->coded_frame->pts : AV_NOPTS_VALUE;
1713 pkt.flags |= PKT_FLAG_KEY;
1719 // Write the compressed frame in the media file
1720 if ( pkt.pts != AV_NOPTS_VALUE )
1721 pkt.pts = av_rescale_q( pkt.pts, codec->time_base, stream->time_base );
1722 #if LIBAVCODEC_VERSION_MAJOR >= 55
1723 if ( pkt.dts != AV_NOPTS_VALUE )
1724 pkt.dts = av_rescale_q( pkt.dts, codec->time_base, stream->time_base );
1725 if ( pkt.duration > 0 )
1726 pkt.duration = av_rescale_q( pkt.duration, codec->time_base, stream->time_base );
1728 pkt.stream_index = stream->index;
1729 if ( av_interleaved_write_frame( oc, &pkt ) )
1731 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1732 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1733 goto on_fatal_error;
1737 else if ( pkt.size < 0 )
1739 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with audio encode %d\n", frame_count );
1740 if ( ++error_count > 2 )
1741 goto on_fatal_error;
1744 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1747 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1756 else if ( video_st )
1759 if ( mlt_deque_count( queue ) )
1762 AVCodecContext *c = video_st->codec;
1764 frame = mlt_deque_pop_front( queue );
1765 frame_properties = MLT_FRAME_PROPERTIES( frame );
1767 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1772 int stride = mlt_image_format_size( img_fmt, width, 0, NULL );
1774 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1777 // Convert the mlt frame to an AVPicture
1778 if ( img_fmt == mlt_image_yuv420p )
1780 memcpy( video_avframe->data[0], q, video_avframe->linesize[0] );
1782 memcpy( video_avframe->data[1], q, video_avframe->linesize[1] );
1784 memcpy( video_avframe->data[2], q, video_avframe->linesize[2] );
1786 else for ( i = 0; i < height; i ++ )
1788 p = video_avframe->data[0] + i * video_avframe->linesize[0];
1789 memcpy( p, q, stride );
1793 // Do the colour space conversion
1794 int flags = SWS_BICUBIC;
1796 flags |= SWS_CPU_CAPS_MMX;
1799 flags |= SWS_CPU_CAPS_MMX2;
1801 struct SwsContext *context = sws_getContext( width, height, pick_pix_fmt( img_fmt ),
1802 width, height, c->pix_fmt, flags, NULL, NULL, NULL);
1803 sws_scale( context, (const uint8_t* const*) video_avframe->data, video_avframe->linesize, 0, height,
1804 converted_avframe->data, converted_avframe->linesize);
1805 sws_freeContext( context );
1807 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1809 // Apply the alpha if applicable
1810 if ( !mlt_properties_get( properties, "mlt_image_format" ) ||
1811 strcmp( mlt_properties_get( properties, "mlt_image_format" ), "rgb24a" ) )
1812 if ( c->pix_fmt == PIX_FMT_RGBA ||
1813 c->pix_fmt == PIX_FMT_ARGB ||
1814 c->pix_fmt == PIX_FMT_BGRA )
1816 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1819 for ( i = 0; i < height; i ++ )
1821 n = ( width + 7 ) / 8;
1822 p = converted_avframe->data[ 0 ] + i * converted_avframe->linesize[ 0 ] + 3;
1826 case 0: do { *p = *alpha++; p += 4;
1827 case 7: *p = *alpha++; p += 4;
1828 case 6: *p = *alpha++; p += 4;
1829 case 5: *p = *alpha++; p += 4;
1830 case 4: *p = *alpha++; p += 4;
1831 case 3: *p = *alpha++; p += 4;
1832 case 2: *p = *alpha++; p += 4;
1833 case 1: *p = *alpha++; p += 4;
1841 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1843 // raw video case. The API will change slightly in the near future for that
1845 av_init_packet(&pkt);
1847 // Set frame interlace hints
1848 c->coded_frame->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1849 c->coded_frame->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1850 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(61<<8)+100)
1851 if ( mlt_properties_get_int( frame_properties, "progressive" ) )
1852 c->field_order = AV_FIELD_PROGRESSIVE;
1854 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TT : AV_FIELD_BB;
1856 pkt.flags |= PKT_FLAG_KEY;
1857 pkt.stream_index = video_st->index;
1858 pkt.data = (uint8_t *)converted_avframe;
1859 pkt.size = sizeof(AVPicture);
1861 ret = av_write_frame(oc, &pkt);
1862 video_pts += c->frame_size;
1867 av_init_packet( &pkt );
1868 pkt.data = video_outbuf;
1869 pkt.size = video_outbuf_size;
1872 converted_avframe->quality = c->global_quality;
1874 // Set frame interlace hints
1875 converted_avframe->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1876 converted_avframe->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1877 converted_avframe->pts = frame_count;
1880 #if LIBAVCODEC_VERSION_MAJOR >= 55
1882 ret = avcodec_encode_video2( c, &pkt, converted_avframe, &got_packet );
1885 else if ( !got_packet )
1888 pkt.size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, converted_avframe );
1889 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
1890 if ( c->coded_frame && c->coded_frame->key_frame )
1891 pkt.flags |= PKT_FLAG_KEY;
1894 // If zero size, it means the image was buffered
1897 if ( pkt.pts != AV_NOPTS_VALUE )
1898 pkt.pts = av_rescale_q( pkt.pts, c->time_base, video_st->time_base );
1899 #if LIBAVCODEC_VERSION_MAJOR >= 55
1900 if ( pkt.dts != AV_NOPTS_VALUE )
1901 pkt.dts = av_rescale_q( pkt.dts, c->time_base, video_st->time_base );
1903 pkt.stream_index = video_st->index;
1905 // write the compressed frame in the media file
1906 ret = av_interleaved_write_frame(oc, &pkt);
1907 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1908 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1910 // Dual pass logging
1911 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1912 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1916 else if ( pkt.size < 0 )
1918 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1919 if ( ++error_count > 2 )
1920 goto on_fatal_error;
1927 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1928 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1929 goto on_fatal_error;
1931 mlt_frame_close( frame );
1940 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1942 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1943 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1946 if ( real_time_output == 1 && frames % 2 == 0 )
1948 long passed = time_difference( &ante );
1951 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
1954 if ( passed < total_time )
1956 long total = ( total_time - passed );
1957 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1958 nanosleep( &t, NULL );
1963 // Flush the encoder buffers
1964 if ( real_time_output <= 0 )
1967 // TODO: flush all audio streams
1968 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1970 AVCodecContext *c = audio_st[0]->codec;
1972 av_init_packet( &pkt );
1973 pkt.data = audio_outbuf;
1977 ( channels * audio_input_nb_samples < sample_fifo_used( fifo ) / sample_bytes ) )
1979 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_nb_samples * sample_bytes );
1980 void* p = audio_buf_1;
1981 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1982 if ( c->sample_fmt == AV_SAMPLE_FMT_FLTP )
1983 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( float ) );
1984 else if ( c->sample_fmt == AV_SAMPLE_FMT_S16P )
1985 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( int16_t ) );
1986 else if ( c->sample_fmt == AV_SAMPLE_FMT_S32P )
1987 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( int32_t ) );
1988 else if ( c->sample_fmt == AV_SAMPLE_FMT_U8P )
1989 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( uint8_t ) );
1991 #if LIBAVCODEC_VERSION_MAJOR >= 55
1992 pkt.size = audio_outbuf_size;
1993 audio_avframe->nb_samples = audio_input_nb_samples;
1994 avcodec_fill_audio_frame( audio_avframe, c->channels, c->sample_fmt,
1995 (const uint8_t*) p, AUDIO_ENCODE_BUFFER_SIZE, 0 );
1997 int ret = avcodec_encode_audio2( c, &pkt, audio_avframe, &got_packet );
2000 else if ( !got_packet )
2003 c->frame_size = audio_input_nb_samples;
2004 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, p );
2006 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2007 if ( p != audio_buf_1 )
2008 mlt_pool_release( p );
2011 if ( pkt.size <= 0 ) {
2012 #if LIBAVCODEC_VERSION_MAJOR >= 55
2013 pkt.size = audio_outbuf_size;
2015 int ret = avcodec_encode_audio2( c, &pkt, NULL, &got_packet );
2018 else if ( !got_packet )
2021 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
2022 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
2023 pkt.flags |= PKT_FLAG_KEY;
2026 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
2027 if ( pkt.size <= 0 )
2030 // Write the compressed frame in the media file
2031 if ( pkt.pts != AV_NOPTS_VALUE )
2032 pkt.pts = av_rescale_q( pkt.pts, c->time_base, audio_st[0]->time_base );
2033 #if LIBAVCODEC_VERSION_MAJOR >= 55
2034 if ( pkt.dts != AV_NOPTS_VALUE )
2035 pkt.dts = av_rescale_q( pkt.dts, c->time_base, audio_st[0]->time_base );
2036 if ( pkt.duration > 0 )
2037 pkt.duration = av_rescale_q( pkt.duration, c->time_base, audio_st[0]->time_base );
2039 pkt.stream_index = audio_st[0]->index;
2040 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
2042 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
2043 mlt_events_fire( properties, "consumer-fatal-error", NULL );
2044 goto on_fatal_error;
2049 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
2051 AVCodecContext *c = video_st->codec;
2053 av_init_packet( &pkt );
2054 pkt.data = video_outbuf;
2055 pkt.size = video_outbuf_size;
2058 #if LIBAVCODEC_VERSION_MAJOR >= 55
2060 int ret = avcodec_encode_video2( c, &pkt, NULL, &got_packet );
2063 else if ( !got_packet )
2066 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
2067 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
2068 if( c->coded_frame && c->coded_frame->key_frame )
2069 pkt.flags |= PKT_FLAG_KEY;
2071 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
2072 if ( pkt.size <= 0 )
2075 if ( pkt.pts != AV_NOPTS_VALUE )
2076 pkt.pts = av_rescale_q( pkt.pts, c->time_base, video_st->time_base );
2077 #if LIBAVCODEC_VERSION_MAJOR >= 55
2078 if ( pkt.dts != AV_NOPTS_VALUE )
2079 pkt.dts = av_rescale_q( pkt.dts, c->time_base, video_st->time_base );
2081 pkt.stream_index = video_st->index;
2083 // write the compressed frame in the media file
2084 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
2086 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
2087 mlt_events_fire( properties, "consumer-fatal-error", NULL );
2088 goto on_fatal_error;
2090 // Dual pass logging
2091 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
2092 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
2098 // Write the trailer, if any
2100 av_write_trailer( oc );
2104 close_video(oc, video_st);
2105 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
2106 close_audio( oc, audio_st[i] );
2109 for ( i = 0; i < oc->nb_streams; i++ )
2110 av_freep( &oc->streams[i] );
2112 // Close the output file
2113 if ( !( fmt->flags & AVFMT_NOFILE ) &&
2114 !mlt_properties_get_int( properties, "redirect" ) )
2116 #if LIBAVFORMAT_VERSION_MAJOR >= 53
2117 if ( oc->pb ) avio_close( oc->pb );
2119 if ( oc->pb ) url_fclose( oc->pb );
2123 // Clean up input and output frames
2124 if ( converted_avframe )
2125 av_free( converted_avframe->data[0] );
2126 av_free( converted_avframe );
2127 av_free( video_avframe->data[0] );
2128 av_free( video_avframe );
2129 av_free( video_outbuf );
2130 av_free( audio_avframe );
2131 av_free( audio_buf_1 );
2132 av_free( audio_buf_2 );
2137 // Just in case we terminated on pause
2138 mlt_consumer_stopped( consumer );
2139 mlt_properties_close( frame_meta_properties );
2141 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
2143 // Remove the dual pass log file
2144 if ( mlt_properties_get( properties, "_logfilename" ) )
2145 remove( mlt_properties_get( properties, "_logfilename" ) );
2147 // Remove the x264 dual pass logs
2148 char *cwd = getcwd( NULL, 0 );
2149 const char *file = "x264_2pass.log";
2150 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2151 sprintf( full, "%s/%s", cwd, file );
2154 file = "x264_2pass.log.temp";
2155 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2156 sprintf( full, "%s/%s", cwd, file );
2159 file = "x264_2pass.log.mbtree";
2160 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2161 sprintf( full, "%s/%s", cwd, file );
2165 remove( "x264_2pass.log.temp" );
2168 while ( ( frame = mlt_deque_pop_back( queue ) ) )
2169 mlt_frame_close( frame );
2174 /** Close the consumer.
2177 static void consumer_close( mlt_consumer consumer )
2179 // Stop the consumer
2180 mlt_consumer_stop( consumer );
2183 mlt_consumer_close( consumer );