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 recompute_aspect_ratio( mlt_properties properties )
201 double ar = mlt_properties_get_double( properties, "aspect" );
202 AVRational rational = av_d2q( ar, 255 );
203 int width = mlt_properties_get_int( properties, "width" );
204 int height = mlt_properties_get_int( properties, "height" );
206 // Update the profile and properties as well since this is an alias
207 // for mlt properties that correspond to profile settings
208 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
209 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
211 // Now compute the sample aspect ratio
212 rational = av_d2q( ar * height / FFMAX(width, 1), 255 );
214 // Update the profile and properties as well since this is an alias
215 // for mlt properties that correspond to profile settings
216 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
217 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
220 static void property_changed( mlt_properties owner, mlt_consumer self, char *name )
222 mlt_properties properties = MLT_CONSUMER_PROPERTIES( self );
224 if ( !strcmp( name, "s" ) )
226 // Obtain the size property
227 char *size = mlt_properties_get( properties, "s" );
228 int width = mlt_properties_get_int( properties, "width" );
229 int height = mlt_properties_get_int( properties, "height" );
232 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
239 mlt_log_warning( MLT_CONSUMER_SERVICE(self), "Invalid size property %s - ignoring.\n", size );
242 // Now ensure we honour the multiple of two requested by libavformat
243 width = ( width / 2 ) * 2;
244 height = ( height / 2 ) * 2;
245 mlt_properties_set_int( properties, "width", width );
246 mlt_properties_set_int( properties, "height", height );
247 recompute_aspect_ratio( properties );
249 // "-aspect" on ffmpeg command line is display aspect ratio
250 else if ( !strcmp( name, "aspect" ) || !strcmp( name, "width" ) || !strcmp( name, "height" ) )
252 recompute_aspect_ratio( properties );
254 // Handle the ffmpeg command line "-r" property for frame rate
255 else if ( !strcmp( name, "r" ) )
257 double frame_rate = mlt_properties_get_double( properties, "r" );
258 AVRational rational = av_d2q( frame_rate, 255 );
259 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
260 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
264 /** Start the consumer.
267 static int consumer_start( mlt_consumer consumer )
269 // Get the properties
270 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
273 // Report information about available muxers and codecs as YAML Tiny
274 char *s = mlt_properties_get( properties, "f" );
275 if ( s && strcmp( s, "list" ) == 0 )
277 mlt_properties doc = mlt_properties_new();
278 mlt_properties formats = mlt_properties_new();
280 AVOutputFormat *format = NULL;
282 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
283 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
284 while ( ( format = av_oformat_next( format ) ) )
286 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
287 mlt_properties_set( formats, key, format->name );
289 s = mlt_properties_serialise_yaml( doc );
290 fprintf( stdout, "%s", s );
292 mlt_properties_close( doc );
295 s = mlt_properties_get( properties, "acodec" );
296 if ( s && strcmp( s, "list" ) == 0 )
298 mlt_properties doc = mlt_properties_new();
299 mlt_properties codecs = mlt_properties_new();
301 AVCodec *codec = NULL;
303 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
304 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
305 while ( ( codec = av_codec_next( codec ) ) )
306 #if (defined(FFUDIV) && LIBAVCODEC_VERSION_INT >= ((54<<16)+(56<<8)+100)) || (LIBAVCODEC_VERSION_INT >= ((54<<16)+(27<<8)+0))
307 if ( codec->encode2 && codec->type == CODEC_TYPE_AUDIO )
308 #elif LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
309 if ( ( codec->encode || codec->encode2 ) && codec->type == CODEC_TYPE_AUDIO )
311 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
314 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
315 mlt_properties_set( codecs, key, codec->name );
317 s = mlt_properties_serialise_yaml( doc );
318 fprintf( stdout, "%s", s );
320 mlt_properties_close( doc );
323 s = mlt_properties_get( properties, "vcodec" );
324 if ( s && strcmp( s, "list" ) == 0 )
326 mlt_properties doc = mlt_properties_new();
327 mlt_properties codecs = mlt_properties_new();
329 AVCodec *codec = NULL;
331 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
332 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
333 while ( ( codec = av_codec_next( codec ) ) )
334 #if (defined(FFUDIV) && LIBAVCODEC_VERSION_INT >= ((54<<16)+(56<<8)+100)) || (LIBAVCODEC_VERSION_INT >= ((54<<16)+(27<<8)+0))
335 if ( codec->encode2 && codec->type == CODEC_TYPE_VIDEO )
336 #elif LIBAVCODEC_VERSION_INT >= ((54<<16)+(0<<8)+0)
337 if ( (codec->encode || codec->encode2) && codec->type == CODEC_TYPE_VIDEO )
339 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
342 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
343 mlt_properties_set( codecs, key, codec->name );
345 s = mlt_properties_serialise_yaml( doc );
346 fprintf( stdout, "%s", s );
348 mlt_properties_close( doc );
352 // Check that we're not already running
353 if ( !error && !mlt_properties_get_int( properties, "running" ) )
356 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
358 mlt_event_block( mlt_properties_get_data( properties, "property-changed event", NULL ) );
360 // Apply AVOptions that are synonyms for standard mlt_consumer options
361 if ( mlt_properties_get( properties, "ac" ) )
362 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
363 if ( mlt_properties_get( properties, "ar" ) )
364 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
366 // Assign the thread to properties
367 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
370 pthread_create( thread, NULL, consumer_thread, consumer );
372 // Set the running state
373 mlt_properties_set_int( properties, "running", 1 );
378 /** Stop the consumer.
381 static int consumer_stop( mlt_consumer consumer )
383 // Get the properties
384 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
385 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
387 // Check that we're running
391 mlt_properties_set_int( properties, "running", 0 );
393 // Wait for termination
394 pthread_join( *thread, NULL );
396 mlt_properties_set_data( properties, "thread", NULL, 0, NULL, NULL );
397 mlt_event_unblock( mlt_properties_get_data( properties, "property-changed event", NULL ) );
403 /** Determine if the consumer is stopped.
406 static int consumer_is_stopped( mlt_consumer consumer )
408 // Get the properties
409 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
410 return !mlt_properties_get_int( properties, "running" );
413 /** Process properties as AVOptions and apply to AV context obj
416 static void apply_properties( void *obj, mlt_properties properties, int flags )
419 int count = mlt_properties_count( properties );
420 #if LIBAVUTIL_VERSION_INT < ((51<<16)+(12<<8)+0)
424 for ( i = 0; i < count; i++ )
426 const char *opt_name = mlt_properties_get_name( properties, i );
427 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
428 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
430 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
433 // If option not found, see if it was prefixed with a or v (-vb)
435 ( opt_name[0] == 'v' && ( flags & AV_OPT_FLAG_VIDEO_PARAM ) ) ||
436 ( opt_name[0] == 'a' && ( flags & AV_OPT_FLAG_AUDIO_PARAM ) ) ) )
437 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
438 opt = av_opt_find( obj, ++opt_name, NULL, flags, flags );
440 opt = av_find_opt( obj, ++opt_name, NULL, flags, flags );
442 // Apply option if found
444 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
445 av_opt_set( obj, opt_name, mlt_properties_get_value( properties, i), 0 );
447 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
452 static enum PixelFormat pick_pix_fmt( mlt_image_format img_fmt )
456 case mlt_image_rgb24:
457 return PIX_FMT_RGB24;
458 case mlt_image_rgb24a:
460 case mlt_image_yuv420p:
461 return PIX_FMT_YUV420P;
463 return PIX_FMT_YUYV422;
467 static int get_mlt_audio_format( int av_sample_fmt )
469 switch ( av_sample_fmt )
471 case AV_SAMPLE_FMT_U8:
473 case AV_SAMPLE_FMT_S32:
474 return mlt_audio_s32le;
475 case AV_SAMPLE_FMT_FLT:
476 return mlt_audio_f32le;
477 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
478 case AV_SAMPLE_FMT_U8P:
480 case AV_SAMPLE_FMT_S32P:
481 return mlt_audio_s32le;
482 case AV_SAMPLE_FMT_FLTP:
483 return mlt_audio_f32le;
486 return mlt_audio_s16;
490 static int pick_sample_fmt( mlt_properties properties, AVCodec *codec )
492 int sample_fmt = AV_SAMPLE_FMT_S16;
493 const char *format = mlt_properties_get( properties, "mlt_audio_format" );
494 const int *p = codec->sample_fmts;
496 // get default av_sample_fmt from mlt_audio_format
499 if ( !strcmp( format, "s32le" ) )
500 sample_fmt = AV_SAMPLE_FMT_S32;
501 else if ( !strcmp( format, "f32le" ) )
502 sample_fmt = AV_SAMPLE_FMT_FLT;
503 else if ( !strcmp( format, "u8" ) )
504 sample_fmt = AV_SAMPLE_FMT_U8;
505 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
506 else if ( !strcmp( format, "s32" ) )
507 sample_fmt = AV_SAMPLE_FMT_S32P;
508 else if ( !strcmp( format, "float" ) )
509 sample_fmt = AV_SAMPLE_FMT_FLTP;
512 // check if codec supports our mlt_audio_format
513 for ( ; *p != -1; p++ )
515 if ( *p == sample_fmt )
518 // no match - pick first one we support
519 for ( p = codec->sample_fmts; *p != -1; p++ )
523 case AV_SAMPLE_FMT_U8:
524 case AV_SAMPLE_FMT_S16:
525 case AV_SAMPLE_FMT_S32:
526 case AV_SAMPLE_FMT_FLT:
527 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
528 case AV_SAMPLE_FMT_U8P:
529 case AV_SAMPLE_FMT_S16P:
530 case AV_SAMPLE_FMT_S32P:
531 case AV_SAMPLE_FMT_FLTP:
538 mlt_log_error( properties, "audio codec sample_fmt not compatible" );
540 return AV_SAMPLE_FMT_NONE;
543 static uint8_t* interleaved_to_planar( int samples, int channels, uint8_t* audio, int bytes_per_sample )
545 uint8_t *buffer = mlt_pool_alloc( AUDIO_ENCODE_BUFFER_SIZE );
549 memset( buffer, 0, AUDIO_ENCODE_BUFFER_SIZE );
550 for ( c = 0; c < channels; c++ )
552 uint8_t *q = audio + c * bytes_per_sample;
556 memcpy( p, q, bytes_per_sample );
557 p += bytes_per_sample;
558 q += channels * bytes_per_sample;
564 /** Add an audio output stream
567 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec, int channels )
569 // Get the properties
570 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
572 // Create a new stream
573 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
574 AVStream *st = avformat_new_stream( oc, codec );
576 AVStream *st = av_new_stream( oc, oc->nb_streams );
579 // If created, then initialise from properties
582 AVCodecContext *c = st->codec;
584 // Establish defaults from AVOptions
585 #if LIBAVCODEC_VERSION_MAJOR >= 53
586 avcodec_get_context_defaults3( c, codec );
588 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
591 c->codec_id = codec->id;
592 c->codec_type = CODEC_TYPE_AUDIO;
593 c->sample_fmt = pick_sample_fmt( properties, codec );
595 #if 0 // disabled until some audio codecs are multi-threaded
596 // Setup multi-threading
597 int thread_count = mlt_properties_get_int( properties, "threads" );
598 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
599 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
600 if ( thread_count > 1 )
601 c->thread_count = thread_count;
604 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
605 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
607 // Allow the user to override the audio fourcc
608 if ( mlt_properties_get( properties, "atag" ) )
611 char *arg = mlt_properties_get( properties, "atag" );
612 int tag = strtol( arg, &tail, 0);
614 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
618 // Process properties as AVOptions
619 char *apre = mlt_properties_get( properties, "apre" );
622 mlt_properties p = mlt_properties_load( apre );
623 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
624 mlt_properties_close( p );
626 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
628 int audio_qscale = mlt_properties_get_int( properties, "aq" );
629 if ( audio_qscale > QSCALE_NONE )
631 c->flags |= CODEC_FLAG_QSCALE;
632 c->global_quality = FF_QP2LAMBDA * audio_qscale;
633 #if LIBAVFORMAT_VERSION_MAJOR < 53
634 st->quality = c->global_quality;
638 // Set parameters controlled by MLT
639 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
640 c->time_base = ( AVRational ){ 1, c->sample_rate };
641 c->channels = channels;
643 if ( mlt_properties_get( properties, "alang" ) != NULL )
644 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
645 av_dict_set( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
647 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
652 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
658 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
660 // We will return the audio input size from here
661 int audio_input_frame_size = 0;
664 AVCodecContext *c = st->codec;
669 codec = avcodec_find_encoder_by_name( codec_name );
671 codec = avcodec_find_encoder( c->codec_id );
673 // Process properties as AVOptions on the AVCodec
674 if ( codec && codec->priv_class )
676 char *apre = mlt_properties_get( properties, "apre" );
677 if ( !c->priv_data && codec->priv_data_size )
679 c->priv_data = av_mallocz( codec->priv_data_size );
680 *(const AVClass **) c->priv_data = codec->priv_class;
681 // av_opt_set_defaults( c );
685 mlt_properties p = mlt_properties_load( apre );
686 apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
687 mlt_properties_close( p );
689 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
692 // Continue if codec found and we can open it
693 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
694 if ( codec && avcodec_open2( c, codec, NULL ) >= 0 )
696 if ( codec && avcodec_open( c, codec ) >= 0 )
699 // ugly hack for PCM codecs (will be removed ASAP with new PCM
700 // support to compute the input frame size in samples
701 if ( c->frame_size <= 1 )
703 audio_input_frame_size = audio_outbuf_size / c->channels;
704 switch(st->codec->codec_id)
706 case AV_CODEC_ID_PCM_S16LE:
707 case AV_CODEC_ID_PCM_S16BE:
708 case AV_CODEC_ID_PCM_U16LE:
709 case AV_CODEC_ID_PCM_U16BE:
710 audio_input_frame_size >>= 1;
712 #if LIBAVCODEC_VERSION_INT >= ((54<<16)+(59<<8)+0)
713 case AV_CODEC_ID_PCM_S24LE:
714 case AV_CODEC_ID_PCM_S24BE:
715 case AV_CODEC_ID_PCM_U24LE:
716 case AV_CODEC_ID_PCM_U24BE:
717 audio_input_frame_size /= 3;
719 case AV_CODEC_ID_PCM_S32LE:
720 case AV_CODEC_ID_PCM_S32BE:
721 case AV_CODEC_ID_PCM_U32LE:
722 case AV_CODEC_ID_PCM_U32BE:
723 audio_input_frame_size >>= 2;
732 audio_input_frame_size = c->frame_size;
735 // Some formats want stream headers to be seperate (hmm)
736 if ( !strcmp( oc->oformat->name, "mp4" ) ||
737 !strcmp( oc->oformat->name, "mov" ) ||
738 !strcmp( oc->oformat->name, "3gp" ) )
739 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
743 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
744 audio_input_frame_size = 0;
747 return audio_input_frame_size;
750 static void close_audio( AVFormatContext *oc, AVStream *st )
752 if ( st && st->codec )
753 avcodec_close( st->codec );
756 /** Add a video output stream
759 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
761 // Get the properties
762 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
764 // Create a new stream
765 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
766 AVStream *st = avformat_new_stream( oc, codec );
768 AVStream *st = av_new_stream( oc, oc->nb_streams );
773 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
774 AVCodecContext *c = st->codec;
776 // Establish defaults from AVOptions
777 #if LIBAVCODEC_VERSION_MAJOR >= 53
778 avcodec_get_context_defaults3( c, codec );
780 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
783 c->codec_id = codec->id;
784 c->codec_type = CODEC_TYPE_VIDEO;
786 // Setup multi-threading
787 int thread_count = mlt_properties_get_int( properties, "threads" );
788 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
789 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
790 if ( thread_count > 1 )
791 #if LIBAVCODEC_VERSION_MAJOR >= 53
792 c->thread_count = thread_count;
794 avcodec_thread_init( c, thread_count );
797 // Process properties as AVOptions
798 char *vpre = mlt_properties_get( properties, "vpre" );
801 mlt_properties p = mlt_properties_load( vpre );
803 if ( mlt_properties_count( p ) < 1 )
805 AVCodec *codec = avcodec_find_encoder( c->codec_id );
808 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
809 strcpy( path, AVDATADIR );
810 strcat( path, codec->name );
812 strcat( path, vpre );
813 strcat( path, ".ffpreset" );
815 mlt_properties_close( p );
816 p = mlt_properties_load( path );
817 if ( mlt_properties_count( p ) > 0 )
818 mlt_properties_debug( p, path, stderr );
824 mlt_properties_debug( p, vpre, stderr );
827 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
828 mlt_properties_close( p );
830 int colorspace = mlt_properties_get_int( properties, "colorspace" );
831 mlt_properties_set( properties, "colorspace", NULL );
832 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
833 mlt_properties_set_int( properties, "colorspace", colorspace );
835 // Set options controlled by MLT
836 c->width = mlt_properties_get_int( properties, "width" );
837 c->height = mlt_properties_get_int( properties, "height" );
838 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
839 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
840 if ( st->time_base.den == 0 )
841 st->time_base = c->time_base;
842 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
844 switch ( colorspace )
847 c->colorspace = AVCOL_SPC_SMPTE170M;
850 c->colorspace = AVCOL_SPC_SMPTE240M;
853 c->colorspace = AVCOL_SPC_BT470BG;
856 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
859 c->colorspace = AVCOL_SPC_BT709;
863 if ( mlt_properties_get( properties, "aspect" ) )
865 // "-aspect" on ffmpeg command line is display aspect ratio
866 double ar = mlt_properties_get_double( properties, "aspect" );
867 c->sample_aspect_ratio = av_d2q( ar * c->height / c->width, 255 );
871 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
872 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
874 st->sample_aspect_ratio = c->sample_aspect_ratio;
876 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
878 c->flags |= CODEC_FLAG_QSCALE;
879 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
880 #if LIBAVFORMAT_VERSION_MAJOR < 53
881 st->quality = c->global_quality;
885 // Allow the user to override the video fourcc
886 if ( mlt_properties_get( properties, "vtag" ) )
889 const char *arg = mlt_properties_get( properties, "vtag" );
890 int tag = strtol( arg, &tail, 0);
892 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
896 // Some formats want stream headers to be seperate
897 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
898 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
900 // Translate these standard mlt consumer properties to ffmpeg
901 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
902 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
904 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
905 c->flags |= CODEC_FLAG_INTERLACED_DCT;
906 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
907 c->flags |= CODEC_FLAG_INTERLACED_ME;
910 // parse the ratecontrol override string
912 char *rc_override = mlt_properties_get( properties, "rc_override" );
913 for ( i = 0; rc_override; i++ )
916 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
918 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
919 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
920 c->rc_override[i].start_frame = start;
921 c->rc_override[i].end_frame = end;
924 c->rc_override[i].qscale = q;
925 c->rc_override[i].quality_factor = 1.0;
929 c->rc_override[i].qscale = 0;
930 c->rc_override[i].quality_factor = -q / 100.0;
932 rc_override = strchr( rc_override, '/' );
936 c->rc_override_count = i;
937 if ( !c->rc_initial_buffer_occupancy )
938 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
939 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
942 i = mlt_properties_get_int( properties, "pass" );
944 c->flags |= CODEC_FLAG_PASS1;
946 c->flags |= CODEC_FLAG_PASS2;
947 if ( codec->id != AV_CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
949 char logfilename[1024];
954 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
955 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
956 if ( c->flags & CODEC_FLAG_PASS1 )
958 f = fopen( logfilename, "w" );
960 perror( logfilename );
962 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
966 /* read the log file */
967 f = fopen( logfilename, "r" );
974 mlt_properties_set( properties, "_logfilename", logfilename );
975 fseek( f, 0, SEEK_END );
977 fseek( f, 0, SEEK_SET );
978 logbuffer = av_malloc( size + 1 );
980 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
985 size = fread( logbuffer, 1, size, f );
986 logbuffer[size] = '\0';
987 c->stats_in = logbuffer;
997 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
1003 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
1006 AVFrame *picture = avcodec_alloc_frame();
1008 // Determine size of the
1009 int size = avpicture_get_size(pix_fmt, width, height);
1011 // Allocate the picture buf
1012 uint8_t *picture_buf = av_malloc(size);
1014 // If we have both, then fill the image
1015 if ( picture != NULL && picture_buf != NULL )
1017 // Fill the frame with the allocated buffer
1018 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
1022 // Something failed - clean up what we can
1024 av_free( picture_buf );
1031 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
1034 AVCodecContext *video_enc = st->codec;
1036 // find the video encoder
1039 codec = avcodec_find_encoder_by_name( codec_name );
1041 codec = avcodec_find_encoder( video_enc->codec_id );
1043 // Process properties as AVOptions on the AVCodec
1044 if ( codec && codec->priv_class )
1046 char *vpre = mlt_properties_get( properties, "vpre" );
1047 if ( !video_enc->priv_data && codec->priv_data_size )
1049 video_enc->priv_data = av_mallocz( codec->priv_data_size );
1050 *(const AVClass **) video_enc->priv_data = codec->priv_class;
1051 // av_opt_set_defaults( video_enc );
1055 mlt_properties p = mlt_properties_load( vpre );
1056 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1057 mlt_properties_close( p );
1059 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1062 if( codec && codec->pix_fmts )
1064 const enum PixelFormat *p = codec->pix_fmts;
1065 for( ; *p!=-1; p++ )
1067 if( *p == video_enc->pix_fmt )
1071 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1074 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1075 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1077 int result = codec && avcodec_open( video_enc, codec ) >= 0;
1083 void close_video(AVFormatContext *oc, AVStream *st)
1085 if ( st && st->codec )
1087 av_freep( &st->codec->stats_in );
1088 avcodec_close(st->codec);
1092 static inline long time_difference( struct timeval *time1 )
1094 struct timeval time2;
1095 gettimeofday( &time2, NULL );
1096 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1099 static int mlt_write(void *h, uint8_t *buf, int size)
1101 mlt_properties properties = (mlt_properties) h;
1102 mlt_events_fire( properties, "avformat-write", buf, &size, NULL );
1106 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1108 int *p_size = (int*) args[1];
1109 listener( owner, service, (uint8_t*) args[0], *p_size );
1112 /** The main thread - the argument is simply the consumer.
1115 static void *consumer_thread( void *arg )
1117 // Map the argument to the object
1118 mlt_consumer consumer = arg;
1120 // Get the properties
1121 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1123 // Get the terminate on pause property
1124 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1127 // Determine if feed is slow (for realtime stuff)
1128 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1131 struct timeval ante;
1133 // Get the frame rate
1134 double fps = mlt_properties_get_double( properties, "fps" );
1136 // Get width and height
1137 int width = mlt_properties_get_int( properties, "width" );
1138 int height = mlt_properties_get_int( properties, "height" );
1139 int img_width = width;
1140 int img_height = height;
1142 // Get default audio properties
1143 int channels = mlt_properties_get_int( properties, "channels" );
1144 int total_channels = channels;
1145 int frequency = mlt_properties_get_int( properties, "frequency" );
1149 // AVFormat audio buffer and frame size
1150 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1151 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1152 int audio_input_nb_samples = 0;
1154 // AVFormat video buffer and frame count
1155 int frame_count = 0;
1156 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1157 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1159 // Used for the frame properties
1160 mlt_frame frame = NULL;
1161 mlt_properties frame_properties = NULL;
1164 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1165 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1167 // For receiving images from an mlt_frame
1169 mlt_image_format img_fmt = mlt_image_yuv422;
1170 // Get the image format to use for rendering threads
1171 const char* img_fmt_name = mlt_properties_get( properties, "mlt_image_format" );
1174 if ( !strcmp( img_fmt_name, "rgb24" ) )
1175 img_fmt = mlt_image_rgb24;
1176 else if ( !strcmp( img_fmt_name, "rgb24a" ) )
1177 img_fmt = mlt_image_rgb24a;
1178 else if ( !strcmp( img_fmt_name, "yuv420p" ) )
1179 img_fmt = mlt_image_yuv420p;
1181 else if ( mlt_properties_get( properties, "pix_fmt" ) )
1183 img_fmt_name = mlt_properties_get( properties, "pix_fmt" );
1184 if ( !strcmp( img_fmt_name, "rgba" ) ||
1185 !strcmp( img_fmt_name, "argb" ) ||
1186 !strcmp( img_fmt_name, "bgra" ) )
1187 img_fmt = mlt_image_rgb24a;
1190 // Need two av pictures for converting
1191 AVFrame *converted_avframe = NULL;
1192 AVFrame *audio_avframe = NULL;
1193 AVFrame *video_avframe = alloc_picture( pick_pix_fmt( img_fmt ), width, height );
1195 // For receiving audio samples back from the fifo
1196 uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1197 uint8_t *audio_buf_2 = NULL;
1200 // Allocate the context
1201 AVFormatContext *oc = NULL;
1204 AVStream *video_st = NULL;
1205 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1208 double audio_pts = 0;
1209 double video_pts = 0;
1211 // Frames dispatched
1212 long int frames = 0;
1213 long int total_time = 0;
1215 // Determine the format
1216 AVOutputFormat *fmt = NULL;
1217 const char *filename = mlt_properties_get( properties, "target" );
1218 char *format = mlt_properties_get( properties, "f" );
1219 char *vcodec = mlt_properties_get( properties, "vcodec" );
1220 char *acodec = mlt_properties_get( properties, "acodec" );
1221 AVCodec *audio_codec = NULL;
1222 AVCodec *video_codec = NULL;
1224 // Used to store and override codec ids
1230 mlt_properties frame_meta_properties = mlt_properties_new();
1231 int error_count = 0;
1232 int64_t synth_audio_pts = 0;
1234 // Initialize audio_st
1235 int i = MAX_AUDIO_STREAMS;
1239 // Check for user selected format first
1240 if ( format != NULL )
1241 fmt = av_guess_format( format, NULL, NULL );
1243 // Otherwise check on the filename
1244 if ( fmt == NULL && filename != NULL )
1245 fmt = av_guess_format( NULL, filename, NULL );
1247 // Otherwise default to mpeg
1249 fmt = av_guess_format( "mpeg", NULL, NULL );
1251 // We need a filename - default to stdout?
1252 if ( filename == NULL || !strcmp( filename, "" ) )
1255 #if defined(FFUDIV) && LIBAVUTIL_VERSION_INT >= ((53<<16)+(2<<8)+0)
1256 avformat_alloc_output_context2( &oc, fmt, format, filename );
1258 oc = avformat_alloc_context( );
1260 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1262 if ( oc->oformat && oc->oformat->priv_class && !oc->priv_data && oc->oformat->priv_data_size ) {
1263 oc->priv_data = av_mallocz( oc->oformat->priv_data_size );
1264 if ( oc->priv_data ) {
1265 *(const AVClass**)oc->priv_data = oc->oformat->priv_class;
1266 av_opt_set_defaults( oc->priv_data );
1271 // Get the codec ids selected
1272 audio_codec_id = fmt->audio_codec;
1273 video_codec_id = fmt->video_codec;
1275 // Check for audio codec overides
1276 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1277 audio_codec_id = AV_CODEC_ID_NONE;
1280 audio_codec = avcodec_find_encoder_by_name( acodec );
1283 audio_codec_id = audio_codec->id;
1284 if ( audio_codec_id == AV_CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1286 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1287 acodec = mlt_properties_get( properties, "_acodec" );
1288 audio_codec = avcodec_find_encoder_by_name( acodec );
1290 else if ( !strcmp( acodec, "aac" ) || !strcmp( acodec, "vorbis" ) )
1292 mlt_properties_set( properties, "astrict", "experimental" );
1297 audio_codec_id = AV_CODEC_ID_NONE;
1298 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1303 audio_codec = avcodec_find_encoder( audio_codec_id );
1306 // Check for video codec overides
1307 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1308 video_codec_id = AV_CODEC_ID_NONE;
1311 video_codec = avcodec_find_encoder_by_name( vcodec );
1314 video_codec_id = video_codec->id;
1318 video_codec_id = AV_CODEC_ID_NONE;
1319 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1324 video_codec = avcodec_find_encoder( video_codec_id );
1328 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1330 char *name = mlt_properties_get_name( properties, i );
1331 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1333 char *key = strdup( name + 10 );
1334 char *markup = strrchr( key, '.' );
1335 if ( markup && !strcmp( markup, ".markup") )
1338 if ( !strstr( key, ".stream." ) )
1339 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1340 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1342 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1349 // Get a frame now, so we can set some AVOptions from properties.
1350 frame = mlt_consumer_rt_frame( consumer );
1352 // Set the timecode from the MLT metadata if available.
1355 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1356 if ( timecode && strcmp( timecode, "" ) )
1358 mlt_properties_set( properties, "timecode", timecode );
1359 if ( strchr( timecode, ';' ) )
1360 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1364 // Add audio and video streams
1365 if ( video_codec_id != AV_CODEC_ID_NONE )
1366 video_st = add_video_stream( consumer, oc, video_codec );
1367 if ( audio_codec_id != AV_CODEC_ID_NONE )
1373 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1375 sprintf( key, "channels.%d", i );
1376 int j = mlt_properties_get_int( properties, key );
1380 total_channels += j;
1381 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1387 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1388 total_channels = channels;
1391 mlt_properties_set_int( properties, "channels", total_channels );
1393 // Audio format is determined when adding the audio stream
1394 mlt_audio_format aud_fmt = mlt_audio_none;
1396 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1397 int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1398 sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1400 // Set the parameters (even though we have none...)
1401 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1402 if ( av_set_parameters(oc, NULL) >= 0 )
1405 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1406 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1407 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1409 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1411 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1413 // Process properties as AVOptions
1414 char *fpre = mlt_properties_get( properties, "fpre" );
1417 mlt_properties p = mlt_properties_load( fpre );
1418 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1419 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1420 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1421 mlt_properties_close( p );
1423 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1424 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1425 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1427 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1429 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1431 audio_input_nb_samples = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1432 acodec? acodec : NULL );
1433 if ( !audio_input_nb_samples )
1435 // Remove the audio stream from the output context
1437 for ( j = 0; j < oc->nb_streams; j++ )
1439 if ( oc->streams[j] == audio_st[i] )
1440 av_freep( &oc->streams[j] );
1447 // Setup custom I/O if redirecting
1448 if ( mlt_properties_get_int( properties, "redirect" ) )
1450 int buffer_size = 32768;
1451 unsigned char *buffer = av_malloc( buffer_size );
1452 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1453 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1455 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1460 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1461 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1463 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1464 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1465 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1470 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1473 // Open the output file, if needed
1474 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1476 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1477 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1479 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1482 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1483 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1484 goto on_fatal_error;
1488 // Write the stream header.
1489 if ( mlt_properties_get_int( properties, "running" ) )
1490 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1491 if ( avformat_write_header( oc, NULL ) < 0 )
1493 if ( av_write_header( oc ) < 0 )
1496 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not write header '%s'\n", filename );
1497 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1498 goto on_fatal_error;
1501 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1504 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1505 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1506 goto on_fatal_error;
1510 // Last check - need at least one stream
1511 if ( !audio_st[0] && !video_st )
1513 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1514 goto on_fatal_error;
1519 converted_avframe = alloc_picture( video_st->codec->pix_fmt, width, height );
1521 #if LIBAVCODEC_VERSION_MAJOR >= 54
1522 // Allocate audio AVFrame
1525 audio_avframe = avcodec_alloc_frame();
1526 if ( audio_avframe ) {
1527 AVCodecContext *c = audio_st[0]->codec;
1528 audio_avframe->format = c->sample_fmt;
1529 audio_avframe->nb_samples = audio_input_nb_samples;
1530 audio_avframe->channel_layout = c->channel_layout;
1532 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to allocate audio AVFrame\n" );
1533 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1534 goto on_fatal_error;
1539 // Get the starting time (can ignore the times above)
1540 gettimeofday( &ante, NULL );
1542 // Loop while running
1543 while( mlt_properties_get_int( properties, "running" ) &&
1544 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1547 frame = mlt_consumer_rt_frame( consumer );
1549 // Check that we have a frame to work with
1550 if ( frame != NULL )
1552 // Increment frames dispatched
1555 // Default audio args
1556 frame_properties = MLT_FRAME_PROPERTIES( frame );
1558 // Check for the terminated condition
1559 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1561 // Get audio and append to the fifo
1562 if ( !terminated && audio_st[0] )
1564 samples = mlt_sample_calculator( fps, frequency, count ++ );
1565 channels = total_channels;
1566 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1568 // Save the audio channel remap properties for later
1569 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1571 // Create the fifo if we don't have one
1574 fifo = sample_fifo_init( frequency, channels );
1575 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1579 // Silence if not normal forward speed
1580 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1581 memset( pcm, 0, samples * channels * sample_bytes );
1583 // Append the samples
1584 sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1585 total_time += ( samples * 1000000 ) / frequency;
1588 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1592 if ( !terminated && video_st )
1593 mlt_deque_push_back( queue, frame );
1595 mlt_frame_close( frame );
1599 // While we have stuff to process, process...
1602 // Write interleaved audio and video frames
1603 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1606 if ( ( video_st && terminated ) || ( channels * audio_input_nb_samples ) < sample_fifo_used( fifo ) / sample_bytes )
1608 int j = 0; // channel offset into interleaved source buffer
1609 int n = FFMIN( FFMIN( channels * audio_input_nb_samples, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1611 // Get the audio samples
1614 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1616 else if ( audio_codec_id == AV_CODEC_ID_VORBIS && terminated )
1618 // This prevents an infinite loop when some versions of vorbis do not
1619 // increment pts when encoding silence.
1620 audio_pts = video_pts;
1625 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1627 samples = n / channels;
1629 // For each output stream
1630 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1632 AVStream *stream = audio_st[i];
1633 AVCodecContext *codec = stream->codec;
1636 av_init_packet( &pkt );
1637 pkt.data = audio_outbuf;
1638 pkt.size = audio_outbuf_size;
1640 // Optimized for single track and no channel remap
1641 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1643 void* p = audio_buf_1;
1644 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1645 if ( codec->sample_fmt == AV_SAMPLE_FMT_FLTP )
1646 p = interleaved_to_planar( samples, channels, p, sizeof( float ) );
1647 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S16P )
1648 p = interleaved_to_planar( samples, channels, p, sizeof( int16_t ) );
1649 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S32P )
1650 p = interleaved_to_planar( samples, channels, p, sizeof( int32_t ) );
1651 else if ( codec->sample_fmt == AV_SAMPLE_FMT_U8P )
1652 p = interleaved_to_planar( samples, channels, p, sizeof( uint8_t ) );
1654 #if LIBAVCODEC_VERSION_MAJOR >= 54
1655 audio_avframe->nb_samples = FFMAX( samples, audio_input_nb_samples );
1656 #if LIBAVCODEC_VERSION_MAJOR >= 55
1657 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
1658 audio_avframe->pts = synth_audio_pts;
1659 synth_audio_pts += audio_avframe->nb_samples;
1661 avcodec_fill_audio_frame( audio_avframe, codec->channels, codec->sample_fmt,
1662 (const uint8_t*) p, AUDIO_ENCODE_BUFFER_SIZE, 0 );
1664 int ret = avcodec_encode_audio2( codec, &pkt, audio_avframe, &got_packet );
1667 else if ( !got_packet )
1670 codec->frame_size = FFMAX( samples, audio_input_nb_samples );
1671 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, p );
1672 pkt.pts = codec->coded_frame? codec->coded_frame->pts : AV_NOPTS_VALUE;
1673 pkt.flags |= PKT_FLAG_KEY;
1676 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1677 if ( p != audio_buf_1 )
1678 mlt_pool_release( p );
1683 // Extract the audio channels according to channel mapping
1684 int dest_offset = 0; // channel offset into interleaved dest buffer
1686 // Get the number of channels for this stream
1687 sprintf( key, "channels.%d", i );
1688 int current_channels = mlt_properties_get_int( properties, key );
1690 // Clear the destination audio buffer.
1692 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1694 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1696 // For each output channel
1697 while ( dest_offset < current_channels && j < total_channels )
1699 int map_start = -1, map_channels = 0;
1700 int source_offset = 0;
1703 // Look for a mapping that starts at j
1704 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1706 sprintf( key, "%d.channels", k );
1707 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1708 sprintf( key, "%d.start", k );
1709 if ( mlt_properties_get( frame_meta_properties, key ) )
1710 map_start = mlt_properties_get_int( frame_meta_properties, key );
1711 if ( map_start != j )
1712 source_offset += map_channels;
1716 if ( map_start != j )
1718 map_channels = current_channels;
1722 // Copy samples if source offset valid
1723 if ( source_offset < channels )
1725 // Interleave the audio buffer with the # channels for this stream/mapping.
1726 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1728 void *src = audio_buf_1 + source_offset * sample_bytes;
1729 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1730 int s = samples + 1;
1733 memcpy( dest, src, sample_bytes );
1734 dest += current_channels * sample_bytes;
1735 src += channels * sample_bytes;
1739 // Otherwise silence
1742 j += current_channels;
1743 dest_offset += current_channels;
1746 #if LIBAVCODEC_VERSION_MAJOR >= 54
1747 audio_avframe->nb_samples = FFMAX( samples, audio_input_nb_samples );
1748 #if LIBAVCODEC_VERSION_MAJOR >= 55
1749 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
1750 audio_avframe->pts = synth_audio_pts;
1751 synth_audio_pts += audio_avframe->nb_samples;
1753 avcodec_fill_audio_frame( audio_avframe, codec->channels, codec->sample_fmt,
1754 (const uint8_t*) audio_buf_2, AUDIO_ENCODE_BUFFER_SIZE, 0 );
1756 int ret = avcodec_encode_audio2( codec, &pkt, audio_avframe, &got_packet );
1759 else if ( !got_packet )
1762 codec->frame_size = FFMAX( samples, audio_input_nb_samples );
1763 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1764 pkt.pts = codec->coded_frame? codec->coded_frame->pts : AV_NOPTS_VALUE;
1765 pkt.flags |= PKT_FLAG_KEY;
1771 // Write the compressed frame in the media file
1772 if ( pkt.pts != AV_NOPTS_VALUE )
1773 pkt.pts = av_rescale_q( pkt.pts, codec->time_base, stream->time_base );
1774 #if LIBAVCODEC_VERSION_MAJOR >= 55
1775 if ( pkt.dts != AV_NOPTS_VALUE )
1776 pkt.dts = av_rescale_q( pkt.dts, codec->time_base, stream->time_base );
1777 if ( pkt.duration > 0 )
1778 pkt.duration = av_rescale_q( pkt.duration, codec->time_base, stream->time_base );
1780 pkt.stream_index = stream->index;
1781 if ( av_interleaved_write_frame( oc, &pkt ) )
1783 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1784 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1785 goto on_fatal_error;
1788 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame_size %d stream pts %"PRId64"\n",
1789 stream->index, pkt.pts, codec->frame_size, stream->pts.val );
1791 else if ( pkt.size < 0 )
1793 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with audio encode %d\n", frame_count );
1794 if ( ++error_count > 2 )
1795 goto on_fatal_error;
1800 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1809 else if ( video_st )
1812 if ( mlt_deque_count( queue ) )
1815 AVCodecContext *c = video_st->codec;
1817 frame = mlt_deque_pop_front( queue );
1818 frame_properties = MLT_FRAME_PROPERTIES( frame );
1820 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1825 int stride = mlt_image_format_size( img_fmt, width, 0, NULL );
1827 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1830 // Convert the mlt frame to an AVPicture
1831 if ( img_fmt == mlt_image_yuv420p )
1833 memcpy( video_avframe->data[0], q, video_avframe->linesize[0] );
1835 memcpy( video_avframe->data[1], q, video_avframe->linesize[1] );
1837 memcpy( video_avframe->data[2], q, video_avframe->linesize[2] );
1839 else for ( i = 0; i < height; i ++ )
1841 p = video_avframe->data[0] + i * video_avframe->linesize[0];
1842 memcpy( p, q, stride );
1846 // Do the colour space conversion
1847 int flags = SWS_BICUBIC;
1849 flags |= SWS_CPU_CAPS_MMX;
1852 flags |= SWS_CPU_CAPS_MMX2;
1854 struct SwsContext *context = sws_getContext( width, height, pick_pix_fmt( img_fmt ),
1855 width, height, c->pix_fmt, flags, NULL, NULL, NULL);
1856 sws_scale( context, (const uint8_t* const*) video_avframe->data, video_avframe->linesize, 0, height,
1857 converted_avframe->data, converted_avframe->linesize);
1858 sws_freeContext( context );
1860 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1862 // Apply the alpha if applicable
1863 if ( !mlt_properties_get( properties, "mlt_image_format" ) ||
1864 strcmp( mlt_properties_get( properties, "mlt_image_format" ), "rgb24a" ) )
1865 if ( c->pix_fmt == PIX_FMT_RGBA ||
1866 c->pix_fmt == PIX_FMT_ARGB ||
1867 c->pix_fmt == PIX_FMT_BGRA )
1869 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1872 for ( i = 0; i < height; i ++ )
1874 n = ( width + 7 ) / 8;
1875 p = converted_avframe->data[ 0 ] + i * converted_avframe->linesize[ 0 ] + 3;
1879 case 0: do { *p = *alpha++; p += 4;
1880 case 7: *p = *alpha++; p += 4;
1881 case 6: *p = *alpha++; p += 4;
1882 case 5: *p = *alpha++; p += 4;
1883 case 4: *p = *alpha++; p += 4;
1884 case 3: *p = *alpha++; p += 4;
1885 case 2: *p = *alpha++; p += 4;
1886 case 1: *p = *alpha++; p += 4;
1894 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1896 // raw video case. The API will change slightly in the near future for that
1898 av_init_packet(&pkt);
1900 // Set frame interlace hints
1901 c->coded_frame->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1902 c->coded_frame->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1903 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(61<<8)+100)
1904 if ( mlt_properties_get_int( frame_properties, "progressive" ) )
1905 c->field_order = AV_FIELD_PROGRESSIVE;
1907 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TT : AV_FIELD_BB;
1909 pkt.flags |= PKT_FLAG_KEY;
1910 pkt.stream_index = video_st->index;
1911 pkt.data = (uint8_t *)converted_avframe;
1912 pkt.size = sizeof(AVPicture);
1914 ret = av_write_frame(oc, &pkt);
1915 video_pts += c->frame_size;
1920 av_init_packet( &pkt );
1921 if ( c->codec->id == AV_CODEC_ID_RAWVIDEO ) {
1925 pkt.data = video_outbuf;
1926 pkt.size = video_outbuf_size;
1930 converted_avframe->quality = c->global_quality;
1931 converted_avframe->pts = frame_count;
1933 // Set frame interlace hints
1934 converted_avframe->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1935 converted_avframe->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1936 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(61<<8)+100)
1937 if ( mlt_properties_get_int( frame_properties, "progressive" ) )
1938 c->field_order = AV_FIELD_PROGRESSIVE;
1939 else if ( c->codec_id == AV_CODEC_ID_MJPEG )
1940 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TT : AV_FIELD_BB;
1942 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TB : AV_FIELD_BT;
1946 #if LIBAVCODEC_VERSION_MAJOR >= 55
1948 ret = avcodec_encode_video2( c, &pkt, converted_avframe, &got_packet );
1951 else if ( !got_packet )
1954 pkt.size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, converted_avframe );
1955 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
1956 if ( c->coded_frame && c->coded_frame->key_frame )
1957 pkt.flags |= PKT_FLAG_KEY;
1960 // If zero size, it means the image was buffered
1963 if ( pkt.pts != AV_NOPTS_VALUE )
1964 pkt.pts = av_rescale_q( pkt.pts, c->time_base, video_st->time_base );
1965 #if LIBAVCODEC_VERSION_MAJOR >= 55
1966 if ( pkt.dts != AV_NOPTS_VALUE )
1967 pkt.dts = av_rescale_q( pkt.dts, c->time_base, video_st->time_base );
1969 pkt.stream_index = video_st->index;
1971 // write the compressed frame in the media file
1972 ret = av_interleaved_write_frame(oc, &pkt);
1973 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1974 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1976 // Dual pass logging
1977 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1978 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1982 else if ( pkt.size < 0 )
1984 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1985 if ( ++error_count > 2 )
1986 goto on_fatal_error;
1993 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1994 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1995 goto on_fatal_error;
1997 mlt_frame_close( frame );
2006 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
2008 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
2009 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
2012 if ( real_time_output == 1 && frames % 2 == 0 )
2014 long passed = time_difference( &ante );
2017 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
2020 if ( passed < total_time )
2022 long total = ( total_time - passed );
2023 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
2024 nanosleep( &t, NULL );
2029 // Flush the encoder buffers
2030 if ( real_time_output <= 0 )
2033 // TODO: flush all audio streams
2034 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
2036 AVCodecContext *c = audio_st[0]->codec;
2038 av_init_packet( &pkt );
2039 pkt.data = audio_outbuf;
2042 if ( fifo && sample_fifo_used( fifo ) > 0 )
2044 // Drain the MLT FIFO
2045 int samples = FFMIN( FFMIN( channels * audio_input_nb_samples, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
2046 sample_fifo_fetch( fifo, audio_buf_1, samples * sample_bytes );
2047 void* p = audio_buf_1;
2048 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2049 if ( c->sample_fmt == AV_SAMPLE_FMT_FLTP )
2050 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( float ) );
2051 else if ( c->sample_fmt == AV_SAMPLE_FMT_S16P )
2052 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( int16_t ) );
2053 else if ( c->sample_fmt == AV_SAMPLE_FMT_S32P )
2054 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( int32_t ) );
2055 else if ( c->sample_fmt == AV_SAMPLE_FMT_U8P )
2056 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( uint8_t ) );
2058 #if LIBAVCODEC_VERSION_MAJOR >= 54
2059 pkt.size = audio_outbuf_size;
2060 audio_avframe->nb_samples = FFMAX( samples / channels, audio_input_nb_samples );
2061 #if LIBAVCODEC_VERSION_MAJOR >= 55
2062 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
2063 audio_avframe->pts = synth_audio_pts;
2064 synth_audio_pts += audio_avframe->nb_samples;
2066 avcodec_fill_audio_frame( audio_avframe, c->channels, c->sample_fmt,
2067 (const uint8_t*) p, AUDIO_ENCODE_BUFFER_SIZE, 0 );
2069 int ret = avcodec_encode_audio2( c, &pkt, audio_avframe, &got_packet );
2072 else if ( !got_packet )
2075 c->frame_size = FFMAX( samples / channels, audio_input_nb_samples );
2076 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, p );
2078 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2079 if ( p != audio_buf_1 )
2080 mlt_pool_release( p );
2082 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
2087 if ( pkt.size <= 0 ) {
2088 #if LIBAVCODEC_VERSION_MAJOR >= 54
2089 pkt.size = audio_outbuf_size;
2091 int ret = avcodec_encode_audio2( c, &pkt, NULL, &got_packet );
2094 else if ( !got_packet )
2097 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
2098 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
2099 pkt.flags |= PKT_FLAG_KEY;
2102 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
2103 if ( pkt.size <= 0 )
2107 // Write the compressed frame in the media file
2108 if ( pkt.pts != AV_NOPTS_VALUE )
2109 pkt.pts = av_rescale_q( pkt.pts, c->time_base, audio_st[0]->time_base );
2110 #if LIBAVCODEC_VERSION_MAJOR >= 55
2111 if ( pkt.dts != AV_NOPTS_VALUE )
2112 pkt.dts = av_rescale_q( pkt.dts, c->time_base, audio_st[0]->time_base );
2113 if ( pkt.duration > 0 )
2114 pkt.duration = av_rescale_q( pkt.duration, c->time_base, audio_st[0]->time_base );
2116 pkt.stream_index = audio_st[0]->index;
2117 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
2119 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
2125 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
2127 AVCodecContext *c = video_st->codec;
2129 av_init_packet( &pkt );
2130 if ( c->codec->id == AV_CODEC_ID_RAWVIDEO ) {
2134 pkt.data = video_outbuf;
2135 pkt.size = video_outbuf_size;
2139 #if LIBAVCODEC_VERSION_MAJOR >= 55
2141 int ret = avcodec_encode_video2( c, &pkt, NULL, &got_packet );
2144 else if ( !got_packet )
2147 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
2148 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
2149 if( c->coded_frame && c->coded_frame->key_frame )
2150 pkt.flags |= PKT_FLAG_KEY;
2152 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
2153 if ( pkt.size <= 0 )
2156 if ( pkt.pts != AV_NOPTS_VALUE )
2157 pkt.pts = av_rescale_q( pkt.pts, c->time_base, video_st->time_base );
2158 #if LIBAVCODEC_VERSION_MAJOR >= 55
2159 if ( pkt.dts != AV_NOPTS_VALUE )
2160 pkt.dts = av_rescale_q( pkt.dts, c->time_base, video_st->time_base );
2162 pkt.stream_index = video_st->index;
2164 // write the compressed frame in the media file
2165 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
2167 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
2168 mlt_events_fire( properties, "consumer-fatal-error", NULL );
2169 goto on_fatal_error;
2171 // Dual pass logging
2172 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
2173 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
2180 mlt_frame_close( frame );
2182 // Write the trailer, if any
2184 av_write_trailer( oc );
2188 close_video(oc, video_st);
2189 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
2190 close_audio( oc, audio_st[i] );
2193 for ( i = 0; i < oc->nb_streams; i++ )
2194 av_freep( &oc->streams[i] );
2196 // Close the output file
2197 if ( !( fmt->flags & AVFMT_NOFILE ) &&
2198 !mlt_properties_get_int( properties, "redirect" ) )
2200 #if LIBAVFORMAT_VERSION_MAJOR >= 53
2201 if ( oc->pb ) avio_close( oc->pb );
2203 if ( oc->pb ) url_fclose( oc->pb );
2207 // Clean up input and output frames
2208 if ( converted_avframe )
2209 av_free( converted_avframe->data[0] );
2210 av_free( converted_avframe );
2211 av_free( video_avframe->data[0] );
2212 av_free( video_avframe );
2213 av_free( video_outbuf );
2214 av_free( audio_avframe );
2215 av_free( audio_buf_1 );
2216 av_free( audio_buf_2 );
2221 // Just in case we terminated on pause
2222 mlt_consumer_stopped( consumer );
2223 mlt_properties_close( frame_meta_properties );
2225 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
2227 // Remove the dual pass log file
2228 if ( mlt_properties_get( properties, "_logfilename" ) )
2229 remove( mlt_properties_get( properties, "_logfilename" ) );
2231 // Remove the x264 dual pass logs
2232 char *cwd = getcwd( NULL, 0 );
2233 const char *file = "x264_2pass.log";
2234 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2235 sprintf( full, "%s/%s", cwd, file );
2238 file = "x264_2pass.log.temp";
2239 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2240 sprintf( full, "%s/%s", cwd, file );
2243 file = "x264_2pass.log.mbtree";
2244 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2245 sprintf( full, "%s/%s", cwd, file );
2249 remove( "x264_2pass.log.temp" );
2251 // Recent versions of libavcodec/x264 support passlogfile and need cleanup if specified.
2252 if ( !mlt_properties_get( properties, "_logfilename" ) &&
2253 mlt_properties_get( properties, "passlogfile" ) )
2255 file = mlt_properties_get( properties, "passlogfile" );
2257 full = malloc( strlen( file ) + strlen( ".mbtree" ) + 1 );
2258 sprintf( full, "%s.mbtree", file );
2264 while ( ( frame = mlt_deque_pop_back( queue ) ) )
2265 mlt_frame_close( frame );
2270 /** Close the consumer.
2273 static void consumer_close( mlt_consumer consumer )
2275 // Stop the consumer
2276 mlt_consumer_stop( consumer );
2279 mlt_consumer_close( consumer );