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)
51 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
52 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
55 #if LIBAVCODEC_VERSION_MAJOR >= 53
56 #include <libavutil/opt.h>
57 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
58 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
59 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
61 #include <libavcodec/opt.h>
64 #define MAX_AUDIO_STREAMS (8)
65 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
66 #define AUDIO_BUFFER_SIZE (1024 * 42)
67 #define VIDEO_BUFFER_SIZE (2048 * 1024)
70 // This structure should be extended and made globally available in mlt
82 *sample_fifo, sample_fifo_s;
84 sample_fifo sample_fifo_init( int frequency, int channels )
86 sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
87 fifo->frequency = frequency;
88 fifo->channels = channels;
92 // sample_fifo_clear and check are temporarily aborted (not working as intended)
94 void sample_fifo_clear( sample_fifo fifo, double time )
96 int words = ( float )( time - fifo->time ) * fifo->frequency * fifo->channels;
97 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )fifo->time * 100 ) && fifo->used > words && words > 0 )
99 memmove( fifo->buffer, &fifo->buffer[ words ], ( fifo->used - words ) * sizeof( int16_t ) );
103 else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )fifo->time * 100 ) )
110 void sample_fifo_check( sample_fifo fifo, double time )
112 if ( fifo->used == 0 )
114 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )fifo->time * 100 ) )
119 void sample_fifo_append( sample_fifo fifo, int16_t *samples, int count )
121 if ( ( fifo->size - fifo->used ) < count )
123 fifo->size += count * 5;
124 fifo->buffer = realloc( fifo->buffer, fifo->size * sizeof( int16_t ) );
127 memcpy( &fifo->buffer[ fifo->used ], samples, count * sizeof( int16_t ) );
131 int sample_fifo_used( sample_fifo fifo )
136 int sample_fifo_fetch( sample_fifo fifo, int16_t *samples, int count )
138 if ( count > fifo->used )
141 memcpy( samples, fifo->buffer, count * sizeof( int16_t ) );
143 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used * sizeof( int16_t ) );
145 fifo->time += ( double )count / fifo->channels / fifo->frequency;
150 void sample_fifo_close( sample_fifo fifo )
152 free( fifo->buffer );
156 // Forward references.
157 static int consumer_start( mlt_consumer consumer );
158 static int consumer_stop( mlt_consumer consumer );
159 static int consumer_is_stopped( mlt_consumer consumer );
160 static void *consumer_thread( void *arg );
161 static void consumer_close( mlt_consumer consumer );
163 /** Initialise the consumer.
166 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
168 // Allocate the consumer
169 mlt_consumer consumer = mlt_consumer_new( profile );
171 // If memory allocated and initialises without error
172 if ( consumer != NULL )
174 // Get properties from the consumer
175 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
177 // Assign close callback
178 consumer->close = consumer_close;
180 // Interpret the argument
182 mlt_properties_set( properties, "target", arg );
184 // sample and frame queue
185 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
187 // Audio options not fully handled by AVOptions
188 #define QSCALE_NONE (-99999)
189 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
191 // Video options not fully handled by AVOptions
192 mlt_properties_set_int( properties, "dc", 8 );
194 // Muxer options not fully handled by AVOptions
195 mlt_properties_set_double( properties, "muxdelay", 0.7 );
196 mlt_properties_set_double( properties, "muxpreload", 0.5 );
198 // Some AVOption defaults we like
199 mlt_properties_set( properties, "strict", "experimental" );
201 // Ensure termination at end of the stream
202 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
204 // Default to separate processing threads for producer and consumer with no frame dropping!
205 mlt_properties_set_int( properties, "real_time", -1 );
206 mlt_properties_set_int( properties, "prefill", 1 );
208 // Set up start/stop/terminated callbacks
209 consumer->start = consumer_start;
210 consumer->stop = consumer_stop;
211 consumer->is_stopped = consumer_is_stopped;
213 mlt_events_register( properties, "consumer-fatal-error", NULL );
220 /** Start the consumer.
223 static int consumer_start( mlt_consumer consumer )
225 // Get the properties
226 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
229 // Report information about available muxers and codecs as YAML Tiny
230 char *s = mlt_properties_get( properties, "f" );
231 if ( s && strcmp( s, "list" ) == 0 )
233 mlt_properties doc = mlt_properties_new();
234 mlt_properties formats = mlt_properties_new();
236 AVOutputFormat *format = NULL;
238 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
239 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
240 while ( ( format = av_oformat_next( format ) ) )
242 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
243 mlt_properties_set( formats, key, format->name );
245 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
246 mlt_properties_close( doc );
249 s = mlt_properties_get( properties, "acodec" );
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, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
258 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
259 while ( ( codec = av_codec_next( codec ) ) )
260 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
262 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
263 mlt_properties_set( codecs, key, codec->name );
265 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
266 mlt_properties_close( doc );
269 s = mlt_properties_get( properties, "vcodec" );
270 if ( s && strcmp( s, "list" ) == 0 )
272 mlt_properties doc = mlt_properties_new();
273 mlt_properties codecs = mlt_properties_new();
275 AVCodec *codec = NULL;
277 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
278 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
279 while ( ( codec = av_codec_next( codec ) ) )
280 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
282 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
283 mlt_properties_set( codecs, key, codec->name );
285 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
286 mlt_properties_close( doc );
290 // Check that we're not already running
291 if ( !error && !mlt_properties_get_int( properties, "running" ) )
294 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
296 // Get the width and height
297 int width = mlt_properties_get_int( properties, "width" );
298 int height = mlt_properties_get_int( properties, "height" );
300 // Obtain the size property
301 char *size = mlt_properties_get( properties, "s" );
307 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
314 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Invalid size property %s - ignoring.\n", size );
318 // Now ensure we honour the multiple of two requested by libavformat
319 width = ( width / 2 ) * 2;
320 height = ( height / 2 ) * 2;
321 mlt_properties_set_int( properties, "width", width );
322 mlt_properties_set_int( properties, "height", height );
324 // We need to set these on the profile as well because the s property is
325 // an alias to mlt properties that correspond to profile settings.
326 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
329 profile->width = width;
330 profile->height = height;
333 // Handle the ffmpeg command line "-r" property for frame rate
334 if ( mlt_properties_get( properties, "r" ) )
336 double frame_rate = mlt_properties_get_double( properties, "r" );
337 AVRational rational = av_d2q( frame_rate, 255 );
338 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
339 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
342 profile->frame_rate_num = rational.num;
343 profile->frame_rate_den = rational.den;
344 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
348 // Apply AVOptions that are synonyms for standard mlt_consumer options
349 if ( mlt_properties_get( properties, "ac" ) )
350 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
351 if ( mlt_properties_get( properties, "ar" ) )
352 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
354 // Assign the thread to properties
355 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
357 // Set the running state
358 mlt_properties_set_int( properties, "running", 1 );
361 pthread_create( thread, NULL, consumer_thread, consumer );
366 /** Stop the consumer.
369 static int consumer_stop( mlt_consumer consumer )
371 // Get the properties
372 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
374 // Check that we're running
375 if ( mlt_properties_get_int( properties, "running" ) )
378 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
381 mlt_properties_set_int( properties, "running", 0 );
383 // Wait for termination
384 pthread_join( *thread, NULL );
390 /** Determine if the consumer is stopped.
393 static int consumer_is_stopped( mlt_consumer consumer )
395 // Get the properties
396 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
397 return !mlt_properties_get_int( properties, "running" );
400 /** Process properties as AVOptions and apply to AV context obj
403 static void apply_properties( void *obj, mlt_properties properties, int flags )
406 int count = mlt_properties_count( properties );
407 #if LIBAVUTIL_VERSION_INT < ((51<<16)+(12<<8)+0)
411 for ( i = 0; i < count; i++ )
413 const char *opt_name = mlt_properties_get_name( properties, i );
414 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(7<<8)+0)
415 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
417 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
420 // If option not found, see if it was prefixed with a or v (-vb)
422 ( opt_name[0] == 'v' && ( flags & AV_OPT_FLAG_VIDEO_PARAM ) ) ||
423 ( opt_name[0] == 'a' && ( flags & AV_OPT_FLAG_AUDIO_PARAM ) ) ) )
424 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(7<<8)+0)
425 opt = av_opt_find( obj, ++opt_name, NULL, flags, flags );
427 opt = av_find_opt( obj, ++opt_name, NULL, flags, flags );
429 // Apply option if found
431 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
432 av_opt_set( obj, opt_name, mlt_properties_get_value( properties, i), 0 );
433 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
434 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
435 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
436 av_set_string2( obj, opt_name, mlt_properties_get_value( properties, i), alloc );
438 av_set_string( obj, opt_name, mlt_properties_get_value( properties, i) );
443 /** Add an audio output stream
446 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec, int channels )
448 // Get the properties
449 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
451 // Create a new stream
452 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
453 AVStream *st = avformat_new_stream( oc, codec );
455 AVStream *st = av_new_stream( oc, oc->nb_streams );
458 // If created, then initialise from properties
461 AVCodecContext *c = st->codec;
463 // Establish defaults from AVOptions
464 #if LIBAVCODEC_VERSION_MAJOR >= 53
465 avcodec_get_context_defaults3( c, codec );
467 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
470 c->codec_id = codec->id;
471 c->codec_type = CODEC_TYPE_AUDIO;
472 c->sample_fmt = SAMPLE_FMT_S16;
474 #if 0 // disabled until some audio codecs are multi-threaded
475 // Setup multi-threading
476 int thread_count = mlt_properties_get_int( properties, "threads" );
477 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
478 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
479 if ( thread_count > 1 )
480 c->thread_count = thread_count;
483 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
484 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
486 // Allow the user to override the audio fourcc
487 if ( mlt_properties_get( properties, "atag" ) )
490 char *arg = mlt_properties_get( properties, "atag" );
491 int tag = strtol( arg, &tail, 0);
493 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
497 // Process properties as AVOptions
498 char *apre = mlt_properties_get( properties, "apre" );
501 mlt_properties p = mlt_properties_load( apre );
502 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
503 mlt_properties_close( p );
505 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
507 int audio_qscale = mlt_properties_get_int( properties, "aq" );
508 if ( audio_qscale > QSCALE_NONE )
510 c->flags |= CODEC_FLAG_QSCALE;
511 c->global_quality = FF_QP2LAMBDA * audio_qscale;
512 #if LIBAVFORMAT_VERSION_MAJOR < 53
513 st->quality = c->global_quality;
517 // Set parameters controlled by MLT
518 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
519 c->time_base = ( AVRational ){ 1, c->sample_rate };
520 c->channels = channels;
522 if ( mlt_properties_get( properties, "alang" ) != NULL )
523 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
524 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
525 av_dict_set( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
527 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
531 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
536 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
542 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
544 // We will return the audio input size from here
545 int audio_input_frame_size = 0;
548 AVCodecContext *c = st->codec;
553 codec = avcodec_find_encoder_by_name( codec_name );
555 codec = avcodec_find_encoder( c->codec_id );
557 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
558 // Process properties as AVOptions on the AVCodec
559 if ( codec && codec->priv_class )
561 char *apre = mlt_properties_get( properties, "apre" );
562 if ( !c->priv_data && codec->priv_data_size )
564 c->priv_data = av_mallocz( codec->priv_data_size );
565 *(const AVClass **) c->priv_data = codec->priv_class;
566 // av_opt_set_defaults( c );
570 mlt_properties p = mlt_properties_load( apre );
571 apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
572 mlt_properties_close( p );
574 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
578 // Continue if codec found and we can open it
579 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
580 if ( codec && avcodec_open2( c, codec, NULL ) >= 0 )
582 if ( codec && avcodec_open( c, codec ) >= 0 )
585 // ugly hack for PCM codecs (will be removed ASAP with new PCM
586 // support to compute the input frame size in samples
587 if ( c->frame_size <= 1 )
589 audio_input_frame_size = audio_outbuf_size / c->channels;
590 switch(st->codec->codec_id)
592 case CODEC_ID_PCM_S16LE:
593 case CODEC_ID_PCM_S16BE:
594 case CODEC_ID_PCM_U16LE:
595 case CODEC_ID_PCM_U16BE:
596 audio_input_frame_size >>= 1;
604 audio_input_frame_size = c->frame_size;
607 // Some formats want stream headers to be seperate (hmm)
608 if ( !strcmp( oc->oformat->name, "mp4" ) ||
609 !strcmp( oc->oformat->name, "mov" ) ||
610 !strcmp( oc->oformat->name, "3gp" ) )
611 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
615 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
618 return audio_input_frame_size;
621 static void close_audio( AVFormatContext *oc, AVStream *st )
623 if ( st && st->codec )
624 avcodec_close( st->codec );
627 /** Add a video output stream
630 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
632 // Get the properties
633 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
635 // Create a new stream
636 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
637 AVStream *st = avformat_new_stream( oc, codec );
639 AVStream *st = av_new_stream( oc, oc->nb_streams );
644 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
645 AVCodecContext *c = st->codec;
647 // Establish defaults from AVOptions
648 #if LIBAVCODEC_VERSION_MAJOR >= 53
649 avcodec_get_context_defaults3( c, codec );
651 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
654 c->codec_id = codec->id;
655 c->codec_type = CODEC_TYPE_VIDEO;
657 // Setup multi-threading
658 int thread_count = mlt_properties_get_int( properties, "threads" );
659 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
660 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
661 if ( thread_count > 1 )
662 #if LIBAVCODEC_VERSION_MAJOR >= 53
663 c->thread_count = thread_count;
665 avcodec_thread_init( c, thread_count );
668 // Process properties as AVOptions
669 char *vpre = mlt_properties_get( properties, "vpre" );
672 mlt_properties p = mlt_properties_load( vpre );
674 if ( mlt_properties_count( p ) < 1 )
676 AVCodec *codec = avcodec_find_encoder( c->codec_id );
679 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
680 strcpy( path, AVDATADIR );
681 strcat( path, codec->name );
683 strcat( path, vpre );
684 strcat( path, ".ffpreset" );
686 mlt_properties_close( p );
687 p = mlt_properties_load( path );
688 if ( mlt_properties_count( p ) > 0 )
689 mlt_properties_debug( p, path, stderr );
695 mlt_properties_debug( p, vpre, stderr );
698 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
699 mlt_properties_close( p );
701 int colorspace = mlt_properties_get_int( properties, "colorspace" );
702 mlt_properties_set( properties, "colorspace", NULL );
703 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
704 mlt_properties_set_int( properties, "colorspace", colorspace );
706 // Set options controlled by MLT
707 c->width = mlt_properties_get_int( properties, "width" );
708 c->height = mlt_properties_get_int( properties, "height" );
709 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
710 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
711 if ( st->time_base.den == 0 )
712 st->time_base = c->time_base;
713 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
714 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
716 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
719 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
720 switch ( colorspace )
723 c->colorspace = AVCOL_SPC_SMPTE170M;
726 c->colorspace = AVCOL_SPC_SMPTE240M;
729 c->colorspace = AVCOL_SPC_BT470BG;
732 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
735 c->colorspace = AVCOL_SPC_BT709;
740 if ( mlt_properties_get( properties, "aspect" ) )
742 // "-aspect" on ffmpeg command line is display aspect ratio
743 double ar = mlt_properties_get_double( properties, "aspect" );
744 AVRational rational = av_d2q( ar, 255 );
746 // Update the profile and properties as well since this is an alias
747 // for mlt properties that correspond to profile settings
748 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
749 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
750 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
753 profile->display_aspect_num = rational.num;
754 profile->display_aspect_den = rational.den;
755 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
758 // Now compute the sample aspect ratio
759 rational = av_d2q( ar * c->height / c->width, 255 );
760 c->sample_aspect_ratio = rational;
761 // Update the profile and properties as well since this is an alias
762 // for mlt properties that correspond to profile settings
763 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
764 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
767 profile->sample_aspect_num = rational.num;
768 profile->sample_aspect_den = rational.den;
769 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
774 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
775 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
777 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
778 st->sample_aspect_ratio = c->sample_aspect_ratio;
781 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
783 c->flags |= CODEC_FLAG_QSCALE;
784 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
785 #if LIBAVFORMAT_VERSION_MAJOR < 53
786 st->quality = c->global_quality;
790 // Allow the user to override the video fourcc
791 if ( mlt_properties_get( properties, "vtag" ) )
794 const char *arg = mlt_properties_get( properties, "vtag" );
795 int tag = strtol( arg, &tail, 0);
797 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
801 // Some formats want stream headers to be seperate
802 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
803 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
805 // Translate these standard mlt consumer properties to ffmpeg
806 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
807 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
809 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
810 c->flags |= CODEC_FLAG_INTERLACED_DCT;
811 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
812 c->flags |= CODEC_FLAG_INTERLACED_ME;
815 // parse the ratecontrol override string
817 char *rc_override = mlt_properties_get( properties, "rc_override" );
818 for ( i = 0; rc_override; i++ )
821 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
823 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
824 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
825 c->rc_override[i].start_frame = start;
826 c->rc_override[i].end_frame = end;
829 c->rc_override[i].qscale = q;
830 c->rc_override[i].quality_factor = 1.0;
834 c->rc_override[i].qscale = 0;
835 c->rc_override[i].quality_factor = -q / 100.0;
837 rc_override = strchr( rc_override, '/' );
841 c->rc_override_count = i;
842 if ( !c->rc_initial_buffer_occupancy )
843 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
844 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
847 i = mlt_properties_get_int( properties, "pass" );
849 c->flags |= CODEC_FLAG_PASS1;
851 c->flags |= CODEC_FLAG_PASS2;
852 if ( codec->id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
854 char logfilename[1024];
859 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
860 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
861 if ( c->flags & CODEC_FLAG_PASS1 )
863 f = fopen( logfilename, "w" );
865 perror( logfilename );
867 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
871 /* read the log file */
872 f = fopen( logfilename, "r" );
879 mlt_properties_set( properties, "_logfilename", logfilename );
880 fseek( f, 0, SEEK_END );
882 fseek( f, 0, SEEK_SET );
883 logbuffer = av_malloc( size + 1 );
885 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
888 size = fread( logbuffer, 1, size, f );
890 logbuffer[size] = '\0';
891 c->stats_in = logbuffer;
899 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
905 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
908 AVFrame *picture = avcodec_alloc_frame();
910 // Determine size of the
911 int size = avpicture_get_size(pix_fmt, width, height);
913 // Allocate the picture buf
914 uint8_t *picture_buf = av_malloc(size);
916 // If we have both, then fill the image
917 if ( picture != NULL && picture_buf != NULL )
919 // Fill the frame with the allocated buffer
920 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
924 // Something failed - clean up what we can
926 av_free( picture_buf );
933 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
936 AVCodecContext *video_enc = st->codec;
938 // find the video encoder
941 codec = avcodec_find_encoder_by_name( codec_name );
943 codec = avcodec_find_encoder( video_enc->codec_id );
945 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
946 // Process properties as AVOptions on the AVCodec
947 if ( codec && codec->priv_class )
949 char *vpre = mlt_properties_get( properties, "vpre" );
950 if ( !video_enc->priv_data && codec->priv_data_size )
952 video_enc->priv_data = av_mallocz( codec->priv_data_size );
953 *(const AVClass **) video_enc->priv_data = codec->priv_class;
954 // av_opt_set_defaults( video_enc );
958 mlt_properties p = mlt_properties_load( vpre );
959 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
960 mlt_properties_close( p );
962 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
966 if( codec && codec->pix_fmts )
968 const enum PixelFormat *p = codec->pix_fmts;
971 if( *p == video_enc->pix_fmt )
975 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
978 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
979 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
981 int result = codec && avcodec_open( video_enc, codec ) >= 0;
987 void close_video(AVFormatContext *oc, AVStream *st)
989 if ( st && st->codec )
991 av_freep( &st->codec->stats_in );
992 avcodec_close(st->codec);
996 static inline long time_difference( struct timeval *time1 )
998 struct timeval time2;
999 gettimeofday( &time2, NULL );
1000 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1003 static int mlt_write(void *h, uint8_t *buf, int size)
1005 mlt_properties properties = (mlt_properties) h;
1006 mlt_events_fire( properties, "avformat-write", buf, size, NULL );
1010 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1012 listener( owner, service, (uint8_t*) args[0], (int) args[1] );
1016 /** The main thread - the argument is simply the consumer.
1019 static void *consumer_thread( void *arg )
1021 // Map the argument to the object
1022 mlt_consumer consumer = arg;
1024 // Get the properties
1025 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1027 // Get the terminate on pause property
1028 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1031 // Determine if feed is slow (for realtime stuff)
1032 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1035 struct timeval ante;
1037 // Get the frame rate
1038 double fps = mlt_properties_get_double( properties, "fps" );
1040 // Get width and height
1041 int width = mlt_properties_get_int( properties, "width" );
1042 int height = mlt_properties_get_int( properties, "height" );
1043 int img_width = width;
1044 int img_height = height;
1046 // Get default audio properties
1047 mlt_audio_format aud_fmt = mlt_audio_s16;
1048 int channels = mlt_properties_get_int( properties, "channels" );
1049 int total_channels = channels;
1050 int frequency = mlt_properties_get_int( properties, "frequency" );
1051 int16_t *pcm = NULL;
1054 // AVFormat audio buffer and frame size
1055 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1056 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1057 int audio_input_frame_size = 0;
1059 // AVFormat video buffer and frame count
1060 int frame_count = 0;
1061 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1062 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1064 // Used for the frame properties
1065 mlt_frame frame = NULL;
1066 mlt_properties frame_properties = NULL;
1069 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1070 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1072 // Need two av pictures for converting
1073 AVFrame *output = NULL;
1074 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
1076 // For receiving images from an mlt_frame
1078 mlt_image_format img_fmt = mlt_image_yuv422;
1080 // For receiving audio samples back from the fifo
1081 int16_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1082 int16_t *audio_buf_2 = NULL;
1085 // Allocate the context
1086 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
1087 AVFormatContext *oc = avformat_alloc_context( );
1089 AVFormatContext *oc = av_alloc_format_context( );
1093 AVStream *video_st = NULL;
1094 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1097 double audio_pts = 0;
1098 double video_pts = 0;
1100 // Frames dispatched
1101 long int frames = 0;
1102 long int total_time = 0;
1104 // Determine the format
1105 AVOutputFormat *fmt = NULL;
1106 const char *filename = mlt_properties_get( properties, "target" );
1107 char *format = mlt_properties_get( properties, "f" );
1108 char *vcodec = mlt_properties_get( properties, "vcodec" );
1109 char *acodec = mlt_properties_get( properties, "acodec" );
1110 AVCodec *audio_codec = NULL;
1111 AVCodec *video_codec = NULL;
1113 // Used to store and override codec ids
1119 mlt_properties frame_meta_properties = mlt_properties_new();
1121 // Initialize audio_st
1122 int i = MAX_AUDIO_STREAMS;
1126 // Check for user selected format first
1127 if ( format != NULL )
1128 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1129 fmt = guess_format( format, NULL, NULL );
1131 fmt = av_guess_format( format, NULL, NULL );
1134 // Otherwise check on the filename
1135 if ( fmt == NULL && filename != NULL )
1136 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1137 fmt = guess_format( NULL, filename, NULL );
1139 fmt = av_guess_format( NULL, filename, NULL );
1142 // Otherwise default to mpeg
1144 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1145 fmt = guess_format( "mpeg", NULL, NULL );
1147 fmt = av_guess_format( "mpeg", NULL, NULL );
1150 // We need a filename - default to stdout?
1151 if ( filename == NULL || !strcmp( filename, "" ) )
1154 // Get the codec ids selected
1155 audio_codec_id = fmt->audio_codec;
1156 video_codec_id = fmt->video_codec;
1158 // Check for audio codec overides
1159 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1160 audio_codec_id = CODEC_ID_NONE;
1163 audio_codec = avcodec_find_encoder_by_name( acodec );
1166 audio_codec_id = audio_codec->id;
1167 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1169 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1170 acodec = mlt_properties_get( properties, "_acodec" );
1171 audio_codec = avcodec_find_encoder_by_name( acodec );
1176 audio_codec_id = CODEC_ID_NONE;
1177 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1182 audio_codec = avcodec_find_encoder( audio_codec_id );
1185 // Check for video codec overides
1186 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1187 video_codec_id = CODEC_ID_NONE;
1190 video_codec = avcodec_find_encoder_by_name( vcodec );
1193 video_codec_id = video_codec->id;
1197 video_codec_id = CODEC_ID_NONE;
1198 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1203 video_codec = avcodec_find_encoder( video_codec_id );
1207 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1208 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1210 char *name = mlt_properties_get_name( properties, i );
1211 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1213 char *key = strdup( name + 10 );
1214 char *markup = strrchr( key, '.' );
1215 if ( markup && !strcmp( markup, ".markup") )
1218 if ( !strstr( key, ".stream." ) )
1219 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1220 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1221 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1223 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1226 av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1236 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1237 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1239 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1240 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1242 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1243 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1245 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1246 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1248 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1249 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1251 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1252 if (metavalue != 0) oc->year = metavalue;
1254 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1255 if (metavalue != 0) oc->track = metavalue;
1259 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1261 // Get a frame now, so we can set some AVOptions from properties.
1262 frame = mlt_consumer_rt_frame( consumer );
1264 // Set the timecode from the MLT metadata if available.
1267 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1268 if ( timecode && strcmp( timecode, "" ) )
1270 mlt_properties_set( properties, "timecode", timecode );
1271 if ( strchr( timecode, ';' ) )
1272 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1276 // Add audio and video streams
1277 if ( video_codec_id != CODEC_ID_NONE )
1278 video_st = add_video_stream( consumer, oc, video_codec );
1279 if ( audio_codec_id != CODEC_ID_NONE )
1285 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1287 sprintf( key, "channels.%d", i );
1288 int j = mlt_properties_get_int( properties, key );
1292 total_channels += j;
1293 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1299 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1300 total_channels = channels;
1303 mlt_properties_set_int( properties, "channels", total_channels );
1305 // Set the parameters (even though we have none...)
1306 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1307 if ( av_set_parameters(oc, NULL) >= 0 )
1310 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1311 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1312 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1314 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1316 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1318 // Process properties as AVOptions
1319 char *fpre = mlt_properties_get( properties, "fpre" );
1322 mlt_properties p = mlt_properties_load( fpre );
1323 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1324 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1325 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1326 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1328 mlt_properties_close( p );
1330 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1331 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1332 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1333 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1336 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1338 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1340 audio_input_frame_size = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1341 acodec? acodec : NULL );
1342 if ( !audio_input_frame_size )
1346 // Setup custom I/O if redirecting
1347 if ( mlt_properties_get_int( properties, "redirect" ) )
1349 int buffer_size = 32768;
1350 unsigned char *buffer = av_malloc( buffer_size );
1351 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1352 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1354 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1359 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1360 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1362 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1363 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1364 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1369 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1372 // Open the output file, if needed
1373 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1375 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1376 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1378 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1381 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1382 mlt_properties_set_int( properties, "running", 0 );
1386 // Write the stream header.
1387 if ( mlt_properties_get_int( properties, "running" ) )
1388 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1389 avformat_write_header( oc, NULL );
1391 av_write_header( oc );
1394 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1397 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1398 mlt_properties_set_int( properties, "running", 0 );
1404 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1406 // Last check - need at least one stream
1407 if ( !audio_st[0] && !video_st )
1408 mlt_properties_set_int( properties, "running", 0 );
1410 // Get the starting time (can ignore the times above)
1411 gettimeofday( &ante, NULL );
1413 // Loop while running
1414 while( mlt_properties_get_int( properties, "running" ) &&
1415 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1418 frame = mlt_consumer_rt_frame( consumer );
1420 // Check that we have a frame to work with
1421 if ( frame != NULL )
1423 // Increment frames dispatched
1426 // Default audio args
1427 frame_properties = MLT_FRAME_PROPERTIES( frame );
1429 // Check for the terminated condition
1430 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1432 // Get audio and append to the fifo
1433 if ( !terminated && audio_st[0] )
1435 samples = mlt_sample_calculator( fps, frequency, count ++ );
1436 channels = total_channels;
1437 mlt_frame_get_audio( frame, (void**) &pcm, &aud_fmt, &frequency, &channels, &samples );
1439 // Save the audio channel remap properties for later
1440 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1442 // Create the fifo if we don't have one
1445 fifo = sample_fifo_init( frequency, channels );
1446 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1449 // Silence if not normal forward speed
1450 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1451 memset( pcm, 0, samples * channels * 2 );
1453 // Append the samples
1454 sample_fifo_append( fifo, pcm, samples * channels );
1455 total_time += ( samples * 1000000 ) / frequency;
1458 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1462 if ( !terminated && video_st )
1463 mlt_deque_push_back( queue, frame );
1465 mlt_frame_close( frame );
1469 // While we have stuff to process, process...
1472 // Write interleaved audio and video frames
1473 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1476 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1478 int j = 0; // channel offset into interleaved source buffer
1479 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) ), AUDIO_ENCODE_BUFFER_SIZE );
1481 // Get the audio samples
1484 sample_fifo_fetch( fifo, audio_buf_1, n );
1486 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1488 // This prevents an infinite loop when some versions of vorbis do not
1489 // increment pts when encoding silence.
1490 audio_pts = video_pts;
1495 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1497 samples = n / channels;
1499 // For each output stream
1500 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1502 AVStream *stream = audio_st[i];
1503 AVCodecContext *codec = stream->codec;
1506 av_init_packet( &pkt );
1508 // Optimized for single track and no channel remap
1509 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1511 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1515 // Extract the audio channels according to channel mapping
1516 int dest_offset = 0; // channel offset into interleaved dest buffer
1518 // Get the number of channels for this stream
1519 sprintf( key, "channels.%d", i );
1520 int current_channels = mlt_properties_get_int( properties, key );
1522 // Clear the destination audio buffer.
1524 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1526 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1528 // For each output channel
1529 while ( dest_offset < current_channels && j < total_channels )
1531 int map_start = -1, map_channels = 0;
1532 int source_offset = 0;
1535 // Look for a mapping that starts at j
1536 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1538 sprintf( key, "%d.channels", k );
1539 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1540 sprintf( key, "%d.start", k );
1541 if ( mlt_properties_get( frame_meta_properties, key ) )
1542 map_start = mlt_properties_get_int( frame_meta_properties, key );
1543 if ( map_start != j )
1544 source_offset += map_channels;
1548 if ( map_start != j )
1550 map_channels = current_channels;
1554 // Copy samples if source offset valid
1555 if ( source_offset < channels )
1557 // Interleave the audio buffer with the # channels for this stream/mapping.
1558 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1560 int16_t *src = audio_buf_1 + source_offset;
1561 int16_t *dest = audio_buf_2 + dest_offset;
1562 int s = samples + 1;
1566 dest += current_channels;
1571 // Otherwise silence
1574 j += current_channels;
1575 dest_offset += current_channels;
1578 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_2 );
1581 // Write the compressed frame in the media file
1582 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1584 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1585 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame pts %"PRId64,
1586 stream->index, pkt.pts, codec->coded_frame->pts );
1588 pkt.flags |= PKT_FLAG_KEY;
1589 pkt.stream_index = stream->index;
1590 pkt.data = audio_outbuf;
1594 if ( av_interleaved_write_frame( oc, &pkt ) )
1596 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1597 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1598 goto on_fatal_error;
1602 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1605 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1614 else if ( video_st )
1617 if ( mlt_deque_count( queue ) )
1619 int out_size, ret = 0;
1622 frame = mlt_deque_pop_front( queue );
1623 frame_properties = MLT_FRAME_PROPERTIES( frame );
1625 c = video_st->codec;
1627 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1633 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1637 // Convert the mlt frame to an AVPicture
1638 for ( i = 0; i < height; i ++ )
1640 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1641 memcpy( p, q, width * 2 );
1645 // Do the colour space conversion
1647 int flags = SWS_BILINEAR;
1649 flags |= SWS_CPU_CAPS_MMX;
1652 flags |= SWS_CPU_CAPS_MMX2;
1654 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1655 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1656 sws_scale( context, (const uint8_t* const*) input->data, input->linesize, 0, height,
1657 output->data, output->linesize);
1658 sws_freeContext( context );
1660 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1663 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1665 // Apply the alpha if applicable
1666 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1668 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1671 for ( i = 0; i < height; i ++ )
1673 n = ( width + 7 ) / 8;
1674 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1678 case 0: do { *p = *alpha++; p += 4;
1679 case 7: *p = *alpha++; p += 4;
1680 case 6: *p = *alpha++; p += 4;
1681 case 5: *p = *alpha++; p += 4;
1682 case 4: *p = *alpha++; p += 4;
1683 case 3: *p = *alpha++; p += 4;
1684 case 2: *p = *alpha++; p += 4;
1685 case 1: *p = *alpha++; p += 4;
1693 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1695 // raw video case. The API will change slightly in the near future for that
1697 av_init_packet(&pkt);
1699 pkt.flags |= PKT_FLAG_KEY;
1700 pkt.stream_index= video_st->index;
1701 pkt.data= (uint8_t *)output;
1702 pkt.size= sizeof(AVPicture);
1704 ret = av_write_frame(oc, &pkt);
1705 video_pts += c->frame_size;
1710 output->quality = c->global_quality;
1712 // Set frame interlace hints
1713 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1714 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1715 output->pts = frame_count;
1718 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1720 // If zero size, it means the image was buffered
1724 av_init_packet( &pkt );
1726 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1727 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1728 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %"PRId64" frame pts %"PRId64, pkt.pts, c->coded_frame->pts );
1729 if( c->coded_frame && c->coded_frame->key_frame )
1730 pkt.flags |= PKT_FLAG_KEY;
1731 pkt.stream_index= video_st->index;
1732 pkt.data= video_outbuf;
1735 // write the compressed frame in the media file
1736 ret = av_interleaved_write_frame(oc, &pkt);
1737 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1738 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1740 // Dual pass logging
1741 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1742 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1744 else if ( out_size < 0 )
1746 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1752 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1753 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1754 goto on_fatal_error;
1756 mlt_frame_close( frame );
1765 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1767 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1768 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1771 if ( real_time_output == 1 && frames % 2 == 0 )
1773 long passed = time_difference( &ante );
1776 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1779 if ( passed < total_time )
1781 long total = ( total_time - passed );
1782 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1783 nanosleep( &t, NULL );
1788 // Flush the encoder buffers
1789 if ( real_time_output <= 0 )
1792 // TODO: flush all audio streams
1793 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1795 AVCodecContext *c = audio_st[0]->codec;
1797 av_init_packet( &pkt );
1800 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1801 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1803 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size );
1804 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1806 if ( pkt.size <= 0 )
1807 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1808 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1809 if ( pkt.size <= 0 )
1812 // Write the compressed frame in the media file
1813 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1814 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1815 pkt.flags |= PKT_FLAG_KEY;
1816 pkt.stream_index = audio_st[0]->index;
1817 pkt.data = audio_outbuf;
1818 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1820 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1821 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1822 goto on_fatal_error;
1827 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1829 AVCodecContext *c = video_st->codec;
1831 av_init_packet( &pkt );
1834 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1835 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1836 if ( pkt.size <= 0 )
1839 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1840 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1841 if( c->coded_frame && c->coded_frame->key_frame )
1842 pkt.flags |= PKT_FLAG_KEY;
1843 pkt.stream_index = video_st->index;
1844 pkt.data = video_outbuf;
1846 // write the compressed frame in the media file
1847 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1849 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1850 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1851 goto on_fatal_error;
1853 // Dual pass logging
1854 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1855 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1861 // Write the trailer, if any
1862 av_write_trailer( oc );
1866 close_video(oc, video_st);
1867 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1868 close_audio( oc, audio_st[i] );
1871 for ( i = 0; i < oc->nb_streams; i++ )
1872 av_freep( &oc->streams[i] );
1874 // Close the output file
1875 if ( !( fmt->flags & AVFMT_NOFILE ) )
1877 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1878 if ( !mlt_properties_get_int( properties, "redirect" ) )
1879 avio_close( oc->pb );
1880 #elif LIBAVFORMAT_VERSION_MAJOR >= 52
1881 url_fclose( oc->pb );
1883 url_fclose( &oc->pb );
1887 // Clean up input and output frames
1889 av_free( output->data[0] );
1891 av_free( input->data[0] );
1893 av_free( video_outbuf );
1894 av_free( audio_buf_1 );
1895 av_free( audio_buf_2 );
1900 // Just in case we terminated on pause
1901 mlt_properties_set_int( properties, "running", 0 );
1903 mlt_consumer_stopped( consumer );
1904 mlt_properties_close( frame_meta_properties );
1906 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1908 // Remove the dual pass log file
1909 if ( mlt_properties_get( properties, "_logfilename" ) )
1910 remove( mlt_properties_get( properties, "_logfilename" ) );
1912 // Remove the x264 dual pass logs
1913 char *cwd = getcwd( NULL, 0 );
1914 const char *file = "x264_2pass.log";
1915 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1916 sprintf( full, "%s/%s", cwd, file );
1919 file = "x264_2pass.log.temp";
1920 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1921 sprintf( full, "%s/%s", cwd, file );
1924 file = "x264_2pass.log.mbtree";
1925 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1926 sprintf( full, "%s/%s", cwd, file );
1930 remove( "x264_2pass.log.temp" );
1933 while ( ( frame = mlt_deque_pop_back( queue ) ) )
1934 mlt_frame_close( frame );
1939 /** Close the consumer.
1942 static void consumer_close( mlt_consumer consumer )
1944 // Stop the consumer
1945 mlt_consumer_stop( consumer );
1948 mlt_consumer_close( consumer );