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;
718 audio_input_frame_size = c->frame_size;
721 // Some formats want stream headers to be seperate (hmm)
722 if ( !strcmp( oc->oformat->name, "mp4" ) ||
723 !strcmp( oc->oformat->name, "mov" ) ||
724 !strcmp( oc->oformat->name, "3gp" ) )
725 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
729 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
730 audio_input_frame_size = 0;
733 return audio_input_frame_size;
736 static void close_audio( AVFormatContext *oc, AVStream *st )
738 if ( st && st->codec )
739 avcodec_close( st->codec );
742 /** Add a video output stream
745 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
747 // Get the properties
748 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
750 // Create a new stream
751 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
752 AVStream *st = avformat_new_stream( oc, codec );
754 AVStream *st = av_new_stream( oc, oc->nb_streams );
759 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
760 AVCodecContext *c = st->codec;
762 // Establish defaults from AVOptions
763 #if LIBAVCODEC_VERSION_MAJOR >= 53
764 avcodec_get_context_defaults3( c, codec );
766 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
769 c->codec_id = codec->id;
770 c->codec_type = CODEC_TYPE_VIDEO;
772 // Setup multi-threading
773 int thread_count = mlt_properties_get_int( properties, "threads" );
774 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
775 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
776 if ( thread_count > 1 )
777 #if LIBAVCODEC_VERSION_MAJOR >= 53
778 c->thread_count = thread_count;
780 avcodec_thread_init( c, thread_count );
783 // Process properties as AVOptions
784 char *vpre = mlt_properties_get( properties, "vpre" );
787 mlt_properties p = mlt_properties_load( vpre );
789 if ( mlt_properties_count( p ) < 1 )
791 AVCodec *codec = avcodec_find_encoder( c->codec_id );
794 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
795 strcpy( path, AVDATADIR );
796 strcat( path, codec->name );
798 strcat( path, vpre );
799 strcat( path, ".ffpreset" );
801 mlt_properties_close( p );
802 p = mlt_properties_load( path );
803 if ( mlt_properties_count( p ) > 0 )
804 mlt_properties_debug( p, path, stderr );
810 mlt_properties_debug( p, vpre, stderr );
813 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
814 mlt_properties_close( p );
816 int colorspace = mlt_properties_get_int( properties, "colorspace" );
817 mlt_properties_set( properties, "colorspace", NULL );
818 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
819 mlt_properties_set_int( properties, "colorspace", colorspace );
821 // Set options controlled by MLT
822 c->width = mlt_properties_get_int( properties, "width" );
823 c->height = mlt_properties_get_int( properties, "height" );
824 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
825 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
826 if ( st->time_base.den == 0 )
827 st->time_base = c->time_base;
828 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
830 switch ( colorspace )
833 c->colorspace = AVCOL_SPC_SMPTE170M;
836 c->colorspace = AVCOL_SPC_SMPTE240M;
839 c->colorspace = AVCOL_SPC_BT470BG;
842 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
845 c->colorspace = AVCOL_SPC_BT709;
849 if ( mlt_properties_get( properties, "aspect" ) )
851 // "-aspect" on ffmpeg command line is display aspect ratio
852 double ar = mlt_properties_get_double( properties, "aspect" );
853 c->sample_aspect_ratio = av_d2q( ar * c->height / c->width, 255 );
857 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
858 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
860 st->sample_aspect_ratio = c->sample_aspect_ratio;
862 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
864 c->flags |= CODEC_FLAG_QSCALE;
865 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
866 #if LIBAVFORMAT_VERSION_MAJOR < 53
867 st->quality = c->global_quality;
871 // Allow the user to override the video fourcc
872 if ( mlt_properties_get( properties, "vtag" ) )
875 const char *arg = mlt_properties_get( properties, "vtag" );
876 int tag = strtol( arg, &tail, 0);
878 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
882 // Some formats want stream headers to be seperate
883 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
884 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
886 // Translate these standard mlt consumer properties to ffmpeg
887 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
888 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
890 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
891 c->flags |= CODEC_FLAG_INTERLACED_DCT;
892 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
893 c->flags |= CODEC_FLAG_INTERLACED_ME;
896 // parse the ratecontrol override string
898 char *rc_override = mlt_properties_get( properties, "rc_override" );
899 for ( i = 0; rc_override; i++ )
902 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
904 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
905 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
906 c->rc_override[i].start_frame = start;
907 c->rc_override[i].end_frame = end;
910 c->rc_override[i].qscale = q;
911 c->rc_override[i].quality_factor = 1.0;
915 c->rc_override[i].qscale = 0;
916 c->rc_override[i].quality_factor = -q / 100.0;
918 rc_override = strchr( rc_override, '/' );
922 c->rc_override_count = i;
923 if ( !c->rc_initial_buffer_occupancy )
924 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
925 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
928 i = mlt_properties_get_int( properties, "pass" );
930 c->flags |= CODEC_FLAG_PASS1;
932 c->flags |= CODEC_FLAG_PASS2;
933 if ( codec->id != AV_CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
935 char logfilename[1024];
940 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
941 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
942 if ( c->flags & CODEC_FLAG_PASS1 )
944 f = fopen( logfilename, "w" );
946 perror( logfilename );
948 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
952 /* read the log file */
953 f = fopen( logfilename, "r" );
960 mlt_properties_set( properties, "_logfilename", logfilename );
961 fseek( f, 0, SEEK_END );
963 fseek( f, 0, SEEK_SET );
964 logbuffer = av_malloc( size + 1 );
966 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
971 size = fread( logbuffer, 1, size, f );
972 logbuffer[size] = '\0';
973 c->stats_in = logbuffer;
983 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
989 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
992 AVFrame *picture = avcodec_alloc_frame();
994 // Determine size of the
995 int size = avpicture_get_size(pix_fmt, width, height);
997 // Allocate the picture buf
998 uint8_t *picture_buf = av_malloc(size);
1000 // If we have both, then fill the image
1001 if ( picture != NULL && picture_buf != NULL )
1003 // Fill the frame with the allocated buffer
1004 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
1008 // Something failed - clean up what we can
1010 av_free( picture_buf );
1017 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
1020 AVCodecContext *video_enc = st->codec;
1022 // find the video encoder
1025 codec = avcodec_find_encoder_by_name( codec_name );
1027 codec = avcodec_find_encoder( video_enc->codec_id );
1029 // Process properties as AVOptions on the AVCodec
1030 if ( codec && codec->priv_class )
1032 char *vpre = mlt_properties_get( properties, "vpre" );
1033 if ( !video_enc->priv_data && codec->priv_data_size )
1035 video_enc->priv_data = av_mallocz( codec->priv_data_size );
1036 *(const AVClass **) video_enc->priv_data = codec->priv_class;
1037 // av_opt_set_defaults( video_enc );
1041 mlt_properties p = mlt_properties_load( vpre );
1042 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1043 mlt_properties_close( p );
1045 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1048 if( codec && codec->pix_fmts )
1050 const enum PixelFormat *p = codec->pix_fmts;
1051 for( ; *p!=-1; p++ )
1053 if( *p == video_enc->pix_fmt )
1057 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1060 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1061 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1063 int result = codec && avcodec_open( video_enc, codec ) >= 0;
1069 void close_video(AVFormatContext *oc, AVStream *st)
1071 if ( st && st->codec )
1073 av_freep( &st->codec->stats_in );
1074 avcodec_close(st->codec);
1078 static inline long time_difference( struct timeval *time1 )
1080 struct timeval time2;
1081 gettimeofday( &time2, NULL );
1082 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1085 static int mlt_write(void *h, uint8_t *buf, int size)
1087 mlt_properties properties = (mlt_properties) h;
1088 mlt_events_fire( properties, "avformat-write", buf, &size, NULL );
1092 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1094 int *p_size = (int*) args[1];
1095 listener( owner, service, (uint8_t*) args[0], *p_size );
1098 /** The main thread - the argument is simply the consumer.
1101 static void *consumer_thread( void *arg )
1103 // Map the argument to the object
1104 mlt_consumer consumer = arg;
1106 // Get the properties
1107 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1109 // Get the terminate on pause property
1110 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1113 // Determine if feed is slow (for realtime stuff)
1114 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1117 struct timeval ante;
1119 // Get the frame rate
1120 double fps = mlt_properties_get_double( properties, "fps" );
1122 // Get width and height
1123 int width = mlt_properties_get_int( properties, "width" );
1124 int height = mlt_properties_get_int( properties, "height" );
1125 int img_width = width;
1126 int img_height = height;
1128 // Get default audio properties
1129 int channels = mlt_properties_get_int( properties, "channels" );
1130 int total_channels = channels;
1131 int frequency = mlt_properties_get_int( properties, "frequency" );
1135 // AVFormat audio buffer and frame size
1136 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1137 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1138 int audio_input_nb_samples = 0;
1140 // AVFormat video buffer and frame count
1141 int frame_count = 0;
1142 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1143 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1145 // Used for the frame properties
1146 mlt_frame frame = NULL;
1147 mlt_properties frame_properties = NULL;
1150 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1151 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1153 // For receiving images from an mlt_frame
1155 mlt_image_format img_fmt = mlt_image_yuv422;
1156 // Get the image format to use for rendering threads
1157 const char* img_fmt_name = mlt_properties_get( properties, "mlt_image_format" );
1160 if ( !strcmp( img_fmt_name, "rgb24" ) )
1161 img_fmt = mlt_image_rgb24;
1162 else if ( !strcmp( img_fmt_name, "rgb24a" ) )
1163 img_fmt = mlt_image_rgb24a;
1164 else if ( !strcmp( img_fmt_name, "yuv420p" ) )
1165 img_fmt = mlt_image_yuv420p;
1167 else if ( mlt_properties_get( properties, "pix_fmt" ) )
1169 img_fmt_name = mlt_properties_get( properties, "pix_fmt" );
1170 if ( !strcmp( img_fmt_name, "rgba" ) ||
1171 !strcmp( img_fmt_name, "argb" ) ||
1172 !strcmp( img_fmt_name, "bgra" ) )
1173 img_fmt = mlt_image_rgb24a;
1176 // Need two av pictures for converting
1177 AVFrame *converted_avframe = NULL;
1178 AVFrame *audio_avframe = NULL;
1179 AVFrame *video_avframe = alloc_picture( pick_pix_fmt( img_fmt ), width, height );
1181 // For receiving audio samples back from the fifo
1182 uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1183 uint8_t *audio_buf_2 = NULL;
1186 // Allocate the context
1187 AVFormatContext *oc = NULL;
1190 AVStream *video_st = NULL;
1191 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1194 double audio_pts = 0;
1195 double video_pts = 0;
1197 // Frames dispatched
1198 long int frames = 0;
1199 long int total_time = 0;
1201 // Determine the format
1202 AVOutputFormat *fmt = NULL;
1203 const char *filename = mlt_properties_get( properties, "target" );
1204 char *format = mlt_properties_get( properties, "f" );
1205 char *vcodec = mlt_properties_get( properties, "vcodec" );
1206 char *acodec = mlt_properties_get( properties, "acodec" );
1207 AVCodec *audio_codec = NULL;
1208 AVCodec *video_codec = NULL;
1210 // Used to store and override codec ids
1216 mlt_properties frame_meta_properties = mlt_properties_new();
1217 int error_count = 0;
1218 int64_t synth_audio_pts = 0;
1220 // Initialize audio_st
1221 int i = MAX_AUDIO_STREAMS;
1225 // Check for user selected format first
1226 if ( format != NULL )
1227 fmt = av_guess_format( format, NULL, NULL );
1229 // Otherwise check on the filename
1230 if ( fmt == NULL && filename != NULL )
1231 fmt = av_guess_format( NULL, filename, NULL );
1233 // Otherwise default to mpeg
1235 fmt = av_guess_format( "mpeg", NULL, NULL );
1237 // We need a filename - default to stdout?
1238 if ( filename == NULL || !strcmp( filename, "" ) )
1241 #if defined(FFUDIV) && LIBAVUTIL_VERSION_INT >= ((53<<16)+(2<<8)+0)
1242 avformat_alloc_output_context2( &oc, fmt, format, filename );
1244 oc = avformat_alloc_context( );
1246 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1248 if ( oc->oformat && oc->oformat->priv_class && !oc->priv_data && oc->oformat->priv_data_size ) {
1249 oc->priv_data = av_mallocz( oc->oformat->priv_data_size );
1250 if ( oc->priv_data ) {
1251 *(const AVClass**)oc->priv_data = oc->oformat->priv_class;
1252 av_opt_set_defaults( oc->priv_data );
1257 // Get the codec ids selected
1258 audio_codec_id = fmt->audio_codec;
1259 video_codec_id = fmt->video_codec;
1261 // Check for audio codec overides
1262 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1263 audio_codec_id = AV_CODEC_ID_NONE;
1266 audio_codec = avcodec_find_encoder_by_name( acodec );
1269 audio_codec_id = audio_codec->id;
1270 if ( audio_codec_id == AV_CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1272 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1273 acodec = mlt_properties_get( properties, "_acodec" );
1274 audio_codec = avcodec_find_encoder_by_name( acodec );
1276 else if ( !strcmp( acodec, "aac" ) || !strcmp( acodec, "vorbis" ) )
1278 mlt_properties_set( properties, "astrict", "experimental" );
1283 audio_codec_id = AV_CODEC_ID_NONE;
1284 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1289 audio_codec = avcodec_find_encoder( audio_codec_id );
1292 // Check for video codec overides
1293 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1294 video_codec_id = AV_CODEC_ID_NONE;
1297 video_codec = avcodec_find_encoder_by_name( vcodec );
1300 video_codec_id = video_codec->id;
1304 video_codec_id = AV_CODEC_ID_NONE;
1305 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1310 video_codec = avcodec_find_encoder( video_codec_id );
1314 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1316 char *name = mlt_properties_get_name( properties, i );
1317 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1319 char *key = strdup( name + 10 );
1320 char *markup = strrchr( key, '.' );
1321 if ( markup && !strcmp( markup, ".markup") )
1324 if ( !strstr( key, ".stream." ) )
1325 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1326 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1328 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1335 // Get a frame now, so we can set some AVOptions from properties.
1336 frame = mlt_consumer_rt_frame( consumer );
1338 // Set the timecode from the MLT metadata if available.
1341 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1342 if ( timecode && strcmp( timecode, "" ) )
1344 mlt_properties_set( properties, "timecode", timecode );
1345 if ( strchr( timecode, ';' ) )
1346 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1350 // Add audio and video streams
1351 if ( video_codec_id != AV_CODEC_ID_NONE )
1352 video_st = add_video_stream( consumer, oc, video_codec );
1353 if ( audio_codec_id != AV_CODEC_ID_NONE )
1359 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1361 sprintf( key, "channels.%d", i );
1362 int j = mlt_properties_get_int( properties, key );
1366 total_channels += j;
1367 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1373 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1374 total_channels = channels;
1377 mlt_properties_set_int( properties, "channels", total_channels );
1379 // Audio format is determined when adding the audio stream
1380 mlt_audio_format aud_fmt = mlt_audio_none;
1382 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1383 int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1384 sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1386 // Set the parameters (even though we have none...)
1387 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1388 if ( av_set_parameters(oc, NULL) >= 0 )
1391 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1392 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1393 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1395 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1397 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1399 // Process properties as AVOptions
1400 char *fpre = mlt_properties_get( properties, "fpre" );
1403 mlt_properties p = mlt_properties_load( fpre );
1404 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1405 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1406 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1407 mlt_properties_close( p );
1409 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1410 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1411 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1413 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1415 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1417 audio_input_nb_samples = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1418 acodec? acodec : NULL );
1419 if ( !audio_input_nb_samples )
1421 // Remove the audio stream from the output context
1423 for ( j = 0; j < oc->nb_streams; j++ )
1425 if ( oc->streams[j] == audio_st[i] )
1426 av_freep( &oc->streams[j] );
1433 // Setup custom I/O if redirecting
1434 if ( mlt_properties_get_int( properties, "redirect" ) )
1436 int buffer_size = 32768;
1437 unsigned char *buffer = av_malloc( buffer_size );
1438 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1439 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1441 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1446 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1447 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1449 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1450 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1451 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1456 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1459 // Open the output file, if needed
1460 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1462 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1463 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1465 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1468 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1469 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1470 goto on_fatal_error;
1474 // Write the stream header.
1475 if ( mlt_properties_get_int( properties, "running" ) )
1476 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1477 avformat_write_header( oc, NULL );
1479 av_write_header( oc );
1482 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1485 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1486 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1487 goto on_fatal_error;
1491 // Last check - need at least one stream
1492 if ( !audio_st[0] && !video_st )
1494 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1495 goto on_fatal_error;
1500 converted_avframe = alloc_picture( video_st->codec->pix_fmt, width, height );
1502 #if LIBAVCODEC_VERSION_MAJOR >= 54
1503 // Allocate audio AVFrame
1506 audio_avframe = avcodec_alloc_frame();
1507 if ( audio_avframe ) {
1508 AVCodecContext *c = audio_st[0]->codec;
1509 audio_avframe->format = c->sample_fmt;
1510 audio_avframe->nb_samples = audio_input_nb_samples;
1511 audio_avframe->channel_layout = c->channel_layout;
1513 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to allocate audio AVFrame\n" );
1514 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1515 goto on_fatal_error;
1520 // Get the starting time (can ignore the times above)
1521 gettimeofday( &ante, NULL );
1523 // Loop while running
1524 while( mlt_properties_get_int( properties, "running" ) &&
1525 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1528 frame = mlt_consumer_rt_frame( consumer );
1530 // Check that we have a frame to work with
1531 if ( frame != NULL )
1533 // Increment frames dispatched
1536 // Default audio args
1537 frame_properties = MLT_FRAME_PROPERTIES( frame );
1539 // Check for the terminated condition
1540 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1542 // Get audio and append to the fifo
1543 if ( !terminated && audio_st[0] )
1545 samples = mlt_sample_calculator( fps, frequency, count ++ );
1546 channels = total_channels;
1547 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1549 // Save the audio channel remap properties for later
1550 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1552 // Create the fifo if we don't have one
1555 fifo = sample_fifo_init( frequency, channels );
1556 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1560 // Silence if not normal forward speed
1561 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1562 memset( pcm, 0, samples * channels * sample_bytes );
1564 // Append the samples
1565 sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1566 total_time += ( samples * 1000000 ) / frequency;
1569 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1573 if ( !terminated && video_st )
1574 mlt_deque_push_back( queue, frame );
1576 mlt_frame_close( frame );
1580 // While we have stuff to process, process...
1583 // Write interleaved audio and video frames
1584 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1587 if ( ( video_st && terminated ) || ( channels * audio_input_nb_samples ) < sample_fifo_used( fifo ) / sample_bytes )
1589 int j = 0; // channel offset into interleaved source buffer
1590 int n = FFMIN( FFMIN( channels * audio_input_nb_samples, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1592 // Get the audio samples
1595 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1597 else if ( audio_codec_id == AV_CODEC_ID_VORBIS && terminated )
1599 // This prevents an infinite loop when some versions of vorbis do not
1600 // increment pts when encoding silence.
1601 audio_pts = video_pts;
1606 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1608 samples = n / channels;
1610 // For each output stream
1611 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1613 AVStream *stream = audio_st[i];
1614 AVCodecContext *codec = stream->codec;
1617 av_init_packet( &pkt );
1618 pkt.data = audio_outbuf;
1619 pkt.size = audio_outbuf_size;
1621 // Optimized for single track and no channel remap
1622 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1624 void* p = audio_buf_1;
1625 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1626 if ( codec->sample_fmt == AV_SAMPLE_FMT_FLTP )
1627 p = interleaved_to_planar( samples, channels, p, sizeof( float ) );
1628 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S16P )
1629 p = interleaved_to_planar( samples, channels, p, sizeof( int16_t ) );
1630 else if ( codec->sample_fmt == AV_SAMPLE_FMT_S32P )
1631 p = interleaved_to_planar( samples, channels, p, sizeof( int32_t ) );
1632 else if ( codec->sample_fmt == AV_SAMPLE_FMT_U8P )
1633 p = interleaved_to_planar( samples, channels, p, sizeof( uint8_t ) );
1635 #if LIBAVCODEC_VERSION_MAJOR >= 54
1636 audio_avframe->nb_samples = FFMAX( samples, audio_input_nb_samples );
1637 #if LIBAVCODEC_VERSION_MAJOR >= 55
1638 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
1639 audio_avframe->pts = synth_audio_pts;
1640 synth_audio_pts += audio_avframe->nb_samples;
1642 avcodec_fill_audio_frame( audio_avframe, codec->channels, codec->sample_fmt,
1643 (const uint8_t*) p, AUDIO_ENCODE_BUFFER_SIZE, 0 );
1645 int ret = avcodec_encode_audio2( codec, &pkt, audio_avframe, &got_packet );
1648 else if ( !got_packet )
1651 codec->frame_size = FFMAX( samples, audio_input_nb_samples );
1652 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, p );
1653 pkt.pts = codec->coded_frame? codec->coded_frame->pts : AV_NOPTS_VALUE;
1654 pkt.flags |= PKT_FLAG_KEY;
1657 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1658 if ( p != audio_buf_1 )
1659 mlt_pool_release( p );
1664 // Extract the audio channels according to channel mapping
1665 int dest_offset = 0; // channel offset into interleaved dest buffer
1667 // Get the number of channels for this stream
1668 sprintf( key, "channels.%d", i );
1669 int current_channels = mlt_properties_get_int( properties, key );
1671 // Clear the destination audio buffer.
1673 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1675 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1677 // For each output channel
1678 while ( dest_offset < current_channels && j < total_channels )
1680 int map_start = -1, map_channels = 0;
1681 int source_offset = 0;
1684 // Look for a mapping that starts at j
1685 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1687 sprintf( key, "%d.channels", k );
1688 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1689 sprintf( key, "%d.start", k );
1690 if ( mlt_properties_get( frame_meta_properties, key ) )
1691 map_start = mlt_properties_get_int( frame_meta_properties, key );
1692 if ( map_start != j )
1693 source_offset += map_channels;
1697 if ( map_start != j )
1699 map_channels = current_channels;
1703 // Copy samples if source offset valid
1704 if ( source_offset < channels )
1706 // Interleave the audio buffer with the # channels for this stream/mapping.
1707 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1709 void *src = audio_buf_1 + source_offset * sample_bytes;
1710 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1711 int s = samples + 1;
1714 memcpy( dest, src, sample_bytes );
1715 dest += current_channels * sample_bytes;
1716 src += channels * sample_bytes;
1720 // Otherwise silence
1723 j += current_channels;
1724 dest_offset += current_channels;
1727 #if LIBAVCODEC_VERSION_MAJOR >= 54
1728 audio_avframe->nb_samples = FFMAX( samples, audio_input_nb_samples );
1729 #if LIBAVCODEC_VERSION_MAJOR >= 55
1730 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
1731 audio_avframe->pts = synth_audio_pts;
1732 synth_audio_pts += audio_avframe->nb_samples;
1734 avcodec_fill_audio_frame( audio_avframe, codec->channels, codec->sample_fmt,
1735 (const uint8_t*) audio_buf_2, AUDIO_ENCODE_BUFFER_SIZE, 0 );
1737 int ret = avcodec_encode_audio2( codec, &pkt, audio_avframe, &got_packet );
1740 else if ( !got_packet )
1743 codec->frame_size = FFMAX( samples, audio_input_nb_samples );
1744 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1745 pkt.pts = codec->coded_frame? codec->coded_frame->pts : AV_NOPTS_VALUE;
1746 pkt.flags |= PKT_FLAG_KEY;
1752 // Write the compressed frame in the media file
1753 if ( pkt.pts != AV_NOPTS_VALUE )
1754 pkt.pts = av_rescale_q( pkt.pts, codec->time_base, stream->time_base );
1755 #if LIBAVCODEC_VERSION_MAJOR >= 55
1756 if ( pkt.dts != AV_NOPTS_VALUE )
1757 pkt.dts = av_rescale_q( pkt.dts, codec->time_base, stream->time_base );
1758 if ( pkt.duration > 0 )
1759 pkt.duration = av_rescale_q( pkt.duration, codec->time_base, stream->time_base );
1761 pkt.stream_index = stream->index;
1762 if ( av_interleaved_write_frame( oc, &pkt ) )
1764 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1765 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1766 goto on_fatal_error;
1769 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame_size %d stream pts %"PRId64"\n",
1770 stream->index, pkt.pts, codec->frame_size, stream->pts.val );
1772 else if ( pkt.size < 0 )
1774 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with audio encode %d\n", frame_count );
1775 if ( ++error_count > 2 )
1776 goto on_fatal_error;
1781 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1790 else if ( video_st )
1793 if ( mlt_deque_count( queue ) )
1796 AVCodecContext *c = video_st->codec;
1798 frame = mlt_deque_pop_front( queue );
1799 frame_properties = MLT_FRAME_PROPERTIES( frame );
1801 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1806 int stride = mlt_image_format_size( img_fmt, width, 0, NULL );
1808 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1811 // Convert the mlt frame to an AVPicture
1812 if ( img_fmt == mlt_image_yuv420p )
1814 memcpy( video_avframe->data[0], q, video_avframe->linesize[0] );
1816 memcpy( video_avframe->data[1], q, video_avframe->linesize[1] );
1818 memcpy( video_avframe->data[2], q, video_avframe->linesize[2] );
1820 else for ( i = 0; i < height; i ++ )
1822 p = video_avframe->data[0] + i * video_avframe->linesize[0];
1823 memcpy( p, q, stride );
1827 // Do the colour space conversion
1828 int flags = SWS_BICUBIC;
1830 flags |= SWS_CPU_CAPS_MMX;
1833 flags |= SWS_CPU_CAPS_MMX2;
1835 struct SwsContext *context = sws_getContext( width, height, pick_pix_fmt( img_fmt ),
1836 width, height, c->pix_fmt, flags, NULL, NULL, NULL);
1837 sws_scale( context, (const uint8_t* const*) video_avframe->data, video_avframe->linesize, 0, height,
1838 converted_avframe->data, converted_avframe->linesize);
1839 sws_freeContext( context );
1841 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1843 // Apply the alpha if applicable
1844 if ( !mlt_properties_get( properties, "mlt_image_format" ) ||
1845 strcmp( mlt_properties_get( properties, "mlt_image_format" ), "rgb24a" ) )
1846 if ( c->pix_fmt == PIX_FMT_RGBA ||
1847 c->pix_fmt == PIX_FMT_ARGB ||
1848 c->pix_fmt == PIX_FMT_BGRA )
1850 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1853 for ( i = 0; i < height; i ++ )
1855 n = ( width + 7 ) / 8;
1856 p = converted_avframe->data[ 0 ] + i * converted_avframe->linesize[ 0 ] + 3;
1860 case 0: do { *p = *alpha++; p += 4;
1861 case 7: *p = *alpha++; p += 4;
1862 case 6: *p = *alpha++; p += 4;
1863 case 5: *p = *alpha++; p += 4;
1864 case 4: *p = *alpha++; p += 4;
1865 case 3: *p = *alpha++; p += 4;
1866 case 2: *p = *alpha++; p += 4;
1867 case 1: *p = *alpha++; p += 4;
1875 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1877 // raw video case. The API will change slightly in the near future for that
1879 av_init_packet(&pkt);
1881 // Set frame interlace hints
1882 c->coded_frame->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1883 c->coded_frame->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1884 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(61<<8)+100)
1885 if ( mlt_properties_get_int( frame_properties, "progressive" ) )
1886 c->field_order = AV_FIELD_PROGRESSIVE;
1888 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TT : AV_FIELD_BB;
1890 pkt.flags |= PKT_FLAG_KEY;
1891 pkt.stream_index = video_st->index;
1892 pkt.data = (uint8_t *)converted_avframe;
1893 pkt.size = sizeof(AVPicture);
1895 ret = av_write_frame(oc, &pkt);
1896 video_pts += c->frame_size;
1901 av_init_packet( &pkt );
1902 if ( c->codec->id == AV_CODEC_ID_RAWVIDEO ) {
1906 pkt.data = video_outbuf;
1907 pkt.size = video_outbuf_size;
1911 converted_avframe->quality = c->global_quality;
1912 converted_avframe->pts = frame_count;
1914 // Set frame interlace hints
1915 converted_avframe->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1916 converted_avframe->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1917 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(61<<8)+100)
1918 if ( mlt_properties_get_int( frame_properties, "progressive" ) )
1919 c->field_order = AV_FIELD_PROGRESSIVE;
1920 else if ( c->codec_id == AV_CODEC_ID_MJPEG )
1921 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TT : AV_FIELD_BB;
1923 c->field_order = (mlt_properties_get_int( frame_properties, "top_field_first" )) ? AV_FIELD_TB : AV_FIELD_BT;
1927 #if LIBAVCODEC_VERSION_MAJOR >= 55
1929 ret = avcodec_encode_video2( c, &pkt, converted_avframe, &got_packet );
1932 else if ( !got_packet )
1935 pkt.size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, converted_avframe );
1936 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
1937 if ( c->coded_frame && c->coded_frame->key_frame )
1938 pkt.flags |= PKT_FLAG_KEY;
1941 // If zero size, it means the image was buffered
1944 if ( pkt.pts != AV_NOPTS_VALUE )
1945 pkt.pts = av_rescale_q( pkt.pts, c->time_base, video_st->time_base );
1946 #if LIBAVCODEC_VERSION_MAJOR >= 55
1947 if ( pkt.dts != AV_NOPTS_VALUE )
1948 pkt.dts = av_rescale_q( pkt.dts, c->time_base, video_st->time_base );
1950 pkt.stream_index = video_st->index;
1952 // write the compressed frame in the media file
1953 ret = av_interleaved_write_frame(oc, &pkt);
1954 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1955 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1957 // Dual pass logging
1958 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1959 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1963 else if ( pkt.size < 0 )
1965 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1966 if ( ++error_count > 2 )
1967 goto on_fatal_error;
1974 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1975 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1976 goto on_fatal_error;
1978 mlt_frame_close( frame );
1987 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1989 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1990 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1993 if ( real_time_output == 1 && frames % 2 == 0 )
1995 long passed = time_difference( &ante );
1998 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
2001 if ( passed < total_time )
2003 long total = ( total_time - passed );
2004 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
2005 nanosleep( &t, NULL );
2010 // Flush the encoder buffers
2011 if ( real_time_output <= 0 )
2014 // TODO: flush all audio streams
2015 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
2017 AVCodecContext *c = audio_st[0]->codec;
2019 av_init_packet( &pkt );
2020 pkt.data = audio_outbuf;
2023 if ( fifo && sample_fifo_used( fifo ) > 0 )
2025 // Drain the MLT FIFO
2026 int samples = FFMIN( FFMIN( channels * audio_input_nb_samples, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
2027 sample_fifo_fetch( fifo, audio_buf_1, samples * sample_bytes );
2028 void* p = audio_buf_1;
2029 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2030 if ( c->sample_fmt == AV_SAMPLE_FMT_FLTP )
2031 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( float ) );
2032 else if ( c->sample_fmt == AV_SAMPLE_FMT_S16P )
2033 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( int16_t ) );
2034 else if ( c->sample_fmt == AV_SAMPLE_FMT_S32P )
2035 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( int32_t ) );
2036 else if ( c->sample_fmt == AV_SAMPLE_FMT_U8P )
2037 p = interleaved_to_planar( audio_input_nb_samples, channels, p, sizeof( uint8_t ) );
2039 #if LIBAVCODEC_VERSION_MAJOR >= 54
2040 pkt.size = audio_outbuf_size;
2041 audio_avframe->nb_samples = FFMAX( samples / channels, audio_input_nb_samples );
2042 #if LIBAVCODEC_VERSION_MAJOR >= 55
2043 if ( audio_codec_id == AV_CODEC_ID_VORBIS )
2044 audio_avframe->pts = synth_audio_pts;
2045 synth_audio_pts += audio_avframe->nb_samples;
2047 avcodec_fill_audio_frame( audio_avframe, c->channels, c->sample_fmt,
2048 (const uint8_t*) p, AUDIO_ENCODE_BUFFER_SIZE, 0 );
2050 int ret = avcodec_encode_audio2( c, &pkt, audio_avframe, &got_packet );
2053 else if ( !got_packet )
2056 c->frame_size = FFMAX( samples / channels, audio_input_nb_samples );
2057 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, p );
2059 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2060 if ( p != audio_buf_1 )
2061 mlt_pool_release( p );
2063 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
2068 if ( pkt.size <= 0 ) {
2069 #if LIBAVCODEC_VERSION_MAJOR >= 54
2070 pkt.size = audio_outbuf_size;
2072 int ret = avcodec_encode_audio2( c, &pkt, NULL, &got_packet );
2075 else if ( !got_packet )
2078 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
2079 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
2080 pkt.flags |= PKT_FLAG_KEY;
2083 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
2084 if ( pkt.size <= 0 )
2088 // Write the compressed frame in the media file
2089 if ( pkt.pts != AV_NOPTS_VALUE )
2090 pkt.pts = av_rescale_q( pkt.pts, c->time_base, audio_st[0]->time_base );
2091 #if LIBAVCODEC_VERSION_MAJOR >= 55
2092 if ( pkt.dts != AV_NOPTS_VALUE )
2093 pkt.dts = av_rescale_q( pkt.dts, c->time_base, audio_st[0]->time_base );
2094 if ( pkt.duration > 0 )
2095 pkt.duration = av_rescale_q( pkt.duration, c->time_base, audio_st[0]->time_base );
2097 pkt.stream_index = audio_st[0]->index;
2098 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
2100 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
2106 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
2108 AVCodecContext *c = video_st->codec;
2110 av_init_packet( &pkt );
2111 if ( c->codec->id == AV_CODEC_ID_RAWVIDEO ) {
2115 pkt.data = video_outbuf;
2116 pkt.size = video_outbuf_size;
2120 #if LIBAVCODEC_VERSION_MAJOR >= 55
2122 int ret = avcodec_encode_video2( c, &pkt, NULL, &got_packet );
2125 else if ( !got_packet )
2128 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
2129 pkt.pts = c->coded_frame? c->coded_frame->pts : AV_NOPTS_VALUE;
2130 if( c->coded_frame && c->coded_frame->key_frame )
2131 pkt.flags |= PKT_FLAG_KEY;
2133 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
2134 if ( pkt.size <= 0 )
2137 if ( pkt.pts != AV_NOPTS_VALUE )
2138 pkt.pts = av_rescale_q( pkt.pts, c->time_base, video_st->time_base );
2139 #if LIBAVCODEC_VERSION_MAJOR >= 55
2140 if ( pkt.dts != AV_NOPTS_VALUE )
2141 pkt.dts = av_rescale_q( pkt.dts, c->time_base, video_st->time_base );
2143 pkt.stream_index = video_st->index;
2145 // write the compressed frame in the media file
2146 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
2148 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
2149 mlt_events_fire( properties, "consumer-fatal-error", NULL );
2150 goto on_fatal_error;
2152 // Dual pass logging
2153 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
2154 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
2161 mlt_frame_close( frame );
2163 // Write the trailer, if any
2165 av_write_trailer( oc );
2169 close_video(oc, video_st);
2170 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
2171 close_audio( oc, audio_st[i] );
2174 for ( i = 0; i < oc->nb_streams; i++ )
2175 av_freep( &oc->streams[i] );
2177 // Close the output file
2178 if ( !( fmt->flags & AVFMT_NOFILE ) &&
2179 !mlt_properties_get_int( properties, "redirect" ) )
2181 #if LIBAVFORMAT_VERSION_MAJOR >= 53
2182 if ( oc->pb ) avio_close( oc->pb );
2184 if ( oc->pb ) url_fclose( oc->pb );
2188 // Clean up input and output frames
2189 if ( converted_avframe )
2190 av_free( converted_avframe->data[0] );
2191 av_free( converted_avframe );
2192 av_free( video_avframe->data[0] );
2193 av_free( video_avframe );
2194 av_free( video_outbuf );
2195 av_free( audio_avframe );
2196 av_free( audio_buf_1 );
2197 av_free( audio_buf_2 );
2202 // Just in case we terminated on pause
2203 mlt_consumer_stopped( consumer );
2204 mlt_properties_close( frame_meta_properties );
2206 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
2208 // Remove the dual pass log file
2209 if ( mlt_properties_get( properties, "_logfilename" ) )
2210 remove( mlt_properties_get( properties, "_logfilename" ) );
2212 // Remove the x264 dual pass logs
2213 char *cwd = getcwd( NULL, 0 );
2214 const char *file = "x264_2pass.log";
2215 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2216 sprintf( full, "%s/%s", cwd, file );
2219 file = "x264_2pass.log.temp";
2220 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2221 sprintf( full, "%s/%s", cwd, file );
2224 file = "x264_2pass.log.mbtree";
2225 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
2226 sprintf( full, "%s/%s", cwd, file );
2230 remove( "x264_2pass.log.temp" );
2232 // Recent versions of libavcodec/x264 support passlogfile and need cleanup if specified.
2233 if ( !mlt_properties_get( properties, "_logfilename" ) &&
2234 mlt_properties_get( properties, "passlogfile" ) )
2236 file = mlt_properties_get( properties, "passlogfile" );
2238 full = malloc( strlen( file ) + strlen( ".mbtree" ) + 1 );
2239 sprintf( full, "%s.mbtree", file );
2245 while ( ( frame = mlt_deque_pop_back( queue ) ) )
2246 mlt_frame_close( frame );
2251 /** Close the consumer.
2254 static void consumer_close( mlt_consumer consumer )
2256 // Stop the consumer
2257 mlt_consumer_stop( consumer );
2260 mlt_consumer_close( consumer );