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>
43 #include <libswscale/swscale.h>
45 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
46 #include <libavutil/pixdesc.h>
48 #include <libavutil/mathematics.h>
50 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
51 # include <libavutil/samplefmt.h>
53 # define AV_SAMPLE_FMT_NONE SAMPLE_FMT_NONE
54 # define AV_SAMPLE_FMT_S16 SAMPLE_FMT_S16
55 # define AV_SAMPLE_FMT_S32 SAMPLE_FMT_S32
56 # define AV_SAMPLE_FMT_FLT SAMPLE_FMT_FLT
59 #if LIBAVUTIL_VERSION_INT < (50<<16)
60 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
61 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
64 #if LIBAVCODEC_VERSION_MAJOR >= 53
65 #include <libavutil/opt.h>
66 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
67 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
68 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
70 #include <libavcodec/opt.h>
73 #define MAX_AUDIO_STREAMS (8)
74 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
75 #define AUDIO_BUFFER_SIZE (1024 * 42)
76 #define VIDEO_BUFFER_SIZE (2048 * 1024)
79 // This structure should be extended and made globally available in mlt
91 *sample_fifo, sample_fifo_s;
93 sample_fifo sample_fifo_init( int frequency, int channels )
95 sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
96 fifo->frequency = frequency;
97 fifo->channels = channels;
101 // count is the number of samples multiplied by the number of bytes per sample
102 void sample_fifo_append( sample_fifo fifo, uint8_t *samples, int count )
104 if ( ( fifo->size - fifo->used ) < count )
106 fifo->size += count * 5;
107 fifo->buffer = realloc( fifo->buffer, fifo->size );
110 memcpy( &fifo->buffer[ fifo->used ], samples, count );
114 int sample_fifo_used( sample_fifo fifo )
119 int sample_fifo_fetch( sample_fifo fifo, uint8_t *samples, int count )
121 if ( count > fifo->used )
124 memcpy( samples, fifo->buffer, count );
126 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used );
128 fifo->time += ( double )count / fifo->channels / fifo->frequency;
133 void sample_fifo_close( sample_fifo fifo )
135 free( fifo->buffer );
139 // Forward references.
140 static int consumer_start( mlt_consumer consumer );
141 static int consumer_stop( mlt_consumer consumer );
142 static int consumer_is_stopped( mlt_consumer consumer );
143 static void *consumer_thread( void *arg );
144 static void consumer_close( mlt_consumer consumer );
146 /** Initialise the consumer.
149 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
151 // Allocate the consumer
152 mlt_consumer consumer = mlt_consumer_new( profile );
154 // If memory allocated and initialises without error
155 if ( consumer != NULL )
157 // Get properties from the consumer
158 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
160 // Assign close callback
161 consumer->close = consumer_close;
163 // Interpret the argument
165 mlt_properties_set( properties, "target", arg );
167 // sample and frame queue
168 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
170 // Audio options not fully handled by AVOptions
171 #define QSCALE_NONE (-99999)
172 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
174 // Video options not fully handled by AVOptions
175 mlt_properties_set_int( properties, "dc", 8 );
177 // Muxer options not fully handled by AVOptions
178 mlt_properties_set_double( properties, "muxdelay", 0.7 );
179 mlt_properties_set_double( properties, "muxpreload", 0.5 );
181 // Ensure termination at end of the stream
182 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
184 // Default to separate processing threads for producer and consumer with no frame dropping!
185 mlt_properties_set_int( properties, "real_time", -1 );
186 mlt_properties_set_int( properties, "prefill", 1 );
188 // Set up start/stop/terminated callbacks
189 consumer->start = consumer_start;
190 consumer->stop = consumer_stop;
191 consumer->is_stopped = consumer_is_stopped;
193 mlt_events_register( properties, "consumer-fatal-error", NULL );
200 /** Start the consumer.
203 static int consumer_start( mlt_consumer consumer )
205 // Get the properties
206 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
209 // Report information about available muxers and codecs as YAML Tiny
210 char *s = mlt_properties_get( properties, "f" );
211 if ( s && strcmp( s, "list" ) == 0 )
213 mlt_properties doc = mlt_properties_new();
214 mlt_properties formats = mlt_properties_new();
216 AVOutputFormat *format = NULL;
218 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
219 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
220 while ( ( format = av_oformat_next( format ) ) )
222 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
223 mlt_properties_set( formats, key, format->name );
225 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
226 mlt_properties_close( doc );
229 s = mlt_properties_get( properties, "acodec" );
230 if ( s && strcmp( s, "list" ) == 0 )
232 mlt_properties doc = mlt_properties_new();
233 mlt_properties codecs = mlt_properties_new();
235 AVCodec *codec = NULL;
237 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
238 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
239 while ( ( codec = av_codec_next( codec ) ) )
240 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
242 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
243 mlt_properties_set( codecs, key, codec->name );
245 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
246 mlt_properties_close( doc );
249 s = mlt_properties_get( properties, "vcodec" );
250 if ( s && strcmp( s, "list" ) == 0 )
252 mlt_properties doc = mlt_properties_new();
253 mlt_properties codecs = mlt_properties_new();
255 AVCodec *codec = NULL;
257 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
258 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
259 while ( ( codec = av_codec_next( codec ) ) )
260 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(34<<8)+0)
261 if ( (codec->encode || codec->encode2) && codec->type == CODEC_TYPE_VIDEO )
263 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
266 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
267 mlt_properties_set( codecs, key, codec->name );
269 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
270 mlt_properties_close( doc );
274 // Check that we're not already running
275 if ( !error && !mlt_properties_get_int( properties, "running" ) )
278 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
280 // Get the width and height
281 int width = mlt_properties_get_int( properties, "width" );
282 int height = mlt_properties_get_int( properties, "height" );
284 // Obtain the size property
285 char *size = mlt_properties_get( properties, "s" );
291 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
298 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Invalid size property %s - ignoring.\n", size );
302 // Now ensure we honour the multiple of two requested by libavformat
303 width = ( width / 2 ) * 2;
304 height = ( height / 2 ) * 2;
305 mlt_properties_set_int( properties, "width", width );
306 mlt_properties_set_int( properties, "height", height );
308 // We need to set these on the profile as well because the s property is
309 // an alias to mlt properties that correspond to profile settings.
310 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
313 profile->width = width;
314 profile->height = height;
317 // Handle the ffmpeg command line "-r" property for frame rate
318 if ( mlt_properties_get( properties, "r" ) )
320 double frame_rate = mlt_properties_get_double( properties, "r" );
321 AVRational rational = av_d2q( frame_rate, 255 );
322 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
323 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
326 profile->frame_rate_num = rational.num;
327 profile->frame_rate_den = rational.den;
328 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
332 // Apply AVOptions that are synonyms for standard mlt_consumer options
333 if ( mlt_properties_get( properties, "ac" ) )
334 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
335 if ( mlt_properties_get( properties, "ar" ) )
336 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
338 // Assign the thread to properties
339 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
342 pthread_create( thread, NULL, consumer_thread, consumer );
344 // Set the running state
345 mlt_properties_set_int( properties, "running", 1 );
350 /** Stop the consumer.
353 static int consumer_stop( mlt_consumer consumer )
355 // Get the properties
356 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
357 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
359 // Check that we're running
363 mlt_properties_set_int( properties, "running", 0 );
365 // Wait for termination
366 pthread_join( *thread, NULL );
368 mlt_properties_set( properties, "thread", NULL );
374 /** Determine if the consumer is stopped.
377 static int consumer_is_stopped( mlt_consumer consumer )
379 // Get the properties
380 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
381 return !mlt_properties_get_int( properties, "running" );
384 /** Process properties as AVOptions and apply to AV context obj
387 static void apply_properties( void *obj, mlt_properties properties, int flags )
390 int count = mlt_properties_count( properties );
391 #if LIBAVUTIL_VERSION_INT < ((51<<16)+(12<<8)+0)
395 for ( i = 0; i < count; i++ )
397 const char *opt_name = mlt_properties_get_name( properties, i );
398 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
399 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
401 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
404 // If option not found, see if it was prefixed with a or v (-vb)
406 ( opt_name[0] == 'v' && ( flags & AV_OPT_FLAG_VIDEO_PARAM ) ) ||
407 ( opt_name[0] == 'a' && ( flags & AV_OPT_FLAG_AUDIO_PARAM ) ) ) )
408 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
409 opt = av_opt_find( obj, ++opt_name, NULL, flags, flags );
411 opt = av_find_opt( obj, ++opt_name, NULL, flags, flags );
413 // Apply option if found
415 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
416 av_opt_set( obj, opt_name, mlt_properties_get_value( properties, i), 0 );
417 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
418 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
419 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
420 av_set_string2( obj, opt_name, mlt_properties_get_value( properties, i), alloc );
422 av_set_string( obj, opt_name, mlt_properties_get_value( properties, i) );
427 static int get_mlt_audio_format( int av_sample_fmt )
429 switch ( av_sample_fmt )
431 case AV_SAMPLE_FMT_S32:
432 return mlt_audio_s32le;
433 case AV_SAMPLE_FMT_FLT:
434 return mlt_audio_f32le;
435 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
436 case AV_SAMPLE_FMT_S32P:
437 return mlt_audio_s32;
438 case AV_SAMPLE_FMT_FLTP:
439 return mlt_audio_float;
442 return mlt_audio_s16;
446 static int pick_sample_fmt( mlt_properties properties, AVCodec *codec )
448 int sample_fmt = AV_SAMPLE_FMT_S16;
449 const char *format = mlt_properties_get( properties, "mlt_audio_format" );
450 const int *p = codec->sample_fmts;
452 // get default av_sample_fmt from mlt_audio_format
455 if ( !strcmp( format, "s32le" ) )
456 sample_fmt = AV_SAMPLE_FMT_S32;
457 else if ( !strcmp( format, "f32le" ) )
458 sample_fmt = AV_SAMPLE_FMT_FLT;
459 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
460 else if ( !strcmp( format, "s32" ) )
461 sample_fmt = AV_SAMPLE_FMT_S32P;
462 else if ( !strcmp( format, "float" ) )
463 sample_fmt = AV_SAMPLE_FMT_FLTP;
466 // check if codec supports our mlt_audio_format
467 for ( ; *p != -1; p++ )
469 if ( *p == sample_fmt )
472 // no match - pick first one we support
473 for ( p = codec->sample_fmts; *p != -1; p++ )
477 case AV_SAMPLE_FMT_S16:
478 case AV_SAMPLE_FMT_S32:
479 case AV_SAMPLE_FMT_FLT:
480 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
481 case AV_SAMPLE_FMT_S32P:
482 case AV_SAMPLE_FMT_FLTP:
489 mlt_log_error( properties, "audio codec sample_fmt not compatible" );
491 return AV_SAMPLE_FMT_NONE;
494 /** Add an audio output stream
497 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec, int channels )
499 // Get the properties
500 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
502 // Create a new stream
503 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
504 AVStream *st = avformat_new_stream( oc, codec );
506 AVStream *st = av_new_stream( oc, oc->nb_streams );
509 // If created, then initialise from properties
512 AVCodecContext *c = st->codec;
514 // Establish defaults from AVOptions
515 #if LIBAVCODEC_VERSION_MAJOR >= 53
516 avcodec_get_context_defaults3( c, codec );
518 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
521 c->codec_id = codec->id;
522 c->codec_type = CODEC_TYPE_AUDIO;
523 c->sample_fmt = pick_sample_fmt( properties, codec );
525 #if 0 // disabled until some audio codecs are multi-threaded
526 // Setup multi-threading
527 int thread_count = mlt_properties_get_int( properties, "threads" );
528 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
529 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
530 if ( thread_count > 1 )
531 c->thread_count = thread_count;
534 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
535 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
537 // Allow the user to override the audio fourcc
538 if ( mlt_properties_get( properties, "atag" ) )
541 char *arg = mlt_properties_get( properties, "atag" );
542 int tag = strtol( arg, &tail, 0);
544 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
548 // Process properties as AVOptions
549 char *apre = mlt_properties_get( properties, "apre" );
552 mlt_properties p = mlt_properties_load( apre );
553 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
554 mlt_properties_close( p );
556 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
558 int audio_qscale = mlt_properties_get_int( properties, "aq" );
559 if ( audio_qscale > QSCALE_NONE )
561 c->flags |= CODEC_FLAG_QSCALE;
562 c->global_quality = FF_QP2LAMBDA * audio_qscale;
563 #if LIBAVFORMAT_VERSION_MAJOR < 53
564 st->quality = c->global_quality;
568 // Set parameters controlled by MLT
569 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
570 c->time_base = ( AVRational ){ 1, c->sample_rate };
571 c->channels = channels;
573 if ( mlt_properties_get( properties, "alang" ) != NULL )
574 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
575 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
576 av_dict_set( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
578 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
582 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
587 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
593 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
595 // We will return the audio input size from here
596 int audio_input_frame_size = 0;
599 AVCodecContext *c = st->codec;
604 codec = avcodec_find_encoder_by_name( codec_name );
606 codec = avcodec_find_encoder( c->codec_id );
608 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
609 // Process properties as AVOptions on the AVCodec
610 if ( codec && codec->priv_class )
612 char *apre = mlt_properties_get( properties, "apre" );
613 if ( !c->priv_data && codec->priv_data_size )
615 c->priv_data = av_mallocz( codec->priv_data_size );
616 *(const AVClass **) c->priv_data = codec->priv_class;
617 // av_opt_set_defaults( c );
621 mlt_properties p = mlt_properties_load( apre );
622 apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
623 mlt_properties_close( p );
625 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
629 // Continue if codec found and we can open it
630 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
631 if ( codec && avcodec_open2( c, codec, NULL ) >= 0 )
633 if ( codec && avcodec_open( c, codec ) >= 0 )
636 // ugly hack for PCM codecs (will be removed ASAP with new PCM
637 // support to compute the input frame size in samples
638 if ( c->frame_size <= 1 )
640 audio_input_frame_size = audio_outbuf_size / c->channels;
641 switch(st->codec->codec_id)
643 case CODEC_ID_PCM_S16LE:
644 case CODEC_ID_PCM_S16BE:
645 case CODEC_ID_PCM_U16LE:
646 case CODEC_ID_PCM_U16BE:
647 audio_input_frame_size >>= 1;
655 audio_input_frame_size = c->frame_size;
658 // Some formats want stream headers to be seperate (hmm)
659 if ( !strcmp( oc->oformat->name, "mp4" ) ||
660 !strcmp( oc->oformat->name, "mov" ) ||
661 !strcmp( oc->oformat->name, "3gp" ) )
662 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
666 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
669 return audio_input_frame_size;
672 static void close_audio( AVFormatContext *oc, AVStream *st )
674 if ( st && st->codec )
675 avcodec_close( st->codec );
678 /** Add a video output stream
681 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
683 // Get the properties
684 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
686 // Create a new stream
687 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
688 AVStream *st = avformat_new_stream( oc, codec );
690 AVStream *st = av_new_stream( oc, oc->nb_streams );
695 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
696 AVCodecContext *c = st->codec;
698 // Establish defaults from AVOptions
699 #if LIBAVCODEC_VERSION_MAJOR >= 53
700 avcodec_get_context_defaults3( c, codec );
702 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
705 c->codec_id = codec->id;
706 c->codec_type = CODEC_TYPE_VIDEO;
708 // Setup multi-threading
709 int thread_count = mlt_properties_get_int( properties, "threads" );
710 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
711 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
712 if ( thread_count > 1 )
713 #if LIBAVCODEC_VERSION_MAJOR >= 53
714 c->thread_count = thread_count;
716 avcodec_thread_init( c, thread_count );
719 // Process properties as AVOptions
720 char *vpre = mlt_properties_get( properties, "vpre" );
723 mlt_properties p = mlt_properties_load( vpre );
725 if ( mlt_properties_count( p ) < 1 )
727 AVCodec *codec = avcodec_find_encoder( c->codec_id );
730 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
731 strcpy( path, AVDATADIR );
732 strcat( path, codec->name );
734 strcat( path, vpre );
735 strcat( path, ".ffpreset" );
737 mlt_properties_close( p );
738 p = mlt_properties_load( path );
739 if ( mlt_properties_count( p ) > 0 )
740 mlt_properties_debug( p, path, stderr );
746 mlt_properties_debug( p, vpre, stderr );
749 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
750 mlt_properties_close( p );
752 int colorspace = mlt_properties_get_int( properties, "colorspace" );
753 mlt_properties_set( properties, "colorspace", NULL );
754 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
755 mlt_properties_set_int( properties, "colorspace", colorspace );
757 // Set options controlled by MLT
758 c->width = mlt_properties_get_int( properties, "width" );
759 c->height = mlt_properties_get_int( properties, "height" );
760 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
761 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
762 if ( st->time_base.den == 0 )
763 st->time_base = c->time_base;
764 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
765 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
767 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
770 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
771 switch ( colorspace )
774 c->colorspace = AVCOL_SPC_SMPTE170M;
777 c->colorspace = AVCOL_SPC_SMPTE240M;
780 c->colorspace = AVCOL_SPC_BT470BG;
783 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
786 c->colorspace = AVCOL_SPC_BT709;
791 if ( mlt_properties_get( properties, "aspect" ) )
793 // "-aspect" on ffmpeg command line is display aspect ratio
794 double ar = mlt_properties_get_double( properties, "aspect" );
795 AVRational rational = av_d2q( ar, 255 );
797 // Update the profile and properties as well since this is an alias
798 // for mlt properties that correspond to profile settings
799 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
800 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
801 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
804 profile->display_aspect_num = rational.num;
805 profile->display_aspect_den = rational.den;
806 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
809 // Now compute the sample aspect ratio
810 rational = av_d2q( ar * c->height / c->width, 255 );
811 c->sample_aspect_ratio = rational;
812 // Update the profile and properties as well since this is an alias
813 // for mlt properties that correspond to profile settings
814 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
815 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
818 profile->sample_aspect_num = rational.num;
819 profile->sample_aspect_den = rational.den;
820 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
825 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
826 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
828 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
829 st->sample_aspect_ratio = c->sample_aspect_ratio;
832 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
834 c->flags |= CODEC_FLAG_QSCALE;
835 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
836 #if LIBAVFORMAT_VERSION_MAJOR < 53
837 st->quality = c->global_quality;
841 // Allow the user to override the video fourcc
842 if ( mlt_properties_get( properties, "vtag" ) )
845 const char *arg = mlt_properties_get( properties, "vtag" );
846 int tag = strtol( arg, &tail, 0);
848 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
852 // Some formats want stream headers to be seperate
853 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
854 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
856 // Translate these standard mlt consumer properties to ffmpeg
857 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
858 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
860 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
861 c->flags |= CODEC_FLAG_INTERLACED_DCT;
862 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
863 c->flags |= CODEC_FLAG_INTERLACED_ME;
866 // parse the ratecontrol override string
868 char *rc_override = mlt_properties_get( properties, "rc_override" );
869 for ( i = 0; rc_override; i++ )
872 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
874 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
875 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
876 c->rc_override[i].start_frame = start;
877 c->rc_override[i].end_frame = end;
880 c->rc_override[i].qscale = q;
881 c->rc_override[i].quality_factor = 1.0;
885 c->rc_override[i].qscale = 0;
886 c->rc_override[i].quality_factor = -q / 100.0;
888 rc_override = strchr( rc_override, '/' );
892 c->rc_override_count = i;
893 if ( !c->rc_initial_buffer_occupancy )
894 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
895 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
898 i = mlt_properties_get_int( properties, "pass" );
900 c->flags |= CODEC_FLAG_PASS1;
902 c->flags |= CODEC_FLAG_PASS2;
903 if ( codec->id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
905 char logfilename[1024];
910 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
911 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
912 if ( c->flags & CODEC_FLAG_PASS1 )
914 f = fopen( logfilename, "w" );
916 perror( logfilename );
918 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
922 /* read the log file */
923 f = fopen( logfilename, "r" );
930 mlt_properties_set( properties, "_logfilename", logfilename );
931 fseek( f, 0, SEEK_END );
933 fseek( f, 0, SEEK_SET );
934 logbuffer = av_malloc( size + 1 );
936 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
939 size = fread( logbuffer, 1, size, f );
941 logbuffer[size] = '\0';
942 c->stats_in = logbuffer;
950 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
956 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
959 AVFrame *picture = avcodec_alloc_frame();
961 // Determine size of the
962 int size = avpicture_get_size(pix_fmt, width, height);
964 // Allocate the picture buf
965 uint8_t *picture_buf = av_malloc(size);
967 // If we have both, then fill the image
968 if ( picture != NULL && picture_buf != NULL )
970 // Fill the frame with the allocated buffer
971 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
975 // Something failed - clean up what we can
977 av_free( picture_buf );
984 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
987 AVCodecContext *video_enc = st->codec;
989 // find the video encoder
992 codec = avcodec_find_encoder_by_name( codec_name );
994 codec = avcodec_find_encoder( video_enc->codec_id );
996 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
997 // Process properties as AVOptions on the AVCodec
998 if ( codec && codec->priv_class )
1000 char *vpre = mlt_properties_get( properties, "vpre" );
1001 if ( !video_enc->priv_data && codec->priv_data_size )
1003 video_enc->priv_data = av_mallocz( codec->priv_data_size );
1004 *(const AVClass **) video_enc->priv_data = codec->priv_class;
1005 // av_opt_set_defaults( video_enc );
1009 mlt_properties p = mlt_properties_load( vpre );
1010 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1011 mlt_properties_close( p );
1013 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
1017 if( codec && codec->pix_fmts )
1019 const enum PixelFormat *p = codec->pix_fmts;
1020 for( ; *p!=-1; p++ )
1022 if( *p == video_enc->pix_fmt )
1026 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
1029 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1030 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
1032 int result = codec && avcodec_open( video_enc, codec ) >= 0;
1038 void close_video(AVFormatContext *oc, AVStream *st)
1040 if ( st && st->codec )
1042 av_freep( &st->codec->stats_in );
1043 avcodec_close(st->codec);
1047 static inline long time_difference( struct timeval *time1 )
1049 struct timeval time2;
1050 gettimeofday( &time2, NULL );
1051 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1054 static int mlt_write(void *h, uint8_t *buf, int size)
1056 mlt_properties properties = (mlt_properties) h;
1057 mlt_events_fire( properties, "avformat-write", buf, size, NULL );
1061 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1063 listener( owner, service, (uint8_t*) args[0], (int) args[1] );
1067 /** The main thread - the argument is simply the consumer.
1070 static void *consumer_thread( void *arg )
1072 // Map the argument to the object
1073 mlt_consumer consumer = arg;
1075 // Get the properties
1076 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1078 // Get the terminate on pause property
1079 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1082 // Determine if feed is slow (for realtime stuff)
1083 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1086 struct timeval ante;
1088 // Get the frame rate
1089 double fps = mlt_properties_get_double( properties, "fps" );
1091 // Get width and height
1092 int width = mlt_properties_get_int( properties, "width" );
1093 int height = mlt_properties_get_int( properties, "height" );
1094 int img_width = width;
1095 int img_height = height;
1097 // Get default audio properties
1098 int channels = mlt_properties_get_int( properties, "channels" );
1099 int total_channels = channels;
1100 int frequency = mlt_properties_get_int( properties, "frequency" );
1104 // AVFormat audio buffer and frame size
1105 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1106 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1107 int audio_input_frame_size = 0;
1109 // AVFormat video buffer and frame count
1110 int frame_count = 0;
1111 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1112 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1114 // Used for the frame properties
1115 mlt_frame frame = NULL;
1116 mlt_properties frame_properties = NULL;
1119 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1120 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1122 // Need two av pictures for converting
1123 AVFrame *output = NULL;
1124 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
1126 // For receiving images from an mlt_frame
1128 mlt_image_format img_fmt = mlt_image_yuv422;
1130 // For receiving audio samples back from the fifo
1131 uint8_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1132 uint8_t *audio_buf_2 = NULL;
1135 // Allocate the context
1136 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
1137 AVFormatContext *oc = avformat_alloc_context( );
1139 AVFormatContext *oc = av_alloc_format_context( );
1143 AVStream *video_st = NULL;
1144 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1147 double audio_pts = 0;
1148 double video_pts = 0;
1150 // Frames dispatched
1151 long int frames = 0;
1152 long int total_time = 0;
1154 // Determine the format
1155 AVOutputFormat *fmt = NULL;
1156 const char *filename = mlt_properties_get( properties, "target" );
1157 char *format = mlt_properties_get( properties, "f" );
1158 char *vcodec = mlt_properties_get( properties, "vcodec" );
1159 char *acodec = mlt_properties_get( properties, "acodec" );
1160 AVCodec *audio_codec = NULL;
1161 AVCodec *video_codec = NULL;
1163 // Used to store and override codec ids
1169 mlt_properties frame_meta_properties = mlt_properties_new();
1171 // Initialize audio_st
1172 int i = MAX_AUDIO_STREAMS;
1176 // Check for user selected format first
1177 if ( format != NULL )
1178 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1179 fmt = guess_format( format, NULL, NULL );
1181 fmt = av_guess_format( format, NULL, NULL );
1184 // Otherwise check on the filename
1185 if ( fmt == NULL && filename != NULL )
1186 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1187 fmt = guess_format( NULL, filename, NULL );
1189 fmt = av_guess_format( NULL, filename, NULL );
1192 // Otherwise default to mpeg
1194 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1195 fmt = guess_format( "mpeg", NULL, NULL );
1197 fmt = av_guess_format( "mpeg", NULL, NULL );
1200 // We need a filename - default to stdout?
1201 if ( filename == NULL || !strcmp( filename, "" ) )
1204 // Get the codec ids selected
1205 audio_codec_id = fmt->audio_codec;
1206 video_codec_id = fmt->video_codec;
1208 // Check for audio codec overides
1209 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1210 audio_codec_id = CODEC_ID_NONE;
1213 audio_codec = avcodec_find_encoder_by_name( acodec );
1216 audio_codec_id = audio_codec->id;
1217 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1219 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1220 acodec = mlt_properties_get( properties, "_acodec" );
1221 audio_codec = avcodec_find_encoder_by_name( acodec );
1223 else if ( !strcmp( acodec, "aac" ) )
1225 mlt_properties_set( properties, "astrict", "experimental" );
1230 audio_codec_id = CODEC_ID_NONE;
1231 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1236 audio_codec = avcodec_find_encoder( audio_codec_id );
1239 // Check for video codec overides
1240 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1241 video_codec_id = CODEC_ID_NONE;
1244 video_codec = avcodec_find_encoder_by_name( vcodec );
1247 video_codec_id = video_codec->id;
1251 video_codec_id = CODEC_ID_NONE;
1252 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1257 video_codec = avcodec_find_encoder( video_codec_id );
1261 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1262 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1264 char *name = mlt_properties_get_name( properties, i );
1265 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1267 char *key = strdup( name + 10 );
1268 char *markup = strrchr( key, '.' );
1269 if ( markup && !strcmp( markup, ".markup") )
1272 if ( !strstr( key, ".stream." ) )
1273 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1274 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1275 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1277 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1280 av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1290 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1291 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1293 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1294 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1296 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1297 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1299 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1300 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1302 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1303 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1305 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1306 if (metavalue != 0) oc->year = metavalue;
1308 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1309 if (metavalue != 0) oc->track = metavalue;
1313 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1315 // Get a frame now, so we can set some AVOptions from properties.
1316 frame = mlt_consumer_rt_frame( consumer );
1318 // Set the timecode from the MLT metadata if available.
1321 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1322 if ( timecode && strcmp( timecode, "" ) )
1324 mlt_properties_set( properties, "timecode", timecode );
1325 if ( strchr( timecode, ';' ) )
1326 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1330 // Add audio and video streams
1331 if ( video_codec_id != CODEC_ID_NONE )
1332 video_st = add_video_stream( consumer, oc, video_codec );
1333 if ( audio_codec_id != CODEC_ID_NONE )
1339 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1341 sprintf( key, "channels.%d", i );
1342 int j = mlt_properties_get_int( properties, key );
1346 total_channels += j;
1347 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1353 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1354 total_channels = channels;
1357 mlt_properties_set_int( properties, "channels", total_channels );
1359 // Audio format is determined when adding the audio stream
1360 mlt_audio_format aud_fmt = mlt_audio_none;
1362 aud_fmt = get_mlt_audio_format( audio_st[0]->codec->sample_fmt );
1363 int sample_bytes = mlt_audio_format_size( aud_fmt, 1, 1 );
1364 sample_bytes = sample_bytes ? sample_bytes : 1; // prevent divide by zero
1366 // Set the parameters (even though we have none...)
1367 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1368 if ( av_set_parameters(oc, NULL) >= 0 )
1371 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1372 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1373 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1375 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1377 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1379 // Process properties as AVOptions
1380 char *fpre = mlt_properties_get( properties, "fpre" );
1383 mlt_properties p = mlt_properties_load( fpre );
1384 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1385 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1386 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1387 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1389 mlt_properties_close( p );
1391 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1392 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1393 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1394 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1397 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1399 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1401 audio_input_frame_size = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1402 acodec? acodec : NULL );
1403 if ( !audio_input_frame_size )
1407 // Setup custom I/O if redirecting
1408 if ( mlt_properties_get_int( properties, "redirect" ) )
1410 int buffer_size = 32768;
1411 unsigned char *buffer = av_malloc( buffer_size );
1412 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1413 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1415 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1420 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1421 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1423 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1424 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1425 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1430 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1433 // Open the output file, if needed
1434 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1436 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1437 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1439 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1442 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1443 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1444 goto on_fatal_error;
1448 // Write the stream header.
1449 if ( mlt_properties_get_int( properties, "running" ) )
1450 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1451 avformat_write_header( oc, NULL );
1453 av_write_header( oc );
1456 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1459 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1460 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1461 goto on_fatal_error;
1467 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1469 // Last check - need at least one stream
1470 if ( !audio_st[0] && !video_st )
1472 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1473 goto on_fatal_error;
1476 // Get the starting time (can ignore the times above)
1477 gettimeofday( &ante, NULL );
1479 // Loop while running
1480 while( mlt_properties_get_int( properties, "running" ) &&
1481 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1484 frame = mlt_consumer_rt_frame( consumer );
1486 // Check that we have a frame to work with
1487 if ( frame != NULL )
1489 // Increment frames dispatched
1492 // Default audio args
1493 frame_properties = MLT_FRAME_PROPERTIES( frame );
1495 // Check for the terminated condition
1496 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1498 // Get audio and append to the fifo
1499 if ( !terminated && audio_st[0] )
1501 samples = mlt_sample_calculator( fps, frequency, count ++ );
1502 channels = total_channels;
1503 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
1505 // Save the audio channel remap properties for later
1506 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1508 // Create the fifo if we don't have one
1511 fifo = sample_fifo_init( frequency, channels );
1512 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1516 // Silence if not normal forward speed
1517 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1518 memset( pcm, 0, samples * channels * sample_bytes );
1520 // Append the samples
1521 sample_fifo_append( fifo, pcm, samples * channels * sample_bytes );
1522 total_time += ( samples * 1000000 ) / frequency;
1525 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1529 if ( !terminated && video_st )
1530 mlt_deque_push_back( queue, frame );
1532 mlt_frame_close( frame );
1536 // While we have stuff to process, process...
1539 // Write interleaved audio and video frames
1540 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1543 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) / sample_bytes )
1545 int j = 0; // channel offset into interleaved source buffer
1546 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) / sample_bytes ), AUDIO_ENCODE_BUFFER_SIZE );
1548 // Get the audio samples
1551 sample_fifo_fetch( fifo, audio_buf_1, n * sample_bytes );
1553 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1555 // This prevents an infinite loop when some versions of vorbis do not
1556 // increment pts when encoding silence.
1557 audio_pts = video_pts;
1562 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1564 samples = n / channels;
1566 // For each output stream
1567 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1569 AVStream *stream = audio_st[i];
1570 AVCodecContext *codec = stream->codec;
1573 av_init_packet( &pkt );
1575 // Optimized for single track and no channel remap
1576 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1578 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_1 );
1582 // Extract the audio channels according to channel mapping
1583 int dest_offset = 0; // channel offset into interleaved dest buffer
1585 // Get the number of channels for this stream
1586 sprintf( key, "channels.%d", i );
1587 int current_channels = mlt_properties_get_int( properties, key );
1589 // Clear the destination audio buffer.
1591 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1593 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1595 // For each output channel
1596 while ( dest_offset < current_channels && j < total_channels )
1598 int map_start = -1, map_channels = 0;
1599 int source_offset = 0;
1602 // Look for a mapping that starts at j
1603 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1605 sprintf( key, "%d.channels", k );
1606 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1607 sprintf( key, "%d.start", k );
1608 if ( mlt_properties_get( frame_meta_properties, key ) )
1609 map_start = mlt_properties_get_int( frame_meta_properties, key );
1610 if ( map_start != j )
1611 source_offset += map_channels;
1615 if ( map_start != j )
1617 map_channels = current_channels;
1621 // Copy samples if source offset valid
1622 if ( source_offset < channels )
1624 // Interleave the audio buffer with the # channels for this stream/mapping.
1625 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1627 void *src = audio_buf_1 + source_offset * sample_bytes;
1628 void *dest = audio_buf_2 + dest_offset * sample_bytes;
1629 int s = samples + 1;
1632 memcpy( dest, src, sample_bytes );
1633 dest += current_channels * sample_bytes;
1634 src += channels * sample_bytes;
1638 // Otherwise silence
1641 j += current_channels;
1642 dest_offset += current_channels;
1645 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, (short*) audio_buf_2 );
1648 // Write the compressed frame in the media file
1649 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1651 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1652 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame pts %"PRId64,
1653 stream->index, pkt.pts, codec->coded_frame->pts );
1655 pkt.flags |= PKT_FLAG_KEY;
1656 pkt.stream_index = stream->index;
1657 pkt.data = audio_outbuf;
1661 if ( av_interleaved_write_frame( oc, &pkt ) )
1663 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1664 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1665 goto on_fatal_error;
1669 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1672 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1681 else if ( video_st )
1684 if ( mlt_deque_count( queue ) )
1686 int out_size, ret = 0;
1689 frame = mlt_deque_pop_front( queue );
1690 frame_properties = MLT_FRAME_PROPERTIES( frame );
1692 c = video_st->codec;
1694 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1700 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1704 // Convert the mlt frame to an AVPicture
1705 for ( i = 0; i < height; i ++ )
1707 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1708 memcpy( p, q, width * 2 );
1712 // Do the colour space conversion
1714 int flags = SWS_BICUBIC;
1716 flags |= SWS_CPU_CAPS_MMX;
1719 flags |= SWS_CPU_CAPS_MMX2;
1721 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1722 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1723 sws_scale( context, (const uint8_t* const*) input->data, input->linesize, 0, height,
1724 output->data, output->linesize);
1725 sws_freeContext( context );
1727 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1730 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1732 // Apply the alpha if applicable
1733 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1735 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1738 for ( i = 0; i < height; i ++ )
1740 n = ( width + 7 ) / 8;
1741 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1745 case 0: do { *p = *alpha++; p += 4;
1746 case 7: *p = *alpha++; p += 4;
1747 case 6: *p = *alpha++; p += 4;
1748 case 5: *p = *alpha++; p += 4;
1749 case 4: *p = *alpha++; p += 4;
1750 case 3: *p = *alpha++; p += 4;
1751 case 2: *p = *alpha++; p += 4;
1752 case 1: *p = *alpha++; p += 4;
1760 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1762 // raw video case. The API will change slightly in the near future for that
1764 av_init_packet(&pkt);
1766 pkt.flags |= PKT_FLAG_KEY;
1767 pkt.stream_index= video_st->index;
1768 pkt.data= (uint8_t *)output;
1769 pkt.size= sizeof(AVPicture);
1771 ret = av_write_frame(oc, &pkt);
1772 video_pts += c->frame_size;
1777 output->quality = c->global_quality;
1779 // Set frame interlace hints
1780 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1781 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1782 output->pts = frame_count;
1785 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1787 // If zero size, it means the image was buffered
1791 av_init_packet( &pkt );
1793 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1794 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1795 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %"PRId64" frame pts %"PRId64, pkt.pts, c->coded_frame->pts );
1796 if( c->coded_frame && c->coded_frame->key_frame )
1797 pkt.flags |= PKT_FLAG_KEY;
1798 pkt.stream_index= video_st->index;
1799 pkt.data= video_outbuf;
1802 // write the compressed frame in the media file
1803 ret = av_interleaved_write_frame(oc, &pkt);
1804 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1805 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1807 // Dual pass logging
1808 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1809 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1811 else if ( out_size < 0 )
1813 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1819 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1820 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1821 goto on_fatal_error;
1823 mlt_frame_close( frame );
1832 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1834 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1835 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1838 if ( real_time_output == 1 && frames % 2 == 0 )
1840 long passed = time_difference( &ante );
1843 long pending = ( ( ( long )sample_fifo_used( fifo ) / sample_bytes * 1000 ) / frequency ) * 1000;
1846 if ( passed < total_time )
1848 long total = ( total_time - passed );
1849 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1850 nanosleep( &t, NULL );
1855 // Flush the encoder buffers
1856 if ( real_time_output <= 0 )
1859 // TODO: flush all audio streams
1860 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1862 AVCodecContext *c = audio_st[0]->codec;
1864 av_init_packet( &pkt );
1868 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) / sample_bytes ) )
1870 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size * sample_bytes );
1871 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, (short*) audio_buf_1 );
1873 if ( pkt.size <= 0 )
1874 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1875 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1876 if ( pkt.size <= 0 )
1879 // Write the compressed frame in the media file
1880 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1881 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1882 pkt.flags |= PKT_FLAG_KEY;
1883 pkt.stream_index = audio_st[0]->index;
1884 pkt.data = audio_outbuf;
1885 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1887 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1888 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1889 goto on_fatal_error;
1894 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1896 AVCodecContext *c = video_st->codec;
1898 av_init_packet( &pkt );
1901 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1902 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1903 if ( pkt.size <= 0 )
1906 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1907 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1908 if( c->coded_frame && c->coded_frame->key_frame )
1909 pkt.flags |= PKT_FLAG_KEY;
1910 pkt.stream_index = video_st->index;
1911 pkt.data = video_outbuf;
1913 // write the compressed frame in the media file
1914 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1916 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1917 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1918 goto on_fatal_error;
1920 // Dual pass logging
1921 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1922 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1928 // Write the trailer, if any
1930 av_write_trailer( oc );
1934 close_video(oc, video_st);
1935 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1936 close_audio( oc, audio_st[i] );
1939 for ( i = 0; i < oc->nb_streams; i++ )
1940 av_freep( &oc->streams[i] );
1942 // Close the output file
1943 if ( !( fmt->flags & AVFMT_NOFILE ) &&
1944 !mlt_properties_get_int( properties, "redirect" ) )
1946 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1947 if ( oc->pb ) avio_close( oc->pb );
1948 #elif LIBAVFORMAT_VERSION_MAJOR >= 52
1949 if ( oc->pb ) url_fclose( oc->pb );
1951 url_fclose( &oc->pb );
1955 // Clean up input and output frames
1957 av_free( output->data[0] );
1959 av_free( input->data[0] );
1961 av_free( video_outbuf );
1962 av_free( audio_buf_1 );
1963 av_free( audio_buf_2 );
1968 // Just in case we terminated on pause
1969 mlt_consumer_stopped( consumer );
1970 mlt_properties_close( frame_meta_properties );
1972 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1974 // Remove the dual pass log file
1975 if ( mlt_properties_get( properties, "_logfilename" ) )
1976 remove( mlt_properties_get( properties, "_logfilename" ) );
1978 // Remove the x264 dual pass logs
1979 char *cwd = getcwd( NULL, 0 );
1980 const char *file = "x264_2pass.log";
1981 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1982 sprintf( full, "%s/%s", cwd, file );
1985 file = "x264_2pass.log.temp";
1986 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1987 sprintf( full, "%s/%s", cwd, file );
1990 file = "x264_2pass.log.mbtree";
1991 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1992 sprintf( full, "%s/%s", cwd, file );
1996 remove( "x264_2pass.log.temp" );
1999 while ( ( frame = mlt_deque_pop_back( queue ) ) )
2000 mlt_frame_close( frame );
2005 /** Close the consumer.
2008 static void consumer_close( mlt_consumer consumer )
2010 // Stop the consumer
2011 mlt_consumer_stop( consumer );
2014 mlt_consumer_close( consumer );