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
66 #define AV_CODEC_ID_MJPEG CODEC_ID_MJPEG
69 #define MAX_AUDIO_STREAMS (8)
70 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
71 #define AUDIO_BUFFER_SIZE (1024 * 42)
72 #define VIDEO_BUFFER_SIZE (2048 * 1024)
75 // This structure should be extended and made globally available in mlt
87 *sample_fifo, sample_fifo_s;
89 sample_fifo sample_fifo_init( int frequency, int channels )
91 sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
92 fifo->frequency = frequency;
93 fifo->channels = channels;
97 // count is the number of samples multiplied by the number of bytes per sample
98 void sample_fifo_append( sample_fifo fifo, uint8_t *samples, int count )
100 if ( ( fifo->size - fifo->used ) < count )
102 fifo->size += count * 5;
103 fifo->buffer = realloc( fifo->buffer, fifo->size );
106 memcpy( &fifo->buffer[ fifo->used ], samples, count );
110 int sample_fifo_used( sample_fifo fifo )
115 int sample_fifo_fetch( sample_fifo fifo, uint8_t *samples, int count )
117 if ( count > fifo->used )
120 memcpy( samples, fifo->buffer, count );
122 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used );
124 fifo->time += ( double )count / fifo->channels / fifo->frequency;
129 void sample_fifo_close( sample_fifo fifo )
131 free( fifo->buffer );
135 // Forward references.
136 static void property_changed( mlt_properties owner, mlt_consumer self, char *name );
137 static int consumer_start( mlt_consumer consumer );
138 static int consumer_stop( mlt_consumer consumer );
139 static int consumer_is_stopped( mlt_consumer consumer );
140 static void *consumer_thread( void *arg );
141 static void consumer_close( mlt_consumer consumer );
143 /** Initialise the consumer.
146 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
148 // Allocate the consumer
149 mlt_consumer consumer = mlt_consumer_new( profile );
151 // If memory allocated and initialises without error
152 if ( consumer != NULL )
154 // Get properties from the consumer
155 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
157 // Assign close callback
158 consumer->close = consumer_close;
160 // Interpret the argument
162 mlt_properties_set( properties, "target", arg );
164 // sample and frame queue
165 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
167 // Audio options not fully handled by AVOptions
168 #define QSCALE_NONE (-99999)
169 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
171 // Video options not fully handled by AVOptions
172 mlt_properties_set_int( properties, "dc", 8 );
174 // Muxer options not fully handled by AVOptions
175 mlt_properties_set_double( properties, "muxdelay", 0.7 );
176 mlt_properties_set_double( properties, "muxpreload", 0.5 );
178 // Ensure termination at end of the stream
179 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
181 // Default to separate processing threads for producer and consumer with no frame dropping!
182 mlt_properties_set_int( properties, "real_time", -1 );
183 mlt_properties_set_int( properties, "prefill", 1 );
185 // Set up start/stop/terminated callbacks
186 consumer->start = consumer_start;
187 consumer->stop = consumer_stop;
188 consumer->is_stopped = consumer_is_stopped;
190 mlt_events_register( properties, "consumer-fatal-error", NULL );
191 mlt_event event = mlt_events_listen( properties, consumer, "property-changed", ( mlt_listener )property_changed );
192 mlt_properties_set_data( properties, "property-changed event", event, 0, NULL, NULL );
199 static void property_changed( mlt_properties owner, mlt_consumer self, char *name )
201 mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
203 if ( !strcmp( name, "s" ) )
205 // Obtain the size property
206 char *size = mlt_properties_get( properties, "s" );
207 int width = mlt_properties_get_int( properties, "width" );
208 int height = mlt_properties_get_int( properties, "height" );
211 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
218 mlt_log_warning( MLT_CONSUMER_SERVICE(self), "Invalid size property %s - ignoring.\n", size );
221 // Now ensure we honour the multiple of two requested by libavformat
222 width = ( width / 2 ) * 2;
223 height = ( height / 2 ) * 2;
224 mlt_properties_set_int( properties, "width", width );
225 mlt_properties_set_int( properties, "height", height );
227 // "-aspect" on ffmpeg command line is display aspect ratio
228 else if ( !strcmp( name, "aspect" ) )
230 double ar = mlt_properties_get_double( properties, "aspect" );
231 AVRational rational = av_d2q( ar, 255 );
232 int width = mlt_properties_get_int( properties, "width" );
233 int height = mlt_properties_get_int( properties, "height" );
235 // Update the profile and properties as well since this is an alias
236 // for mlt properties that correspond to profile settings
237 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
238 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
240 // Now compute the sample aspect ratio
241 rational = av_d2q( ar * height / FFMAX(width, 1), 255 );
243 // Update the profile and properties as well since this is an alias
244 // for mlt properties that correspond to profile settings
245 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
246 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
248 // Handle the ffmpeg command line "-r" property for frame rate
249 else if ( !strcmp( name, "r" ) )
251 double frame_rate = mlt_properties_get_double( properties, "r" );
252 AVRational rational = av_d2q( frame_rate, 255 );
253 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
254 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
258 /** Start the consumer.
261 static int consumer_start( mlt_consumer consumer )
263 // Get the properties
264 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
267 // Report information about available muxers and codecs as YAML Tiny
268 char *s = mlt_properties_get( properties, "f" );
269 if ( s && strcmp( s, "list" ) == 0 )
271 mlt_properties doc = mlt_properties_new();
272 mlt_properties formats = mlt_properties_new();
274 AVOutputFormat *format = NULL;
276 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
277 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
278 while ( ( format = av_oformat_next( format ) ) )
280 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
281 mlt_properties_set( formats, key, format->name );
283 s = mlt_properties_serialise_yaml( doc );
284 fprintf( stdout, "%s", s );
286 mlt_properties_close( doc );
289 s = mlt_properties_get( properties, "acodec" );
290 if ( s && strcmp( s, "list" ) == 0 )
292 mlt_properties doc = mlt_properties_new();
293 mlt_properties codecs = mlt_properties_new();
295 AVCodec *codec = NULL;
297 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
298 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
299 while ( ( codec = av_codec_next( codec ) ) )
300 #if (defined(FFUDIV) && LIBAVCODEC_VERSION_INT >= ((54<<16)+(56<<8)+100)) || (LIBAVCODEC_VERSION_INT >= ((54<<16)+(27<<8)+0))
301 if ( codec->encode2 && codec->type == CODEC_TYPE_AUDIO )
302 #elif LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
303 if ( ( codec->encode || codec->encode2 ) && codec->type == CODEC_TYPE_AUDIO )
305 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
308 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
309 mlt_properties_set( codecs, key, codec->name );
311 s = mlt_properties_serialise_yaml( doc );
312 fprintf( stdout, "%s", s );
314 mlt_properties_close( doc );
317 s = mlt_properties_get( properties, "vcodec" );
318 if ( s && strcmp( s, "list" ) == 0 )
320 mlt_properties doc = mlt_properties_new();
321 mlt_properties codecs = mlt_properties_new();
323 AVCodec *codec = NULL;
325 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
326 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
327 while ( ( codec = av_codec_next( codec ) ) )
328 #if (defined(FFUDIV) && LIBAVCODEC_VERSION_INT >= ((54<<16)+(56<<8)+100)) || (LIBAVCODEC_VERSION_INT >= ((54<<16)+(27<<8)+0))
329 if ( codec->encode2 && codec->type == CODEC_TYPE_VIDEO )
330 #elif LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
331 if ( (codec->encode || codec->encode2) && codec->type == CODEC_TYPE_VIDEO )
333 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
336 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
337 mlt_properties_set( codecs, key, codec->name );
339 s = mlt_properties_serialise_yaml( doc );
340 fprintf( stdout, "%s", s );
342 mlt_properties_close( doc );
346 // Check that we're not already running
347 if ( !error && !mlt_properties_get_int( properties, "running" ) )
350 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
352 mlt_event_block( mlt_properties_get_data( properties, "property-changed event", NULL ) );
354 // Apply AVOptions that are synonyms for standard mlt_consumer options
355 if ( mlt_properties_get( properties, "ac" ) )
356 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
357 if ( mlt_properties_get( properties, "ar" ) )
358 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
360 // Assign the thread to properties
361 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
364 pthread_create( thread, NULL, consumer_thread, consumer );
366 // Set the running state
367 mlt_properties_set_int( properties, "running", 1 );
372 /** Stop the consumer.
375 static int consumer_stop( mlt_consumer consumer )
377 // Get the properties
378 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
379 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
381 // Check that we're running
385 mlt_properties_set_int( properties, "running", 0 );
387 // Wait for termination
388 pthread_join( *thread, NULL );
390 mlt_properties_set_data( properties, "thread", NULL, 0, NULL, NULL );
391 mlt_event_unblock( mlt_properties_get_data( properties, "property-changed event", NULL ) );
397 /** Determine if the consumer is stopped.
400 static int consumer_is_stopped( mlt_consumer consumer )
402 // Get the properties
403 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
404 return !mlt_properties_get_int( properties, "running" );
407 /** Process properties as AVOptions and apply to AV context obj
410 static void apply_properties( void *obj, mlt_properties properties, int flags )
413 int count = mlt_properties_count( properties );
414 #if LIBAVUTIL_VERSION_INT < ((51<<16)+(12<<8)+0)
418 for ( i = 0; i < count; i++ )
420 const char *opt_name = mlt_properties_get_name( properties, i );
421 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
422 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
424 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
427 // If option not found, see if it was prefixed with a or v (-vb)
429 ( opt_name[0] == 'v' && ( flags & AV_OPT_FLAG_VIDEO_PARAM ) ) ||
430 ( opt_name[0] == 'a' && ( flags & AV_OPT_FLAG_AUDIO_PARAM ) ) ) )
431 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
432 opt = av_opt_find( obj, ++opt_name, NULL, flags, flags );
434 opt = av_find_opt( obj, ++opt_name, NULL, flags, flags );
436 // Apply option if found
438 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
439 av_opt_set( obj, opt_name, mlt_properties_get_value( properties, i), 0 );
441 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
446 static enum PixelFormat pick_pix_fmt( mlt_image_format img_fmt )
450 case mlt_image_rgb24:
451 return PIX_FMT_RGB24;
452 case mlt_image_rgb24a:
454 case mlt_image_yuv420p:
455 return PIX_FMT_YUV420P;
457 return PIX_FMT_YUYV422;
461 static int get_mlt_audio_format( int av_sample_fmt )
463 switch ( av_sample_fmt )
465 case AV_SAMPLE_FMT_U8:
467 case AV_SAMPLE_FMT_S32:
468 return mlt_audio_s32le;
469 case AV_SAMPLE_FMT_FLT:
470 return mlt_audio_f32le;
471 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
472 case AV_SAMPLE_FMT_U8P:
474 case AV_SAMPLE_FMT_S32P:
475 return mlt_audio_s32le;
476 case AV_SAMPLE_FMT_FLTP:
477 return mlt_audio_f32le;
480 return mlt_audio_s16;
484 static int pick_sample_fmt( mlt_properties properties, AVCodec *codec )
486 int sample_fmt = AV_SAMPLE_FMT_S16;
487 const char *format = mlt_properties_get( properties, "mlt_audio_format" );
488 const int *p = codec->sample_fmts;
490 // get default av_sample_fmt from mlt_audio_format
493 if ( !strcmp( format, "s32le" ) )
494 sample_fmt = AV_SAMPLE_FMT_S32;
495 else if ( !strcmp( format, "f32le" ) )
496 sample_fmt = AV_SAMPLE_FMT_FLT;
497 else if ( !strcmp( format, "u8" ) )
498 sample_fmt = AV_SAMPLE_FMT_U8;
499 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
500 else if ( !strcmp( format, "s32" ) )
501 sample_fmt = AV_SAMPLE_FMT_S32P;
502 else if ( !strcmp( format, "float" ) )
503 sample_fmt = AV_SAMPLE_FMT_FLTP;
506 // check if codec supports our mlt_audio_format
507 for ( ; *p != -1; p++ )
509 if ( *p == sample_fmt )
512 // no match - pick first one we support
513 for ( p = codec->sample_fmts; *p != -1; p++ )
517 case AV_SAMPLE_FMT_U8:
518 case AV_SAMPLE_FMT_S16:
519 case AV_SAMPLE_FMT_S32:
520 case AV_SAMPLE_FMT_FLT:
521 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
522 case AV_SAMPLE_FMT_U8P:
523 case AV_SAMPLE_FMT_S16P:
524 case AV_SAMPLE_FMT_S32P:
525 case AV_SAMPLE_FMT_FLTP:
532 mlt_log_error( properties, "audio codec sample_fmt not compatible" );
534 return AV_SAMPLE_FMT_NONE;
537 static uint8_t* interleaved_to_planar( int samples, int channels, uint8_t* audio, int bytes_per_sample )
539 uint8_t *buffer = mlt_pool_alloc( AUDIO_ENCODE_BUFFER_SIZE );
543 memset( buffer, 0, AUDIO_ENCODE_BUFFER_SIZE );
544 for ( c = 0; c < channels; c++ )
546 uint8_t *q = audio + c * bytes_per_sample;
550 memcpy( p, q, bytes_per_sample );
551 p += bytes_per_sample;
552 q += channels * bytes_per_sample;
558 /** Add an audio output stream
561 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec, int channels )
563 // Get the properties
564 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
566 // Create a new stream
567 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
568 AVStream *st = avformat_new_stream( oc, codec );
570 AVStream *st = av_new_stream( oc, oc->nb_streams );
573 // If created, then initialise from properties
576 AVCodecContext *c = st->codec;
578 // Establish defaults from AVOptions
579 #if LIBAVCODEC_VERSION_MAJOR >= 53
580 avcodec_get_context_defaults3( c, codec );
582 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
585 c->codec_id = codec->id;
586 c->codec_type = CODEC_TYPE_AUDIO;
587 c->sample_fmt = pick_sample_fmt( properties, codec );
589 #if 0 // disabled until some audio codecs are multi-threaded
590 // Setup multi-threading
591 int thread_count = mlt_properties_get_int( properties, "threads" );
592 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
593 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
594 if ( thread_count > 1 )
595 c->thread_count = thread_count;
598 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
599 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
601 // Allow the user to override the audio fourcc
602 if ( mlt_properties_get( properties, "atag" ) )
605 char *arg = mlt_properties_get( properties, "atag" );
606 int tag = strtol( arg, &tail, 0);
608 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
612 // Process properties as AVOptions
613 char *apre = mlt_properties_get( properties, "apre" );
616 mlt_properties p = mlt_properties_load( apre );
617 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
618 mlt_properties_close( p );
620 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
622 int audio_qscale = mlt_properties_get_int( properties, "aq" );
623 if ( audio_qscale > QSCALE_NONE )
625 c->flags |= CODEC_FLAG_QSCALE;
626 c->global_quality = FF_QP2LAMBDA * audio_qscale;
627 #if LIBAVFORMAT_VERSION_MAJOR < 53
628 st->quality = c->global_quality;
632 // Set parameters controlled by MLT
633 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
634 c->time_base = ( AVRational ){ 1, c->sample_rate };
635 c->channels = channels;
637 if ( mlt_properties_get( properties, "alang" ) != NULL )
638 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
639 av_dict_set( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
641 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
646 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
652 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
654 // We will return the audio input size from here
655 int audio_input_frame_size = 0;
658 AVCodecContext *c = st->codec;
663 codec = avcodec_find_encoder_by_name( codec_name );
665 codec = avcodec_find_encoder( c->codec_id );
667 // Process properties as AVOptions on the AVCodec
668 if ( codec && codec->priv_class )
670 char *apre = mlt_properties_get( properties, "apre" );
671 if ( !c->priv_data && codec->priv_data_size )
673 c->priv_data = av_mallocz( codec->priv_data_size );
674 *(const AVClass **) c->priv_data = codec->priv_class;
675 // av_opt_set_defaults( c );
679 mlt_properties p = mlt_properties_load( apre );
680 apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
681 mlt_properties_close( p );
683 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
686 // Continue if codec found and we can open it
687 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
688 if ( codec && avcodec_open2( c, codec, NULL ) >= 0 )
690 if ( codec && avcodec_open( c, codec ) >= 0 )
693 // ugly hack for PCM codecs (will be removed ASAP with new PCM
694 // support to compute the input frame size in samples
695 if ( c->frame_size <= 1 )
697 audio_input_frame_size = audio_outbuf_size / c->channels;
698 switch(st->codec->codec_id)
700 case AV_CODEC_ID_PCM_S16LE:
701 case AV_CODEC_ID_PCM_S16BE:
702 case AV_CODEC_ID_PCM_U16LE:
703 case AV_CODEC_ID_PCM_U16BE:
704 audio_input_frame_size >>= 1;
712 audio_input_frame_size = c->frame_size;
715 // Some formats want stream headers to be seperate (hmm)
716 if ( !strcmp( oc->oformat->name, "mp4" ) ||
717 !strcmp( oc->oformat->name, "mov" ) ||
718 !strcmp( oc->oformat->name, "3gp" ) )
719 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
723 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
724 audio_input_frame_size = 0;
727 return audio_input_frame_size;
730 static void close_audio( AVFormatContext *oc, AVStream *st )
732 if ( st && st->codec )
733 avcodec_close( st->codec );
736 /** Add a video output stream
739 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
741 // Get the properties
742 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
744 // Create a new stream
745 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
746 AVStream *st = avformat_new_stream( oc, codec );
748 AVStream *st = av_new_stream( oc, oc->nb_streams );
753 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
754 AVCodecContext *c = st->codec;
756 // Establish defaults from AVOptions
757 #if LIBAVCODEC_VERSION_MAJOR >= 53
758 avcodec_get_context_defaults3( c, codec );
760 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
763 c->codec_id = codec->id;
764 c->codec_type = CODEC_TYPE_VIDEO;
766 // Setup multi-threading
767 int thread_count = mlt_properties_get_int( properties, "threads" );
768 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
769 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
770 if ( thread_count > 1 )
771 #if LIBAVCODEC_VERSION_MAJOR >= 53
772 c->thread_count = thread_count;
774 avcodec_thread_init( c, thread_count );
777 // Process properties as AVOptions
778 char *vpre = mlt_properties_get( properties, "vpre" );
781 mlt_properties p = mlt_properties_load( vpre );
783 if ( mlt_properties_count( p ) < 1 )
785 AVCodec *codec = avcodec_find_encoder( c->codec_id );
788 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
789 strcpy( path, AVDATADIR );
790 strcat( path, codec->name );
792 strcat( path, vpre );
793 strcat( path, ".ffpreset" );
795 mlt_properties_close( p );
796 p = mlt_properties_load( path );
797 if ( mlt_properties_count( p ) > 0 )
798 mlt_properties_debug( p, path, stderr );
804 mlt_properties_debug( p, vpre, stderr );
807 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
808 mlt_properties_close( p );
810 int colorspace = mlt_properties_get_int( properties, "colorspace" );
811 mlt_properties_set( properties, "colorspace", NULL );
812 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
813 mlt_properties_set_int( properties, "colorspace", colorspace );
815 // Set options controlled by MLT
816 c->width = mlt_properties_get_int( properties, "width" );
817 c->height = mlt_properties_get_int( properties, "height" );
818 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
819 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
820 if ( st->time_base.den == 0 )
821 st->time_base = c->time_base;
822 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
824 switch ( colorspace )
827 c->colorspace = AVCOL_SPC_SMPTE170M;
830 c->colorspace = AVCOL_SPC_SMPTE240M;
833 c->colorspace = AVCOL_SPC_BT470BG;
836 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
839 c->colorspace = AVCOL_SPC_BT709;
843 if ( mlt_properties_get( properties, "aspect" ) )
845 // "-aspect" on ffmpeg command line is display aspect ratio
846 double ar = mlt_properties_get_double( properties, "aspect" );
847 c->sample_aspect_ratio = av_d2q( ar * c->height / c->width, 255 );
851 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
852 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
854 st->sample_aspect_ratio = c->sample_aspect_ratio;
856 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
858 c->flags |= CODEC_FLAG_QSCALE;
859 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
860 #if LIBAVFORMAT_VERSION_MAJOR < 53
861 st->quality = c->global_quality;
865 // Allow the user to override the video fourcc
866 if ( mlt_properties_get( properties, "vtag" ) )
869 const char *arg = mlt_properties_get( properties, "vtag" );
870 int tag = strtol( arg, &tail, 0);
872 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
876 // Some formats want stream headers to be seperate
877 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
878 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
880 // Translate these standard mlt consumer properties to ffmpeg
881 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
882 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
884 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
885 c->flags |= CODEC_FLAG_INTERLACED_DCT;
886 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
887 c->flags |= CODEC_FLAG_INTERLACED_ME;
890 // parse the ratecontrol override string
892 char *rc_override = mlt_properties_get( properties, "rc_override" );
893 for ( i = 0; rc_override; i++ )
896 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
898 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
899 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
900 c->rc_override[i].start_frame = start;
901 c->rc_override[i].end_frame = end;
904 c->rc_override[i].qscale = q;
905 c->rc_override[i].quality_factor = 1.0;
909 c->rc_override[i].qscale = 0;
910 c->rc_override[i].quality_factor = -q / 100.0;
912 rc_override = strchr( rc_override, '/' );
916 c->rc_override_count = i;
917 if ( !c->rc_initial_buffer_occupancy )
918 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
919 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
922 i = mlt_properties_get_int( properties, "pass" );
924 c->flags |= CODEC_FLAG_PASS1;
926 c->flags |= CODEC_FLAG_PASS2;
927 if ( codec->id != AV_CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
929 char logfilename[1024];
934 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
935 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
936 if ( c->flags & CODEC_FLAG_PASS1 )
938 f = fopen( logfilename, "w" );
940 perror( logfilename );
942 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
946 /* read the log file */
947 f = fopen( logfilename, "r" );
954 mlt_properties_set( properties, "_logfilename", logfilename );
955 fseek( f, 0, SEEK_END );
957 fseek( f, 0, SEEK_SET );
958 logbuffer = av_malloc( size + 1 );
960 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
965 size = fread( logbuffer, 1, size, f );
966 logbuffer[size] = '\0';
967 c->stats_in = logbuffer;
977 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
983 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
986 AVFrame *picture = avcodec_alloc_frame();
988 // Determine size of the
989 int size = avpicture_get_size(pix_fmt, width, height);
991 // Allocate the picture buf
992 uint8_t *picture_buf = av_malloc(size);
994 // If we have both, then fill the image
995 if ( picture != NULL && picture_buf != NULL )
997 // Fill the frame with the allocated buffer
998 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
1002 // Something failed - clean up what we can
1004 av_free( picture_buf );
1011 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
1014 AVCodecContext *video_enc = st->codec;
1016 // find the video encoder
1019 codec = avcodec_find_encoder_by_name( codec_name );
1021 codec = avcodec_find_encoder( video_enc->codec_id );
1023 // Process properties as AVOptions on the AVCodec
1024 if ( codec && codec->priv_class )
1026 char *vpre = mlt_properties_get( properties, "vpre" );
1027 if ( !video_enc->priv_data && codec->priv_data_size )
1029 video_enc->priv_data = av_mallocz( codec->priv_data_size );
1030 *(const AVClass **) video_enc->priv_data = codec->priv_class;
1031 // av_opt_set_defaults( video_enc );
1035 mlt_properties p = mlt_properties_load( vpre );
1036 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1037 mlt_properties_close( p );
1039 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1042 if( codec && codec->pix_fmts )
1044 const enum PixelFormat *p = codec->pix_fmts;
1045 for( ; *p!=-1; p++ )
1047 if( *p == video_enc->pix_fmt )
1051 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1054 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1055 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1057 int result = codec && avcodec_open( video_enc, codec ) >= 0;
1063 void close_video(AVFormatContext *oc, AVStream *st)
1065 if ( st && st->codec )
1067 av_freep( &st->codec->stats_in );
1068 avcodec_close(st->codec);
1072 static inline long time_difference( struct timeval *time1 )
1074 struct timeval time2;
1075 gettimeofday( &time2, NULL );
1076 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1079 static int mlt_write(void *h, uint8_t *buf, int size)
1081 mlt_properties properties = (mlt_properties) h;
1082 mlt_events_fire( properties, "avformat-write", buf, &size, NULL );
1086 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1088 int *p_size = (int*) args[1];
1089 listener( owner, service, (uint8_t*) args[0], *p_size );
1092 /** The main thread - the argument is simply the consumer.
1095 static void *consumer_thread( void *arg )
1097 // Map the argument to the object
1098 mlt_consumer consumer = arg;
1100 // Get the properties
1101 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1103 // Get the terminate on pause property
1104 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1107 // Determine if feed is slow (for realtime stuff)
1108 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1111 struct timeval ante;
1113 // Get the frame rate
1114 double fps = mlt_properties_get_double( properties, "fps" );
1116 // Get width and height
1117 int width = mlt_properties_get_int( properties, "width" );
1118 int height = mlt_properties_get_int( properties, "height" );
1119 int img_width = width;
1120 int img_height = height;
1122 // Get default audio properties
1123 int channels = mlt_properties_get_int( properties, "channels" );
1124 int total_channels = channels;
1125 int frequency = mlt_properties_get_int( properties, "frequency" );
1129 // AVFormat audio buffer and frame size
1130 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1131 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1132 int audio_input_nb_samples = 0;
1134 // AVFormat video buffer and frame count
1135 int frame_count = 0;
1136 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1137 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1139 // Used for the frame properties
1140 mlt_frame frame = NULL;
1141 mlt_properties frame_properties = NULL;
1144 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1145 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1147 // For receiving images from an mlt_frame
1149 mlt_image_format img_fmt = mlt_image_yuv422;
1150 // Get the image format to use for rendering threads
1151 const char* img_fmt_name = mlt_properties_get( properties, "mlt_image_format" );
1154 if ( !strcmp( img_fmt_name, "rgb24" ) )
1155 img_fmt = mlt_image_rgb24;
1156 else if ( !strcmp( img_fmt_name, "rgb24a" ) )
1157 img_fmt = mlt_image_rgb24a;
1158 else if ( !strcmp( img_fmt_name, "yuv420p" ) )
1159 img_fmt = mlt_image_yuv420p;
1161 else if ( mlt_properties_get( properties, "pix_fmt" ) )
1163 img_fmt_name = mlt_properties_get( properties, "pix_fmt" );
1164 if ( !strcmp( img_fmt_name, "rgba" ) ||
1165 !strcmp( img_fmt_name, "argb" ) ||
1166 !strcmp( img_fmt_name, "bgra" ) )
1167 img_fmt = mlt_image_rgb24a;
1170 // Need two av pictures for converting
1171 AVFrame *converted_avframe = NULL;
1172 AVFrame *audio_avframe = NULL;
1173 AVFrame *video_avframe = alloc_picture( pick_pix_fmt( img_fmt ), width, height );
1175 // For receiving audio samples back from the fifo
1176 uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1177 uint8_t *audio_buf_2 = NULL;
1180 // Allocate the context
1181 AVFormatContext *oc = avformat_alloc_context( );
1184 AVStream *video_st = NULL;
1185 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1188 double audio_pts = 0;
1189 double video_pts = 0;
1191 // Frames dispatched
1192 long int frames = 0;
1193 long int total_time = 0;
1195 // Determine the format
1196 AVOutputFormat *fmt = NULL;
1197 const char *filename = mlt_properties_get( properties, "target" );
1198 char *format = mlt_properties_get( properties, "f" );
1199 char *vcodec = mlt_properties_get( properties, "vcodec" );
1200 char *acodec = mlt_properties_get( properties, "acodec" );
1201 AVCodec *audio_codec = NULL;
1202 AVCodec *video_codec = NULL;
1204 // Used to store and override codec ids
1210 mlt_properties frame_meta_properties = mlt_properties_new();
1211 int error_count = 0;
1212 int64_t synth_audio_pts = 0;
1214 // Initialize audio_st
1215 int i = MAX_AUDIO_STREAMS;
1219 // Check for user selected format first
1220 if ( format != NULL )
1221 fmt = av_guess_format( format, NULL, NULL );
1223 // Otherwise check on the filename
1224 if ( fmt == NULL && filename != NULL )
1225 fmt = av_guess_format( NULL, filename, NULL );
1227 // Otherwise default to mpeg
1229 fmt = av_guess_format( "mpeg", NULL, NULL );
1231 // We need a filename - default to stdout?
1232 if ( filename == NULL || !strcmp( filename, "" ) )
1235 // Get the codec ids selected
1236 audio_codec_id = fmt->audio_codec;
1237 video_codec_id = fmt->video_codec;
1239 // Check for audio codec overides
1240 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1241 audio_codec_id = AV_CODEC_ID_NONE;
1244 audio_codec = avcodec_find_encoder_by_name( acodec );
1247 audio_codec_id = audio_codec->id;
1248 if ( audio_codec_id == AV_CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1250 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1251 acodec = mlt_properties_get( properties, "_acodec" );
1252 audio_codec = avcodec_find_encoder_by_name( acodec );
1254 else if ( !strcmp( acodec, "aac" ) || !strcmp( acodec, "vorbis" ) )
1256 mlt_properties_set( properties, "astrict", "experimental" );
1261 audio_codec_id = AV_CODEC_ID_NONE;
1262 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1267 audio_codec = avcodec_find_encoder( audio_codec_id );
1270 // Check for video codec overides
1271 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1272 video_codec_id = AV_CODEC_ID_NONE;
1275 video_codec = avcodec_find_encoder_by_name( vcodec );
1278 video_codec_id = video_codec->id;
1282 video_codec_id = AV_CODEC_ID_NONE;
1283 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1288 video_codec = avcodec_find_encoder( video_codec_id );
1292 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1294 char *name = mlt_properties_get_name( properties, i );
1295 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1297 char *key = strdup( name + 10 );
1298 char *markup = strrchr( key, '.' );
1299 if ( markup && !strcmp( markup, ".markup") )
1302 if ( !strstr( key, ".stream." ) )
1303 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1304 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1306 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1314 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1316 // Get a frame now, so we can set some AVOptions from properties.
1317 frame = mlt_consumer_rt_frame( consumer );
1319 // Set the timecode from the MLT metadata if available.
1322 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1323 if ( timecode && strcmp( timecode, "" ) )
1325 mlt_properties_set( properties, "timecode", timecode );
1326 if ( strchr( timecode, ';' ) )
1327 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1331 // Add audio and video streams
1332 if ( video_codec_id != AV_CODEC_ID_NONE )
1333 video_st = add_video_stream( consumer, oc, video_codec );
1334 if ( audio_codec_id != AV_CODEC_ID_NONE )
1340 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1342 sprintf( key, "channels.%d", i );
1343 int j = mlt_properties_get_int( properties, key );
1347 total_channels += j;
1348 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1354 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1355 total_channels = channels;
1358 mlt_properties_set_int( properties, "channels", total_channels );
1360 // Audio format is determined when adding the audio stream
1361 mlt_audio_format aud_fmt = mlt_audio_none;
1363 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1364 int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1365 sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1367 // Set the parameters (even though we have none...)
1368 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1369 if ( av_set_parameters(oc, NULL) >= 0 )
1372 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1373 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1374 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1376 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1378 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1380 // Process properties as AVOptions
1381 char *fpre = mlt_properties_get( properties, "fpre" );
1384 mlt_properties p = mlt_properties_load( fpre );
1385 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1386 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1387 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1388 mlt_properties_close( p );
1390 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1391 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1392 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1394 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1396 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1398 audio_input_nb_samples = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1399 acodec? acodec : NULL );
1400 if ( !audio_input_nb_samples )
1402 // Remove the audio stream from the output context
1404 for ( j = 0; j < oc->nb_streams; j++ )
1406 if ( oc->streams[j] == audio_st[i] )
1407 av_freep( &oc->streams[j] );
1414 // Setup custom I/O if redirecting
1415 if ( mlt_properties_get_int( properties, "redirect" ) )
1417 int buffer_size = 32768;
1418 unsigned char *buffer = av_malloc( buffer_size );
1419 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1420 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1422 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1427 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1428 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1430 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1431 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1432 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1437 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1440 // Open the output file, if needed
1441 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1443 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1444 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1446 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1449 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1450 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1451 goto on_fatal_error;
1455 // Write the stream header.
1456 if ( mlt_properties_get_int( properties, "running" ) )
1457 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1458 avformat_write_header( oc, NULL );
1460 av_write_header( oc );
1463 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1466 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1467 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1468 goto on_fatal_error;
1472 // Last check - need at least one stream
1473 if ( !audio_st[0] && !video_st )
1475 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1476 goto on_fatal_error;
1481 converted_avframe = alloc_picture( video_st->codec->pix_fmt, width, height );
1483 #if LIBAVCODEC_VERSION_MAJOR >= 54
1484 // Allocate audio AVFrame
1487 audio_avframe = avcodec_alloc_frame();
1488 if ( audio_avframe ) {
1489 AVCodecContext *c = audio_st[0]->codec;
1490 audio_avframe->format = c->sample_fmt;
1491 audio_avframe->nb_samples = audio_input_nb_samples;
1492 audio_avframe->channel_layout = c->channel_layout;
1494 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to allocate audio AVFrame\n" );
1495 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1496 goto on_fatal_error;
1501 // Get the starting time (can ignore the times above)
1502 gettimeofday( &ante, NULL );
1504 // Loop while running
1505 while( mlt_properties_get_int( properties, "running" ) &&
1506 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1509 frame = mlt_consumer_rt_frame( consumer );
1511 // Check that we have a frame to work with
1512 if ( frame != NULL )
1514 // Increment frames dispatched
1517 // Default audio args
1518 frame_properties = MLT_FRAME_PROPERTIES( frame );
1520 // Check for the terminated condition
1521 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1523 // Get audio and append to the fifo
1524 if ( !terminated && audio_st[0] )
1526 samples = mlt_sample_calculator( fps, frequency, count ++ );
1527 channels = total_channels;
1528 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1530 // Save the audio channel remap properties for later
1531 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1533 // Create the fifo if we don't have one
1536 fifo = sample_fifo_init( frequency, channels );
1537 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1541 // Silence if not normal forward speed
1542 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1543 memset( pcm, 0, samples * channels * sample_bytes );
1545 // Append the samples
1546 sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1547 total_time += ( samples * 1000000 ) / frequency;
1550 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1554 if ( !terminated && video_st )
1555 mlt_deque_push_back( queue, frame );
1557 mlt_frame_close( frame );
1561 // While we have stuff to process, process...
1564 // Write interleaved audio and video frames
1565 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1568 if ( ( video_st && terminated ) || ( channels * audio_input_nb_samples ) < sample_fifo_used( fifo ) / sample_bytes )
1570 int j = 0; // channel offset into interleaved source buffer
1571 int n = FFMIN( FFMIN( channels * audio_input_nb_samples, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1573 // Get the audio samples
1576 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1578 else if ( audio_codec_id == AV_CODEC_ID_VORBIS && terminated )
1580 // This prevents an infinite loop when some versions of vorbis do not
1581 // increment pts when encoding silence.
1582 audio_pts = video_pts;
1587 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1589 samples = n / channels;
1591 // For each output stream
1592 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1594 AVStream *stream = audio_st[i];
1595 AVCodecContext *codec = stream->codec;
1598 av_init_packet( &pkt );
1599 pkt.data = audio_outbuf;
1600 pkt.size = audio_outbuf_size;
1602 // Optimized for single track and no channel remap
1603 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1605 void* p = audio_buf_1;
1606 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1607 if ( codec->sample_fmt == AV_SAMPLE_FMT_FLTP )
1608 p = interleaved_to_planar( samples, channels, p, sizeof( float ) );
1609 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S16P )
1610 p = interleaved_to_planar( samples, channels, p, sizeof( int16_t ) );
1611 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S32P )
1612 p = interleaved_to_planar( samples, channels, p, sizeof( int32_t ) );
1613 else if ( codec->sample_fmt == AV_SAMPLE_FMT_U8P )
1614 p = interleaved_to_planar( samples, channels, p, sizeof( uint8_t ) );
1616 #if LIBAVCODEC_VERSION_MAJOR >= 54
1617 audio_avframe->nb_samples = FFMAX( samples, audio_input_nb_samples );
1618 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
1619 audio_avframe->pts = synth_audio_pts;
1620 synth_audio_pts += audio_avframe->nb_samples;
1621 avcodec_fill_audio_frame( audio_avframe, codec->channels, codec->sample_fmt,
1622 (const uint8_t*) p, AUDIO_ENCODE_BUFFER_SIZE, 0 );
1624 int ret = avcodec_encode_audio2( codec, &pkt, audio_avframe, &got_packet );
1627 else if ( !got_packet )
1630 codec->frame_size = FFMAX( samples, audio_input_nb_samples );
1631 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, p );
1632 pkt.pts = codec->coded_frame? codec->coded_frame->pts : AV_NOPTS_VALUE;
1633 pkt.flags |= PKT_FLAG_KEY;
1636 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1637 if ( p != audio_buf_1 )
1638 mlt_pool_release( p );
1643 // Extract the audio channels according to channel mapping
1644 int dest_offset = 0; // channel offset into interleaved dest buffer
1646 // Get the number of channels for this stream
1647 sprintf( key, "channels.%d", i );
1648 int current_channels = mlt_properties_get_int( properties, key );
1650 // Clear the destination audio buffer.
1652 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1654 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1656 // For each output channel
1657 while ( dest_offset < current_channels && j < total_channels )
1659 int map_start = -1, map_channels = 0;
1660 int source_offset = 0;
1663 // Look for a mapping that starts at j
1664 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1666 sprintf( key, "%d.channels", k );
1667 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1668 sprintf( key, "%d.start", k );
1669 if ( mlt_properties_get( frame_meta_properties, key ) )
1670 map_start = mlt_properties_get_int( frame_meta_properties, key );
1671 if ( map_start != j )
1672 source_offset += map_channels;
1676 if ( map_start != j )
1678 map_channels = current_channels;
1682 // Copy samples if source offset valid
1683 if ( source_offset < channels )
1685 // Interleave the audio buffer with the # channels for this stream/mapping.
1686 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1688 void *src = audio_buf_1 + source_offset * sample_bytes;
1689 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1690 int s = samples + 1;
1693 memcpy( dest, src, sample_bytes );
1694 dest += current_channels * sample_bytes;
1695 src += channels * sample_bytes;
1699 // Otherwise silence
1702 j += current_channels;
1703 dest_offset += current_channels;
1706 #if LIBAVCODEC_VERSION_MAJOR >= 54
1707 audio_avframe->nb_samples = FFMAX( samples, audio_input_nb_samples );
1708 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
1709 audio_avframe->pts = synth_audio_pts;
1710 synth_audio_pts += audio_avframe->nb_samples;
1711 avcodec_fill_audio_frame( audio_avframe, codec->channels, codec->sample_fmt,
1712 (const uint8_t*) audio_buf_2, AUDIO_ENCODE_BUFFER_SIZE, 0 );
1714 int ret = avcodec_encode_audio2( codec, &pkt, audio_avframe, &got_packet );
1717 else if ( !got_packet )
1720 codec->frame_size = FFMAX( samples, audio_input_nb_samples );
1721 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1722 pkt.pts = codec->coded_frame? codec->coded_frame->pts : AV_NOPTS_VALUE;
1723 pkt.flags |= PKT_FLAG_KEY;
1729 // Write the compressed frame in the media file
1730 if ( pkt.pts != AV_NOPTS_VALUE )
1731 pkt.pts = av_rescale_q( pkt.pts, codec->time_base, stream->time_base );
1732 #if LIBAVCODEC_VERSION_MAJOR >= 55
1733 if ( pkt.dts != AV_NOPTS_VALUE )
1734 pkt.dts = av_rescale_q( pkt.dts, codec->time_base, stream->time_base );
1735 if ( pkt.duration > 0 )
1736 pkt.duration = av_rescale_q( pkt.duration, codec->time_base, stream->time_base );
1738 pkt.stream_index = stream->index;
1739 if ( av_interleaved_write_frame( oc, &pkt ) )
1741 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1742 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1743 goto on_fatal_error;
1746 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame_size %d stream pts %"PRId64"\n",
1747 stream->index, pkt.pts, codec->frame_size, stream->pts.val );
1749 else if ( pkt.size < 0 )
1751 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with audio encode %d\n", frame_count );
1752 if ( ++error_count > 2 )
1753 goto on_fatal_error;
1758 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1767 else if ( video_st )
1770 if ( mlt_deque_count( queue ) )
1773 AVCodecContext *c = video_st->codec;
1775 frame = mlt_deque_pop_front( queue );
1776 frame_properties = MLT_FRAME_PROPERTIES( frame );
1778 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1783 int stride = mlt_image_format_size( img_fmt, width, 0, NULL );
1785 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1788 // Convert the mlt frame to an AVPicture
1789 if ( img_fmt == mlt_image_yuv420p )
1791 memcpy( video_avframe->data[0], q, video_avframe->linesize[0] );
1793 memcpy( video_avframe->data[1], q, video_avframe->linesize[1] );
1795 memcpy( video_avframe->data[2], q, video_avframe->linesize[2] );
1797 else for ( i = 0; i < height; i ++ )
1799 p = video_avframe->data[0] + i * video_avframe->linesize[0];
1800 memcpy( p, q, stride );
1804 // Do the colour space conversion
1805 int flags = SWS_BICUBIC;
1807 flags |= SWS_CPU_CAPS_MMX;
1810 flags |= SWS_CPU_CAPS_MMX2;
1812 struct SwsContext *context = sws_getContext( width, height, pick_pix_fmt( img_fmt ),
1813 width, height, c->pix_fmt, flags, NULL, NULL, NULL);
1814 sws_scale( context, (const uint8_t* const*) video_avframe->data, video_avframe->linesize, 0, height,
1815 converted_avframe->data, converted_avframe->linesize);
1816 sws_freeContext( context );
1818 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1820 // Apply the alpha if applicable
1821 if ( !mlt_properties_get( properties, "mlt_image_format" ) ||
1822 strcmp( mlt_properties_get( properties, "mlt_image_format" ), "rgb24a" ) )
1823 if ( c->pix_fmt == PIX_FMT_RGBA ||
1824 c->pix_fmt == PIX_FMT_ARGB ||
1825 c->pix_fmt == PIX_FMT_BGRA )
1827 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1830 for ( i = 0; i < height; i ++ )
1832 n = ( width + 7 ) / 8;
1833 p = converted_avframe->data[ 0 ] + i * converted_avframe->linesize[ 0 ] + 3;
1837 case 0: do { *p = *alpha++; p += 4;
1838 case 7: *p = *alpha++; p += 4;
1839 case 6: *p = *alpha++; p += 4;
1840 case 5: *p = *alpha++; p += 4;
1841 case 4: *p = *alpha++; p += 4;
1842 case 3: *p = *alpha++; p += 4;
1843 case 2: *p = *alpha++; p += 4;
1844 case 1: *p = *alpha++; p += 4;
1852 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1854 // raw video case. The API will change slightly in the near future for that
1856 av_init_packet(&pkt);
1858 // Set frame interlace hints
1859 c->coded_frame->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1860 c->coded_frame->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1861 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(61<<8)+100)
1862 if ( mlt_properties_get_int( frame_properties, "progressive" ) )
1863 c->field_order = AV_FIELD_PROGRESSIVE;
1865 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TT : AV_FIELD_BB;
1867 pkt.flags |= PKT_FLAG_KEY;
1868 pkt.stream_index = video_st->index;
1869 pkt.data = (uint8_t *)converted_avframe;
1870 pkt.size = sizeof(AVPicture);
1872 ret = av_write_frame(oc, &pkt);
1873 video_pts += c->frame_size;
1878 av_init_packet( &pkt );
1879 if ( c->codec->id == AV_CODEC_ID_RAWVIDEO ) {
1883 pkt.data = video_outbuf;
1884 pkt.size = video_outbuf_size;
1888 converted_avframe->quality = c->global_quality;
1889 converted_avframe->pts = frame_count;
1891 // Set frame interlace hints
1892 converted_avframe->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1893 converted_avframe->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1894 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(61<<8)+100)
1895 if ( mlt_properties_get_int( frame_properties, "progressive" ) )
1896 c->field_order = AV_FIELD_PROGRESSIVE;
1897 else if ( c->codec_id == AV_CODEC_ID_MJPEG )
1898 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TT : AV_FIELD_BB;
1900 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TB : AV_FIELD_BT;
1904 #if LIBAVCODEC_VERSION_MAJOR >= 55
1906 ret = avcodec_encode_video2( c, &pkt, converted_avframe, &got_packet );
1909 else if ( !got_packet )
1912 pkt.size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, converted_avframe );
1913 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
1914 if ( c->coded_frame && c->coded_frame->key_frame )
1915 pkt.flags |= PKT_FLAG_KEY;
1918 // If zero size, it means the image was buffered
1921 if ( pkt.pts != AV_NOPTS_VALUE )
1922 pkt.pts = av_rescale_q( pkt.pts, c->time_base, video_st->time_base );
1923 #if LIBAVCODEC_VERSION_MAJOR >= 55
1924 if ( pkt.dts != AV_NOPTS_VALUE )
1925 pkt.dts = av_rescale_q( pkt.dts, c->time_base, video_st->time_base );
1927 pkt.stream_index = video_st->index;
1929 // write the compressed frame in the media file
1930 ret = av_interleaved_write_frame(oc, &pkt);
1931 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1932 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1934 // Dual pass logging
1935 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1936 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1940 else if ( pkt.size < 0 )
1942 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1943 if ( ++error_count > 2 )
1944 goto on_fatal_error;
1951 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1952 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1953 goto on_fatal_error;
1955 mlt_frame_close( frame );
1964 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1966 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1967 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1970 if ( real_time_output == 1 && frames % 2 == 0 )
1972 long passed = time_difference( &ante );
1975 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
1978 if ( passed < total_time )
1980 long total = ( total_time - passed );
1981 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1982 nanosleep( &t, NULL );
1987 // Flush the encoder buffers
1988 if ( real_time_output <= 0 )
1991 // TODO: flush all audio streams
1992 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1994 AVCodecContext *c = audio_st[0]->codec;
1996 av_init_packet( &pkt );
1997 pkt.data = audio_outbuf;
2000 if ( fifo && sample_fifo_used( fifo ) > 0 )
2002 // Drain the MLT FIFO
2003 int samples = FFMIN( FFMIN( channels * audio_input_nb_samples, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
2004 sample_fifo_fetch( fifo, audio_buf_1, samples * sample_bytes );
2005 void* p = audio_buf_1;
2006 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2007 if ( c->sample_fmt == AV_SAMPLE_FMT_FLTP )
2008 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( float ) );
2009 else if ( c->sample_fmt == AV_SAMPLE_FMT_S16P )
2010 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( int16_t ) );
2011 else if ( c->sample_fmt == AV_SAMPLE_FMT_S32P )
2012 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( int32_t ) );
2013 else if ( c->sample_fmt == AV_SAMPLE_FMT_U8P )
2014 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( uint8_t ) );
2016 #if LIBAVCODEC_VERSION_MAJOR >= 54
2017 pkt.size = audio_outbuf_size;
2018 audio_avframe->nb_samples = FFMAX( samples / channels, audio_input_nb_samples );
2019 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
2020 audio_avframe->pts = synth_audio_pts;
2021 synth_audio_pts += audio_avframe->nb_samples;
2022 avcodec_fill_audio_frame( audio_avframe, c->channels, c->sample_fmt,
2023 (const uint8_t*) p, AUDIO_ENCODE_BUFFER_SIZE, 0 );
2025 int ret = avcodec_encode_audio2( c, &pkt, audio_avframe, &got_packet );
2028 else if ( !got_packet )
2031 c->frame_size = FFMAX( samples / channels, audio_input_nb_samples );
2032 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, p );
2034 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2035 if ( p != audio_buf_1 )
2036 mlt_pool_release( p );
2038 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
2043 if ( pkt.size <= 0 ) {
2044 #if LIBAVCODEC_VERSION_MAJOR >= 54
2045 pkt.size = audio_outbuf_size;
2047 int ret = avcodec_encode_audio2( c, &pkt, NULL, &got_packet );
2050 else if ( !got_packet )
2053 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
2054 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
2055 pkt.flags |= PKT_FLAG_KEY;
2058 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
2059 if ( pkt.size <= 0 )
2063 // Write the compressed frame in the media file
2064 if ( pkt.pts != AV_NOPTS_VALUE )
2065 pkt.pts = av_rescale_q( pkt.pts, c->time_base, audio_st[0]->time_base );
2066 #if LIBAVCODEC_VERSION_MAJOR >= 55
2067 if ( pkt.dts != AV_NOPTS_VALUE )
2068 pkt.dts = av_rescale_q( pkt.dts, c->time_base, audio_st[0]->time_base );
2069 if ( pkt.duration > 0 )
2070 pkt.duration = av_rescale_q( pkt.duration, c->time_base, audio_st[0]->time_base );
2072 pkt.stream_index = audio_st[0]->index;
2073 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
2075 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
2081 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
2083 AVCodecContext *c = video_st->codec;
2085 av_init_packet( &pkt );
2086 if ( c->codec->id == AV_CODEC_ID_RAWVIDEO ) {
2090 pkt.data = video_outbuf;
2091 pkt.size = video_outbuf_size;
2095 #if LIBAVCODEC_VERSION_MAJOR >= 55
2097 int ret = avcodec_encode_video2( c, &pkt, NULL, &got_packet );
2100 else if ( !got_packet )
2103 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
2104 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
2105 if( c->coded_frame && c->coded_frame->key_frame )
2106 pkt.flags |= PKT_FLAG_KEY;
2108 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
2109 if ( pkt.size <= 0 )
2112 if ( pkt.pts != AV_NOPTS_VALUE )
2113 pkt.pts = av_rescale_q( pkt.pts, c->time_base, video_st->time_base );
2114 #if LIBAVCODEC_VERSION_MAJOR >= 55
2115 if ( pkt.dts != AV_NOPTS_VALUE )
2116 pkt.dts = av_rescale_q( pkt.dts, c->time_base, video_st->time_base );
2118 pkt.stream_index = video_st->index;
2120 // write the compressed frame in the media file
2121 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
2123 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
2124 mlt_events_fire( properties, "consumer-fatal-error", NULL );
2125 goto on_fatal_error;
2127 // Dual pass logging
2128 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
2129 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
2135 // Write the trailer, if any
2137 av_write_trailer( oc );
2141 close_video(oc, video_st);
2142 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
2143 close_audio( oc, audio_st[i] );
2146 for ( i = 0; i < oc->nb_streams; i++ )
2147 av_freep( &oc->streams[i] );
2149 // Close the output file
2150 if ( !( fmt->flags & AVFMT_NOFILE ) &&
2151 !mlt_properties_get_int( properties, "redirect" ) )
2153 #if LIBAVFORMAT_VERSION_MAJOR >= 53
2154 if ( oc->pb ) avio_close( oc->pb );
2156 if ( oc->pb ) url_fclose( oc->pb );
2160 // Clean up input and output frames
2161 if ( converted_avframe )
2162 av_free( converted_avframe->data[0] );
2163 av_free( converted_avframe );
2164 av_free( video_avframe->data[0] );
2165 av_free( video_avframe );
2166 av_free( video_outbuf );
2167 av_free( audio_avframe );
2168 av_free( audio_buf_1 );
2169 av_free( audio_buf_2 );
2174 // Just in case we terminated on pause
2175 mlt_consumer_stopped( consumer );
2176 mlt_properties_close( frame_meta_properties );
2178 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
2180 // Remove the dual pass log file
2181 if ( mlt_properties_get( properties, "_logfilename" ) )
2182 remove( mlt_properties_get( properties, "_logfilename" ) );
2184 // Remove the x264 dual pass logs
2185 char *cwd = getcwd( NULL, 0 );
2186 const char *file = "x264_2pass.log";
2187 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2188 sprintf( full, "%s/%s", cwd, file );
2191 file = "x264_2pass.log.temp";
2192 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2193 sprintf( full, "%s/%s", cwd, file );
2196 file = "x264_2pass.log.mbtree";
2197 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2198 sprintf( full, "%s/%s", cwd, file );
2202 remove( "x264_2pass.log.temp" );
2205 while ( ( frame = mlt_deque_pop_back( queue ) ) )
2206 mlt_frame_close( frame );
2211 /** Close the consumer.
2214 static void consumer_close( mlt_consumer consumer )
2216 // Stop the consumer
2217 mlt_consumer_stop( consumer );
2220 mlt_consumer_close( consumer );