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 = NULL;
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 #if LIBAVUTIL_VERSION_INT >= ((53<<16)+(2<<8)+0)
1236 avformat_alloc_output_context2( &oc, fmt, format, filename );
1238 oc = avformat_alloc_context( );
1240 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1242 if ( oc->oformat && oc->oformat->priv_class && !oc->priv_data && oc->oformat->priv_data_size ) {
1243 oc->priv_data = av_mallocz( oc->oformat->priv_data_size );
1244 if ( oc->priv_data ) {
1245 *(const AVClass**)oc->priv_data = oc->oformat->priv_class;
1246 av_opt_set_defaults( oc->priv_data );
1251 // Get the codec ids selected
1252 audio_codec_id = fmt->audio_codec;
1253 video_codec_id = fmt->video_codec;
1255 // Check for audio codec overides
1256 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1257 audio_codec_id = AV_CODEC_ID_NONE;
1260 audio_codec = avcodec_find_encoder_by_name( acodec );
1263 audio_codec_id = audio_codec->id;
1264 if ( audio_codec_id == AV_CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1266 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1267 acodec = mlt_properties_get( properties, "_acodec" );
1268 audio_codec = avcodec_find_encoder_by_name( acodec );
1270 else if ( !strcmp( acodec, "aac" ) || !strcmp( acodec, "vorbis" ) )
1272 mlt_properties_set( properties, "astrict", "experimental" );
1277 audio_codec_id = AV_CODEC_ID_NONE;
1278 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1283 audio_codec = avcodec_find_encoder( audio_codec_id );
1286 // Check for video codec overides
1287 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1288 video_codec_id = AV_CODEC_ID_NONE;
1291 video_codec = avcodec_find_encoder_by_name( vcodec );
1294 video_codec_id = video_codec->id;
1298 video_codec_id = AV_CODEC_ID_NONE;
1299 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1304 video_codec = avcodec_find_encoder( video_codec_id );
1308 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1310 char *name = mlt_properties_get_name( properties, i );
1311 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1313 char *key = strdup( name + 10 );
1314 char *markup = strrchr( key, '.' );
1315 if ( markup && !strcmp( markup, ".markup") )
1318 if ( !strstr( key, ".stream." ) )
1319 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1320 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1322 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1329 // Get a frame now, so we can set some AVOptions from properties.
1330 frame = mlt_consumer_rt_frame( consumer );
1332 // Set the timecode from the MLT metadata if available.
1335 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1336 if ( timecode && strcmp( timecode, "" ) )
1338 mlt_properties_set( properties, "timecode", timecode );
1339 if ( strchr( timecode, ';' ) )
1340 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1344 // Add audio and video streams
1345 if ( video_codec_id != AV_CODEC_ID_NONE )
1346 video_st = add_video_stream( consumer, oc, video_codec );
1347 if ( audio_codec_id != AV_CODEC_ID_NONE )
1353 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1355 sprintf( key, "channels.%d", i );
1356 int j = mlt_properties_get_int( properties, key );
1360 total_channels += j;
1361 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1367 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1368 total_channels = channels;
1371 mlt_properties_set_int( properties, "channels", total_channels );
1373 // Audio format is determined when adding the audio stream
1374 mlt_audio_format aud_fmt = mlt_audio_none;
1376 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1377 int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1378 sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1380 // Set the parameters (even though we have none...)
1381 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1382 if ( av_set_parameters(oc, NULL) >= 0 )
1385 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1386 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1387 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1389 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1391 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1393 // Process properties as AVOptions
1394 char *fpre = mlt_properties_get( properties, "fpre" );
1397 mlt_properties p = mlt_properties_load( fpre );
1398 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1399 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1400 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1401 mlt_properties_close( p );
1403 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1404 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1405 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1407 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1409 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1411 audio_input_nb_samples = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1412 acodec? acodec : NULL );
1413 if ( !audio_input_nb_samples )
1415 // Remove the audio stream from the output context
1417 for ( j = 0; j < oc->nb_streams; j++ )
1419 if ( oc->streams[j] == audio_st[i] )
1420 av_freep( &oc->streams[j] );
1427 // Setup custom I/O if redirecting
1428 if ( mlt_properties_get_int( properties, "redirect" ) )
1430 int buffer_size = 32768;
1431 unsigned char *buffer = av_malloc( buffer_size );
1432 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1433 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1435 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1440 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1441 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1443 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1444 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1445 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1450 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1453 // Open the output file, if needed
1454 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1456 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1457 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1459 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1462 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1463 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1464 goto on_fatal_error;
1468 // Write the stream header.
1469 if ( mlt_properties_get_int( properties, "running" ) )
1470 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1471 avformat_write_header( oc, NULL );
1473 av_write_header( oc );
1476 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1479 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1480 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1481 goto on_fatal_error;
1485 // Last check - need at least one stream
1486 if ( !audio_st[0] && !video_st )
1488 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1489 goto on_fatal_error;
1494 converted_avframe = alloc_picture( video_st->codec->pix_fmt, width, height );
1496 #if LIBAVCODEC_VERSION_MAJOR >= 54
1497 // Allocate audio AVFrame
1500 audio_avframe = avcodec_alloc_frame();
1501 if ( audio_avframe ) {
1502 AVCodecContext *c = audio_st[0]->codec;
1503 audio_avframe->format = c->sample_fmt;
1504 audio_avframe->nb_samples = audio_input_nb_samples;
1505 audio_avframe->channel_layout = c->channel_layout;
1507 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to allocate audio AVFrame\n" );
1508 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1509 goto on_fatal_error;
1514 // Get the starting time (can ignore the times above)
1515 gettimeofday( &ante, NULL );
1517 // Loop while running
1518 while( mlt_properties_get_int( properties, "running" ) &&
1519 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1522 frame = mlt_consumer_rt_frame( consumer );
1524 // Check that we have a frame to work with
1525 if ( frame != NULL )
1527 // Increment frames dispatched
1530 // Default audio args
1531 frame_properties = MLT_FRAME_PROPERTIES( frame );
1533 // Check for the terminated condition
1534 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1536 // Get audio and append to the fifo
1537 if ( !terminated && audio_st[0] )
1539 samples = mlt_sample_calculator( fps, frequency, count ++ );
1540 channels = total_channels;
1541 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1543 // Save the audio channel remap properties for later
1544 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1546 // Create the fifo if we don't have one
1549 fifo = sample_fifo_init( frequency, channels );
1550 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1554 // Silence if not normal forward speed
1555 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1556 memset( pcm, 0, samples * channels * sample_bytes );
1558 // Append the samples
1559 sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1560 total_time += ( samples * 1000000 ) / frequency;
1563 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1567 if ( !terminated && video_st )
1568 mlt_deque_push_back( queue, frame );
1570 mlt_frame_close( frame );
1574 // While we have stuff to process, process...
1577 // Write interleaved audio and video frames
1578 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1581 if ( ( video_st && terminated ) || ( channels * audio_input_nb_samples ) < sample_fifo_used( fifo ) / sample_bytes )
1583 int j = 0; // channel offset into interleaved source buffer
1584 int n = FFMIN( FFMIN( channels * audio_input_nb_samples, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1586 // Get the audio samples
1589 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1591 else if ( audio_codec_id == AV_CODEC_ID_VORBIS && terminated )
1593 // This prevents an infinite loop when some versions of vorbis do not
1594 // increment pts when encoding silence.
1595 audio_pts = video_pts;
1600 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1602 samples = n / channels;
1604 // For each output stream
1605 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1607 AVStream *stream = audio_st[i];
1608 AVCodecContext *codec = stream->codec;
1611 av_init_packet( &pkt );
1612 pkt.data = audio_outbuf;
1613 pkt.size = audio_outbuf_size;
1615 // Optimized for single track and no channel remap
1616 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1618 void* p = audio_buf_1;
1619 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1620 if ( codec->sample_fmt == AV_SAMPLE_FMT_FLTP )
1621 p = interleaved_to_planar( samples, channels, p, sizeof( float ) );
1622 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S16P )
1623 p = interleaved_to_planar( samples, channels, p, sizeof( int16_t ) );
1624 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S32P )
1625 p = interleaved_to_planar( samples, channels, p, sizeof( int32_t ) );
1626 else if ( codec->sample_fmt == AV_SAMPLE_FMT_U8P )
1627 p = interleaved_to_planar( samples, channels, p, sizeof( uint8_t ) );
1629 #if LIBAVCODEC_VERSION_MAJOR >= 54
1630 audio_avframe->nb_samples = FFMAX( samples, audio_input_nb_samples );
1631 #if LIBAVCODEC_VERSION_MAJOR >= 55
1632 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
1633 audio_avframe->pts = synth_audio_pts;
1634 synth_audio_pts += audio_avframe->nb_samples;
1636 avcodec_fill_audio_frame( audio_avframe, codec->channels, codec->sample_fmt,
1637 (const uint8_t*) p, AUDIO_ENCODE_BUFFER_SIZE, 0 );
1639 int ret = avcodec_encode_audio2( codec, &pkt, audio_avframe, &got_packet );
1642 else if ( !got_packet )
1645 codec->frame_size = FFMAX( samples, audio_input_nb_samples );
1646 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, p );
1647 pkt.pts = codec->coded_frame? codec->coded_frame->pts : AV_NOPTS_VALUE;
1648 pkt.flags |= PKT_FLAG_KEY;
1651 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1652 if ( p != audio_buf_1 )
1653 mlt_pool_release( p );
1658 // Extract the audio channels according to channel mapping
1659 int dest_offset = 0; // channel offset into interleaved dest buffer
1661 // Get the number of channels for this stream
1662 sprintf( key, "channels.%d", i );
1663 int current_channels = mlt_properties_get_int( properties, key );
1665 // Clear the destination audio buffer.
1667 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1669 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1671 // For each output channel
1672 while ( dest_offset < current_channels && j < total_channels )
1674 int map_start = -1, map_channels = 0;
1675 int source_offset = 0;
1678 // Look for a mapping that starts at j
1679 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1681 sprintf( key, "%d.channels", k );
1682 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1683 sprintf( key, "%d.start", k );
1684 if ( mlt_properties_get( frame_meta_properties, key ) )
1685 map_start = mlt_properties_get_int( frame_meta_properties, key );
1686 if ( map_start != j )
1687 source_offset += map_channels;
1691 if ( map_start != j )
1693 map_channels = current_channels;
1697 // Copy samples if source offset valid
1698 if ( source_offset < channels )
1700 // Interleave the audio buffer with the # channels for this stream/mapping.
1701 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1703 void *src = audio_buf_1 + source_offset * sample_bytes;
1704 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1705 int s = samples + 1;
1708 memcpy( dest, src, sample_bytes );
1709 dest += current_channels * sample_bytes;
1710 src += channels * sample_bytes;
1714 // Otherwise silence
1717 j += current_channels;
1718 dest_offset += current_channels;
1721 #if LIBAVCODEC_VERSION_MAJOR >= 54
1722 audio_avframe->nb_samples = FFMAX( samples, audio_input_nb_samples );
1723 #if LIBAVCODEC_VERSION_MAJOR >= 55
1724 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
1725 audio_avframe->pts = synth_audio_pts;
1726 synth_audio_pts += audio_avframe->nb_samples;
1728 avcodec_fill_audio_frame( audio_avframe, codec->channels, codec->sample_fmt,
1729 (const uint8_t*) audio_buf_2, AUDIO_ENCODE_BUFFER_SIZE, 0 );
1731 int ret = avcodec_encode_audio2( codec, &pkt, audio_avframe, &got_packet );
1734 else if ( !got_packet )
1737 codec->frame_size = FFMAX( samples, audio_input_nb_samples );
1738 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1739 pkt.pts = codec->coded_frame? codec->coded_frame->pts : AV_NOPTS_VALUE;
1740 pkt.flags |= PKT_FLAG_KEY;
1746 // Write the compressed frame in the media file
1747 if ( pkt.pts != AV_NOPTS_VALUE )
1748 pkt.pts = av_rescale_q( pkt.pts, codec->time_base, stream->time_base );
1749 #if LIBAVCODEC_VERSION_MAJOR >= 55
1750 if ( pkt.dts != AV_NOPTS_VALUE )
1751 pkt.dts = av_rescale_q( pkt.dts, codec->time_base, stream->time_base );
1752 if ( pkt.duration > 0 )
1753 pkt.duration = av_rescale_q( pkt.duration, codec->time_base, stream->time_base );
1755 pkt.stream_index = stream->index;
1756 if ( av_interleaved_write_frame( oc, &pkt ) )
1758 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1759 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1760 goto on_fatal_error;
1763 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame_size %d stream pts %"PRId64"\n",
1764 stream->index, pkt.pts, codec->frame_size, stream->pts.val );
1766 else if ( pkt.size < 0 )
1768 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with audio encode %d\n", frame_count );
1769 if ( ++error_count > 2 )
1770 goto on_fatal_error;
1775 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1784 else if ( video_st )
1787 if ( mlt_deque_count( queue ) )
1790 AVCodecContext *c = video_st->codec;
1792 frame = mlt_deque_pop_front( queue );
1793 frame_properties = MLT_FRAME_PROPERTIES( frame );
1795 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1800 int stride = mlt_image_format_size( img_fmt, width, 0, NULL );
1802 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1805 // Convert the mlt frame to an AVPicture
1806 if ( img_fmt == mlt_image_yuv420p )
1808 memcpy( video_avframe->data[0], q, video_avframe->linesize[0] );
1810 memcpy( video_avframe->data[1], q, video_avframe->linesize[1] );
1812 memcpy( video_avframe->data[2], q, video_avframe->linesize[2] );
1814 else for ( i = 0; i < height; i ++ )
1816 p = video_avframe->data[0] + i * video_avframe->linesize[0];
1817 memcpy( p, q, stride );
1821 // Do the colour space conversion
1822 int flags = SWS_BICUBIC;
1824 flags |= SWS_CPU_CAPS_MMX;
1827 flags |= SWS_CPU_CAPS_MMX2;
1829 struct SwsContext *context = sws_getContext( width, height, pick_pix_fmt( img_fmt ),
1830 width, height, c->pix_fmt, flags, NULL, NULL, NULL);
1831 sws_scale( context, (const uint8_t* const*) video_avframe->data, video_avframe->linesize, 0, height,
1832 converted_avframe->data, converted_avframe->linesize);
1833 sws_freeContext( context );
1835 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1837 // Apply the alpha if applicable
1838 if ( !mlt_properties_get( properties, "mlt_image_format" ) ||
1839 strcmp( mlt_properties_get( properties, "mlt_image_format" ), "rgb24a" ) )
1840 if ( c->pix_fmt == PIX_FMT_RGBA ||
1841 c->pix_fmt == PIX_FMT_ARGB ||
1842 c->pix_fmt == PIX_FMT_BGRA )
1844 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1847 for ( i = 0; i < height; i ++ )
1849 n = ( width + 7 ) / 8;
1850 p = converted_avframe->data[ 0 ] + i * converted_avframe->linesize[ 0 ] + 3;
1854 case 0: do { *p = *alpha++; p += 4;
1855 case 7: *p = *alpha++; p += 4;
1856 case 6: *p = *alpha++; p += 4;
1857 case 5: *p = *alpha++; p += 4;
1858 case 4: *p = *alpha++; p += 4;
1859 case 3: *p = *alpha++; p += 4;
1860 case 2: *p = *alpha++; p += 4;
1861 case 1: *p = *alpha++; p += 4;
1869 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1871 // raw video case. The API will change slightly in the near future for that
1873 av_init_packet(&pkt);
1875 // Set frame interlace hints
1876 c->coded_frame->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1877 c->coded_frame->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1878 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(61<<8)+100)
1879 if ( mlt_properties_get_int( frame_properties, "progressive" ) )
1880 c->field_order = AV_FIELD_PROGRESSIVE;
1882 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TT : AV_FIELD_BB;
1884 pkt.flags |= PKT_FLAG_KEY;
1885 pkt.stream_index = video_st->index;
1886 pkt.data = (uint8_t *)converted_avframe;
1887 pkt.size = sizeof(AVPicture);
1889 ret = av_write_frame(oc, &pkt);
1890 video_pts += c->frame_size;
1895 av_init_packet( &pkt );
1896 if ( c->codec->id == AV_CODEC_ID_RAWVIDEO ) {
1900 pkt.data = video_outbuf;
1901 pkt.size = video_outbuf_size;
1905 converted_avframe->quality = c->global_quality;
1906 converted_avframe->pts = frame_count;
1908 // Set frame interlace hints
1909 converted_avframe->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1910 converted_avframe->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1911 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(61<<8)+100)
1912 if ( mlt_properties_get_int( frame_properties, "progressive" ) )
1913 c->field_order = AV_FIELD_PROGRESSIVE;
1914 else if ( c->codec_id == AV_CODEC_ID_MJPEG )
1915 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TT : AV_FIELD_BB;
1917 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TB : AV_FIELD_BT;
1921 #if LIBAVCODEC_VERSION_MAJOR >= 55
1923 ret = avcodec_encode_video2( c, &pkt, converted_avframe, &got_packet );
1926 else if ( !got_packet )
1929 pkt.size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, converted_avframe );
1930 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
1931 if ( c->coded_frame && c->coded_frame->key_frame )
1932 pkt.flags |= PKT_FLAG_KEY;
1935 // If zero size, it means the image was buffered
1938 if ( pkt.pts != AV_NOPTS_VALUE )
1939 pkt.pts = av_rescale_q( pkt.pts, c->time_base, video_st->time_base );
1940 #if LIBAVCODEC_VERSION_MAJOR >= 55
1941 if ( pkt.dts != AV_NOPTS_VALUE )
1942 pkt.dts = av_rescale_q( pkt.dts, c->time_base, video_st->time_base );
1944 pkt.stream_index = video_st->index;
1946 // write the compressed frame in the media file
1947 ret = av_interleaved_write_frame(oc, &pkt);
1948 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1949 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1951 // Dual pass logging
1952 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1953 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1957 else if ( pkt.size < 0 )
1959 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1960 if ( ++error_count > 2 )
1961 goto on_fatal_error;
1968 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1969 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1970 goto on_fatal_error;
1972 mlt_frame_close( frame );
1981 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1983 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1984 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1987 if ( real_time_output == 1 && frames % 2 == 0 )
1989 long passed = time_difference( &ante );
1992 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
1995 if ( passed < total_time )
1997 long total = ( total_time - passed );
1998 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1999 nanosleep( &t, NULL );
2004 // Flush the encoder buffers
2005 if ( real_time_output <= 0 )
2008 // TODO: flush all audio streams
2009 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
2011 AVCodecContext *c = audio_st[0]->codec;
2013 av_init_packet( &pkt );
2014 pkt.data = audio_outbuf;
2017 if ( fifo && sample_fifo_used( fifo ) > 0 )
2019 // Drain the MLT FIFO
2020 int samples = FFMIN( FFMIN( channels * audio_input_nb_samples, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
2021 sample_fifo_fetch( fifo, audio_buf_1, samples * sample_bytes );
2022 void* p = audio_buf_1;
2023 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2024 if ( c->sample_fmt == AV_SAMPLE_FMT_FLTP )
2025 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( float ) );
2026 else if ( c->sample_fmt == AV_SAMPLE_FMT_S16P )
2027 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( int16_t ) );
2028 else if ( c->sample_fmt == AV_SAMPLE_FMT_S32P )
2029 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( int32_t ) );
2030 else if ( c->sample_fmt == AV_SAMPLE_FMT_U8P )
2031 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( uint8_t ) );
2033 #if LIBAVCODEC_VERSION_MAJOR >= 54
2034 pkt.size = audio_outbuf_size;
2035 audio_avframe->nb_samples = FFMAX( samples / channels, audio_input_nb_samples );
2036 #if LIBAVCODEC_VERSION_MAJOR >= 55
2037 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
2038 audio_avframe->pts = synth_audio_pts;
2039 synth_audio_pts += audio_avframe->nb_samples;
2041 avcodec_fill_audio_frame( audio_avframe, c->channels, c->sample_fmt,
2042 (const uint8_t*) p, AUDIO_ENCODE_BUFFER_SIZE, 0 );
2044 int ret = avcodec_encode_audio2( c, &pkt, audio_avframe, &got_packet );
2047 else if ( !got_packet )
2050 c->frame_size = FFMAX( samples / channels, audio_input_nb_samples );
2051 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, p );
2053 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2054 if ( p != audio_buf_1 )
2055 mlt_pool_release( p );
2057 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
2062 if ( pkt.size <= 0 ) {
2063 #if LIBAVCODEC_VERSION_MAJOR >= 54
2064 pkt.size = audio_outbuf_size;
2066 int ret = avcodec_encode_audio2( c, &pkt, NULL, &got_packet );
2069 else if ( !got_packet )
2072 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
2073 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
2074 pkt.flags |= PKT_FLAG_KEY;
2077 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
2078 if ( pkt.size <= 0 )
2082 // Write the compressed frame in the media file
2083 if ( pkt.pts != AV_NOPTS_VALUE )
2084 pkt.pts = av_rescale_q( pkt.pts, c->time_base, audio_st[0]->time_base );
2085 #if LIBAVCODEC_VERSION_MAJOR >= 55
2086 if ( pkt.dts != AV_NOPTS_VALUE )
2087 pkt.dts = av_rescale_q( pkt.dts, c->time_base, audio_st[0]->time_base );
2088 if ( pkt.duration > 0 )
2089 pkt.duration = av_rescale_q( pkt.duration, c->time_base, audio_st[0]->time_base );
2091 pkt.stream_index = audio_st[0]->index;
2092 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
2094 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
2100 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
2102 AVCodecContext *c = video_st->codec;
2104 av_init_packet( &pkt );
2105 if ( c->codec->id == AV_CODEC_ID_RAWVIDEO ) {
2109 pkt.data = video_outbuf;
2110 pkt.size = video_outbuf_size;
2114 #if LIBAVCODEC_VERSION_MAJOR >= 55
2116 int ret = avcodec_encode_video2( c, &pkt, NULL, &got_packet );
2119 else if ( !got_packet )
2122 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
2123 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
2124 if( c->coded_frame && c->coded_frame->key_frame )
2125 pkt.flags |= PKT_FLAG_KEY;
2127 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
2128 if ( pkt.size <= 0 )
2131 if ( pkt.pts != AV_NOPTS_VALUE )
2132 pkt.pts = av_rescale_q( pkt.pts, c->time_base, video_st->time_base );
2133 #if LIBAVCODEC_VERSION_MAJOR >= 55
2134 if ( pkt.dts != AV_NOPTS_VALUE )
2135 pkt.dts = av_rescale_q( pkt.dts, c->time_base, video_st->time_base );
2137 pkt.stream_index = video_st->index;
2139 // write the compressed frame in the media file
2140 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
2142 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
2143 mlt_events_fire( properties, "consumer-fatal-error", NULL );
2144 goto on_fatal_error;
2146 // Dual pass logging
2147 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
2148 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
2155 mlt_frame_close( frame );
2157 // Write the trailer, if any
2159 av_write_trailer( oc );
2163 close_video(oc, video_st);
2164 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
2165 close_audio( oc, audio_st[i] );
2168 for ( i = 0; i < oc->nb_streams; i++ )
2169 av_freep( &oc->streams[i] );
2171 // Close the output file
2172 if ( !( fmt->flags & AVFMT_NOFILE ) &&
2173 !mlt_properties_get_int( properties, "redirect" ) )
2175 #if LIBAVFORMAT_VERSION_MAJOR >= 53
2176 if ( oc->pb ) avio_close( oc->pb );
2178 if ( oc->pb ) url_fclose( oc->pb );
2182 // Clean up input and output frames
2183 if ( converted_avframe )
2184 av_free( converted_avframe->data[0] );
2185 av_free( converted_avframe );
2186 av_free( video_avframe->data[0] );
2187 av_free( video_avframe );
2188 av_free( video_outbuf );
2189 av_free( audio_avframe );
2190 av_free( audio_buf_1 );
2191 av_free( audio_buf_2 );
2196 // Just in case we terminated on pause
2197 mlt_consumer_stopped( consumer );
2198 mlt_properties_close( frame_meta_properties );
2200 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
2202 // Remove the dual pass log file
2203 if ( mlt_properties_get( properties, "_logfilename" ) )
2204 remove( mlt_properties_get( properties, "_logfilename" ) );
2206 // Remove the x264 dual pass logs
2207 char *cwd = getcwd( NULL, 0 );
2208 const char *file = "x264_2pass.log";
2209 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2210 sprintf( full, "%s/%s", cwd, file );
2213 file = "x264_2pass.log.temp";
2214 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2215 sprintf( full, "%s/%s", cwd, file );
2218 file = "x264_2pass.log.mbtree";
2219 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2220 sprintf( full, "%s/%s", cwd, file );
2224 remove( "x264_2pass.log.temp" );
2226 // Recent versions of libavcodec/x264 support passlogfile and need cleanup if specified.
2227 if ( !mlt_properties_get( properties, "_logfilename" ) &&
2228 mlt_properties_get( properties, "passlogfile" ) )
2230 file = mlt_properties_get( properties, "passlogfile" );
2232 full = malloc( strlen( file ) + strlen( ".mbtree" ) + 1 );
2233 sprintf( full, "%s.mbtree", file );
2239 while ( ( frame = mlt_deque_pop_back( queue ) ) )
2240 mlt_frame_close( frame );
2245 /** Close the consumer.
2248 static void consumer_close( mlt_consumer consumer )
2250 // Stop the consumer
2251 mlt_consumer_stop( consumer );
2254 mlt_consumer_close( consumer );