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)
69 void avformat_lock( );
70 void avformat_unlock( );
73 // This structure should be extended and made globally available in mlt
85 *sample_fifo, sample_fifo_s;
87 sample_fifo sample_fifo_init( int frequency, int channels )
89 sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
90 fifo->frequency = frequency;
91 fifo->channels = channels;
95 // sample_fifo_clear and check are temporarily aborted (not working as intended)
97 void sample_fifo_clear( sample_fifo fifo, double time )
99 int words = ( float )( time - fifo->time ) * fifo->frequency * fifo->channels;
100 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )fifo->time * 100 ) && fifo->used > words && words > 0 )
102 memmove( fifo->buffer, &fifo->buffer[ words ], ( fifo->used - words ) * sizeof( int16_t ) );
106 else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )fifo->time * 100 ) )
113 void sample_fifo_check( sample_fifo fifo, double time )
115 if ( fifo->used == 0 )
117 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )fifo->time * 100 ) )
122 void sample_fifo_append( sample_fifo fifo, int16_t *samples, int count )
124 if ( ( fifo->size - fifo->used ) < count )
126 fifo->size += count * 5;
127 fifo->buffer = realloc( fifo->buffer, fifo->size * sizeof( int16_t ) );
130 memcpy( &fifo->buffer[ fifo->used ], samples, count * sizeof( int16_t ) );
134 int sample_fifo_used( sample_fifo fifo )
139 int sample_fifo_fetch( sample_fifo fifo, int16_t *samples, int count )
141 if ( count > fifo->used )
144 memcpy( samples, fifo->buffer, count * sizeof( int16_t ) );
146 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used * sizeof( int16_t ) );
148 fifo->time += ( double )count / fifo->channels / fifo->frequency;
153 void sample_fifo_close( sample_fifo fifo )
155 free( fifo->buffer );
159 // Forward references.
160 static int consumer_start( mlt_consumer consumer );
161 static int consumer_stop( mlt_consumer consumer );
162 static int consumer_is_stopped( mlt_consumer consumer );
163 static void *consumer_thread( void *arg );
164 static void consumer_close( mlt_consumer consumer );
166 /** Initialise the consumer.
169 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
171 // Allocate the consumer
172 mlt_consumer consumer = mlt_consumer_new( profile );
174 // If memory allocated and initialises without error
175 if ( consumer != NULL )
177 // Get properties from the consumer
178 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
180 // Assign close callback
181 consumer->close = consumer_close;
183 // Interpret the argument
185 mlt_properties_set( properties, "target", arg );
187 // sample and frame queue
188 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
190 // Audio options not fully handled by AVOptions
191 #define QSCALE_NONE (-99999)
192 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
194 // Video options not fully handled by AVOptions
195 mlt_properties_set_int( properties, "dc", 8 );
197 // Muxer options not fully handled by AVOptions
198 mlt_properties_set_double( properties, "muxdelay", 0.7 );
199 mlt_properties_set_double( properties, "muxpreload", 0.5 );
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 );
580 // Continue if codec found and we can open it
581 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
582 if ( codec && avcodec_open2( c, codec, NULL ) >= 0 )
584 if ( codec && avcodec_open( c, codec ) >= 0 )
587 // ugly hack for PCM codecs (will be removed ASAP with new PCM
588 // support to compute the input frame size in samples
589 if ( c->frame_size <= 1 )
591 audio_input_frame_size = audio_outbuf_size / c->channels;
592 switch(st->codec->codec_id)
594 case CODEC_ID_PCM_S16LE:
595 case CODEC_ID_PCM_S16BE:
596 case CODEC_ID_PCM_U16LE:
597 case CODEC_ID_PCM_U16BE:
598 audio_input_frame_size >>= 1;
606 audio_input_frame_size = c->frame_size;
609 // Some formats want stream headers to be seperate (hmm)
610 if ( !strcmp( oc->oformat->name, "mp4" ) ||
611 !strcmp( oc->oformat->name, "mov" ) ||
612 !strcmp( oc->oformat->name, "3gp" ) )
613 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
617 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
622 return audio_input_frame_size;
625 static void close_audio( AVFormatContext *oc, AVStream *st )
627 if ( st && st->codec )
630 avcodec_close( st->codec );
635 /** Add a video output stream
638 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
640 // Get the properties
641 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
643 // Create a new stream
644 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(10<<8)+0)
645 AVStream *st = avformat_new_stream( oc, codec );
647 AVStream *st = av_new_stream( oc, oc->nb_streams );
652 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
653 AVCodecContext *c = st->codec;
655 // Establish defaults from AVOptions
656 #if LIBAVCODEC_VERSION_MAJOR >= 53
657 avcodec_get_context_defaults3( c, codec );
659 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
662 c->codec_id = codec->id;
663 c->codec_type = CODEC_TYPE_VIDEO;
665 // Setup multi-threading
666 int thread_count = mlt_properties_get_int( properties, "threads" );
667 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
668 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
669 if ( thread_count > 1 )
670 #if LIBAVCODEC_VERSION_MAJOR >= 53
671 c->thread_count = thread_count;
673 avcodec_thread_init( c, thread_count );
676 // Process properties as AVOptions
677 char *vpre = mlt_properties_get( properties, "vpre" );
680 mlt_properties p = mlt_properties_load( vpre );
682 if ( mlt_properties_count( p ) < 1 )
684 AVCodec *codec = avcodec_find_encoder( c->codec_id );
687 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
688 strcpy( path, AVDATADIR );
689 strcat( path, codec->name );
691 strcat( path, vpre );
692 strcat( path, ".ffpreset" );
694 mlt_properties_close( p );
695 p = mlt_properties_load( path );
696 if ( mlt_properties_count( p ) > 0 )
697 mlt_properties_debug( p, path, stderr );
703 mlt_properties_debug( p, vpre, stderr );
706 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
707 mlt_properties_close( p );
709 int colorspace = mlt_properties_get_int( properties, "colorspace" );
710 mlt_properties_set( properties, "colorspace", NULL );
711 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
712 mlt_properties_set_int( properties, "colorspace", colorspace );
714 // Set options controlled by MLT
715 c->width = mlt_properties_get_int( properties, "width" );
716 c->height = mlt_properties_get_int( properties, "height" );
717 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
718 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
719 if ( st->time_base.den == 0 )
720 st->time_base = c->time_base;
721 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
722 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
724 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
727 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
728 switch ( colorspace )
731 c->colorspace = AVCOL_SPC_SMPTE170M;
734 c->colorspace = AVCOL_SPC_SMPTE240M;
737 c->colorspace = AVCOL_SPC_BT470BG;
740 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
743 c->colorspace = AVCOL_SPC_BT709;
748 if ( mlt_properties_get( properties, "aspect" ) )
750 // "-aspect" on ffmpeg command line is display aspect ratio
751 double ar = mlt_properties_get_double( properties, "aspect" );
752 AVRational rational = av_d2q( ar, 255 );
754 // Update the profile and properties as well since this is an alias
755 // for mlt properties that correspond to profile settings
756 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
757 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
758 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
761 profile->display_aspect_num = rational.num;
762 profile->display_aspect_den = rational.den;
763 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
766 // Now compute the sample aspect ratio
767 rational = av_d2q( ar * c->height / c->width, 255 );
768 c->sample_aspect_ratio = rational;
769 // Update the profile and properties as well since this is an alias
770 // for mlt properties that correspond to profile settings
771 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
772 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
775 profile->sample_aspect_num = rational.num;
776 profile->sample_aspect_den = rational.den;
777 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
782 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
783 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
785 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
786 st->sample_aspect_ratio = c->sample_aspect_ratio;
789 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
791 c->flags |= CODEC_FLAG_QSCALE;
792 c->global_quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
793 #if LIBAVFORMAT_VERSION_MAJOR < 53
794 st->quality = c->global_quality;
798 // Allow the user to override the video fourcc
799 if ( mlt_properties_get( properties, "vtag" ) )
802 const char *arg = mlt_properties_get( properties, "vtag" );
803 int tag = strtol( arg, &tail, 0);
805 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
809 // Some formats want stream headers to be seperate
810 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
811 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
813 // Translate these standard mlt consumer properties to ffmpeg
814 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
815 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
817 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
818 c->flags |= CODEC_FLAG_INTERLACED_DCT;
819 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
820 c->flags |= CODEC_FLAG_INTERLACED_ME;
823 // parse the ratecontrol override string
825 char *rc_override = mlt_properties_get( properties, "rc_override" );
826 for ( i = 0; rc_override; i++ )
829 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
831 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
832 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
833 c->rc_override[i].start_frame = start;
834 c->rc_override[i].end_frame = end;
837 c->rc_override[i].qscale = q;
838 c->rc_override[i].quality_factor = 1.0;
842 c->rc_override[i].qscale = 0;
843 c->rc_override[i].quality_factor = -q / 100.0;
845 rc_override = strchr( rc_override, '/' );
849 c->rc_override_count = i;
850 if ( !c->rc_initial_buffer_occupancy )
851 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
852 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
855 i = mlt_properties_get_int( properties, "pass" );
857 c->flags |= CODEC_FLAG_PASS1;
859 c->flags |= CODEC_FLAG_PASS2;
860 if ( codec->id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
862 char logfilename[1024];
867 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
868 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
869 if ( c->flags & CODEC_FLAG_PASS1 )
871 f = fopen( logfilename, "w" );
873 perror( logfilename );
875 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
879 /* read the log file */
880 f = fopen( logfilename, "r" );
887 mlt_properties_set( properties, "_logfilename", logfilename );
888 fseek( f, 0, SEEK_END );
890 fseek( f, 0, SEEK_SET );
891 logbuffer = av_malloc( size + 1 );
893 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
896 size = fread( logbuffer, 1, size, f );
898 logbuffer[size] = '\0';
899 c->stats_in = logbuffer;
907 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
913 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
916 AVFrame *picture = avcodec_alloc_frame();
918 // Determine size of the
919 int size = avpicture_get_size(pix_fmt, width, height);
921 // Allocate the picture buf
922 uint8_t *picture_buf = av_malloc(size);
924 // If we have both, then fill the image
925 if ( picture != NULL && picture_buf != NULL )
927 // Fill the frame with the allocated buffer
928 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
932 // Something failed - clean up what we can
934 av_free( picture_buf );
941 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
944 AVCodecContext *video_enc = st->codec;
946 // find the video encoder
949 codec = avcodec_find_encoder_by_name( codec_name );
951 codec = avcodec_find_encoder( video_enc->codec_id );
953 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
954 // Process properties as AVOptions on the AVCodec
955 if ( codec && codec->priv_class )
957 char *vpre = mlt_properties_get( properties, "vpre" );
958 if ( !video_enc->priv_data && codec->priv_data_size )
960 video_enc->priv_data = av_mallocz( codec->priv_data_size );
961 *(const AVClass **) video_enc->priv_data = codec->priv_class;
962 // av_opt_set_defaults( video_enc );
966 mlt_properties p = mlt_properties_load( vpre );
967 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
968 mlt_properties_close( p );
970 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
974 if( codec && codec->pix_fmts )
976 const enum PixelFormat *p = codec->pix_fmts;
979 if( *p == video_enc->pix_fmt )
983 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
986 // Open the codec safely
988 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
989 int result = codec && avcodec_open2( video_enc, codec, NULL ) >= 0;
991 int result = codec && avcodec_open( video_enc, codec ) >= 0;
998 void close_video(AVFormatContext *oc, AVStream *st)
1000 if ( st && st->codec )
1003 av_freep( &st->codec->stats_in );
1004 avcodec_close(st->codec);
1009 static inline long time_difference( struct timeval *time1 )
1011 struct timeval time2;
1012 gettimeofday( &time2, NULL );
1013 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
1016 static int mlt_write(void *h, uint8_t *buf, int size)
1018 mlt_properties properties = (mlt_properties) h;
1019 mlt_events_fire( properties, "avformat-write", buf, size, NULL );
1023 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
1025 listener( owner, service, (uint8_t*) args[0], (int) args[1] );
1029 /** The main thread - the argument is simply the consumer.
1032 static void *consumer_thread( void *arg )
1034 // Map the argument to the object
1035 mlt_consumer consumer = arg;
1037 // Get the properties
1038 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1040 // Get the terminate on pause property
1041 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1044 // Determine if feed is slow (for realtime stuff)
1045 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1048 struct timeval ante;
1050 // Get the frame rate
1051 double fps = mlt_properties_get_double( properties, "fps" );
1053 // Get width and height
1054 int width = mlt_properties_get_int( properties, "width" );
1055 int height = mlt_properties_get_int( properties, "height" );
1056 int img_width = width;
1057 int img_height = height;
1059 // Get default audio properties
1060 mlt_audio_format aud_fmt = mlt_audio_s16;
1061 int channels = mlt_properties_get_int( properties, "channels" );
1062 int total_channels = channels;
1063 int frequency = mlt_properties_get_int( properties, "frequency" );
1064 int16_t *pcm = NULL;
1067 // AVFormat audio buffer and frame size
1068 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1069 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1070 int audio_input_frame_size = 0;
1072 // AVFormat video buffer and frame count
1073 int frame_count = 0;
1074 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1075 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1077 // Used for the frame properties
1078 mlt_frame frame = NULL;
1079 mlt_properties frame_properties = NULL;
1082 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1083 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1085 // Need two av pictures for converting
1086 AVFrame *output = NULL;
1087 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
1089 // For receiving images from an mlt_frame
1091 mlt_image_format img_fmt = mlt_image_yuv422;
1093 // For receiving audio samples back from the fifo
1094 int16_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1095 int16_t *audio_buf_2 = NULL;
1098 // Allocate the context
1099 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
1100 AVFormatContext *oc = avformat_alloc_context( );
1102 AVFormatContext *oc = av_alloc_format_context( );
1106 AVStream *video_st = NULL;
1107 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1110 double audio_pts = 0;
1111 double video_pts = 0;
1113 // Frames dispatched
1114 long int frames = 0;
1115 long int total_time = 0;
1117 // Determine the format
1118 AVOutputFormat *fmt = NULL;
1119 const char *filename = mlt_properties_get( properties, "target" );
1120 char *format = mlt_properties_get( properties, "f" );
1121 char *vcodec = mlt_properties_get( properties, "vcodec" );
1122 char *acodec = mlt_properties_get( properties, "acodec" );
1123 AVCodec *audio_codec = NULL;
1124 AVCodec *video_codec = NULL;
1126 // Used to store and override codec ids
1132 mlt_properties frame_meta_properties = mlt_properties_new();
1134 // Initialize audio_st
1135 int i = MAX_AUDIO_STREAMS;
1139 // Check for user selected format first
1140 if ( format != NULL )
1141 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1142 fmt = guess_format( format, NULL, NULL );
1144 fmt = av_guess_format( format, NULL, NULL );
1147 // Otherwise check on the filename
1148 if ( fmt == NULL && filename != NULL )
1149 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1150 fmt = guess_format( NULL, filename, NULL );
1152 fmt = av_guess_format( NULL, filename, NULL );
1155 // Otherwise default to mpeg
1157 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1158 fmt = guess_format( "mpeg", NULL, NULL );
1160 fmt = av_guess_format( "mpeg", NULL, NULL );
1163 // We need a filename - default to stdout?
1164 if ( filename == NULL || !strcmp( filename, "" ) )
1167 // Get the codec ids selected
1168 audio_codec_id = fmt->audio_codec;
1169 video_codec_id = fmt->video_codec;
1171 // Check for audio codec overides
1172 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1173 audio_codec_id = CODEC_ID_NONE;
1176 audio_codec = avcodec_find_encoder_by_name( acodec );
1179 audio_codec_id = audio_codec->id;
1180 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1182 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1183 acodec = mlt_properties_get( properties, "_acodec" );
1184 audio_codec = avcodec_find_encoder_by_name( acodec );
1189 audio_codec_id = CODEC_ID_NONE;
1190 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1195 audio_codec = avcodec_find_encoder( audio_codec_id );
1198 // Check for video codec overides
1199 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1200 video_codec_id = CODEC_ID_NONE;
1203 video_codec = avcodec_find_encoder_by_name( vcodec );
1206 video_codec_id = video_codec->id;
1210 video_codec_id = CODEC_ID_NONE;
1211 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1216 video_codec = avcodec_find_encoder( video_codec_id );
1220 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1221 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1223 char *name = mlt_properties_get_name( properties, i );
1224 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1226 char *key = strdup( name + 10 );
1227 char *markup = strrchr( key, '.' );
1228 if ( markup && !strcmp( markup, ".markup") )
1231 if ( !strstr( key, ".stream." ) )
1232 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1233 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
1234 av_dict_set( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1236 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1239 av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1249 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1250 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1252 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1253 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1255 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1256 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1258 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1259 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1261 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1262 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1264 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1265 if (metavalue != 0) oc->year = metavalue;
1267 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1268 if (metavalue != 0) oc->track = metavalue;
1272 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1274 // Get a frame now, so we can set some AVOptions from properties.
1275 frame = mlt_consumer_rt_frame( consumer );
1277 // Set the timecode from the MLT metadata if available.
1278 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1279 if ( timecode && strcmp( timecode, "" ) )
1281 mlt_properties_set( properties, "timecode", timecode );
1282 if ( strchr( timecode, ';' ) )
1283 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1286 // Add audio and video streams
1287 if ( video_codec_id != CODEC_ID_NONE )
1288 video_st = add_video_stream( consumer, oc, video_codec );
1289 if ( audio_codec_id != CODEC_ID_NONE )
1295 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1297 sprintf( key, "channels.%d", i );
1298 int j = mlt_properties_get_int( properties, key );
1302 total_channels += j;
1303 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1309 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1310 total_channels = channels;
1313 mlt_properties_set_int( properties, "channels", total_channels );
1315 // Set the parameters (even though we have none...)
1316 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1317 if ( av_set_parameters(oc, NULL) >= 0 )
1320 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1321 if ( mlt_properties_get( properties, "muxpreload" ) && ! mlt_properties_get( properties, "preload" ) )
1322 mlt_properties_set_double( properties, "preload", mlt_properties_get_double( properties, "muxpreload" ) );
1324 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1326 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1328 // Process properties as AVOptions
1329 char *fpre = mlt_properties_get( properties, "fpre" );
1332 mlt_properties p = mlt_properties_load( fpre );
1333 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1334 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1335 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1336 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1338 mlt_properties_close( p );
1340 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1341 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
1342 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1343 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1346 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1348 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1350 audio_input_frame_size = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1351 acodec? acodec : NULL );
1352 if ( !audio_input_frame_size )
1356 // Setup custom I/O if redirecting
1357 if ( mlt_properties_get_int( properties, "redirect" ) )
1359 int buffer_size = 32768;
1360 unsigned char *buffer = av_malloc( buffer_size );
1361 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1362 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1364 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1369 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1370 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1372 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1373 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1374 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1379 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1382 // Open the output file, if needed
1383 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1385 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1386 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1388 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1391 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1392 mlt_properties_set_int( properties, "running", 0 );
1396 // Write the stream header.
1397 if ( mlt_properties_get_int( properties, "running" ) )
1398 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(2<<8)+0)
1399 avformat_write_header( oc, NULL );
1401 av_write_header( oc );
1404 #if LIBAVFORMAT_VERSION_INT < ((53<<16)+(2<<8)+0)
1407 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1408 mlt_properties_set_int( properties, "running", 0 );
1414 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1416 // Last check - need at least one stream
1417 if ( !audio_st[0] && !video_st )
1418 mlt_properties_set_int( properties, "running", 0 );
1420 // Get the starting time (can ignore the times above)
1421 gettimeofday( &ante, NULL );
1423 // Loop while running
1424 while( mlt_properties_get_int( properties, "running" ) &&
1425 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1428 frame = mlt_consumer_rt_frame( consumer );
1430 // Check that we have a frame to work with
1431 if ( frame != NULL )
1433 // Increment frames dispatched
1436 // Default audio args
1437 frame_properties = MLT_FRAME_PROPERTIES( frame );
1439 // Check for the terminated condition
1440 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1442 // Get audio and append to the fifo
1443 if ( !terminated && audio_st[0] )
1445 samples = mlt_sample_calculator( fps, frequency, count ++ );
1446 channels = total_channels;
1447 mlt_frame_get_audio( frame, (void**) &pcm, &aud_fmt, &frequency, &channels, &samples );
1449 // Save the audio channel remap properties for later
1450 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1452 // Create the fifo if we don't have one
1455 fifo = sample_fifo_init( frequency, channels );
1456 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1459 // Silence if not normal forward speed
1460 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1461 memset( pcm, 0, samples * channels * 2 );
1463 // Append the samples
1464 sample_fifo_append( fifo, pcm, samples * channels );
1465 total_time += ( samples * 1000000 ) / frequency;
1468 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1472 if ( !terminated && video_st )
1473 mlt_deque_push_back( queue, frame );
1475 mlt_frame_close( frame );
1479 // While we have stuff to process, process...
1482 // Write interleaved audio and video frames
1483 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1486 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1488 int j = 0; // channel offset into interleaved source buffer
1489 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) ), AUDIO_ENCODE_BUFFER_SIZE );
1491 // Get the audio samples
1494 sample_fifo_fetch( fifo, audio_buf_1, n );
1496 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1498 // This prevents an infinite loop when some versions of vorbis do not
1499 // increment pts when encoding silence.
1500 audio_pts = video_pts;
1505 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1507 samples = n / channels;
1509 // For each output stream
1510 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1512 AVStream *stream = audio_st[i];
1513 AVCodecContext *codec = stream->codec;
1516 av_init_packet( &pkt );
1518 // Optimized for single track and no channel remap
1519 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1521 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1525 // Extract the audio channels according to channel mapping
1526 int dest_offset = 0; // channel offset into interleaved dest buffer
1528 // Get the number of channels for this stream
1529 sprintf( key, "channels.%d", i );
1530 int current_channels = mlt_properties_get_int( properties, key );
1532 // Clear the destination audio buffer.
1534 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1536 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1538 // For each output channel
1539 while ( dest_offset < current_channels && j < total_channels )
1541 int map_start = -1, map_channels = 0;
1542 int source_offset = 0;
1545 // Look for a mapping that starts at j
1546 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1548 sprintf( key, "%d.channels", k );
1549 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1550 sprintf( key, "%d.start", k );
1551 if ( mlt_properties_get( frame_meta_properties, key ) )
1552 map_start = mlt_properties_get_int( frame_meta_properties, key );
1553 if ( map_start != j )
1554 source_offset += map_channels;
1558 if ( map_start != j )
1560 map_channels = current_channels;
1564 // Copy samples if source offset valid
1565 if ( source_offset < channels )
1567 // Interleave the audio buffer with the # channels for this stream/mapping.
1568 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1570 int16_t *src = audio_buf_1 + source_offset;
1571 int16_t *dest = audio_buf_2 + dest_offset;
1572 int s = samples + 1;
1576 dest += current_channels;
1581 // Otherwise silence
1584 j += current_channels;
1585 dest_offset += current_channels;
1588 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_2 );
1591 // Write the compressed frame in the media file
1592 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1594 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1595 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame pts %"PRId64,
1596 stream->index, pkt.pts, codec->coded_frame->pts );
1598 pkt.flags |= PKT_FLAG_KEY;
1599 pkt.stream_index = stream->index;
1600 pkt.data = audio_outbuf;
1604 if ( av_interleaved_write_frame( oc, &pkt ) )
1606 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1607 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1608 goto on_fatal_error;
1612 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1615 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1624 else if ( video_st )
1627 if ( mlt_deque_count( queue ) )
1629 int out_size, ret = 0;
1632 frame = mlt_deque_pop_front( queue );
1633 frame_properties = MLT_FRAME_PROPERTIES( frame );
1635 c = video_st->codec;
1637 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1643 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1647 // Convert the mlt frame to an AVPicture
1648 for ( i = 0; i < height; i ++ )
1650 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1651 memcpy( p, q, width * 2 );
1655 // Do the colour space conversion
1657 int flags = SWS_BILINEAR;
1659 flags |= SWS_CPU_CAPS_MMX;
1662 flags |= SWS_CPU_CAPS_MMX2;
1664 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1665 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1666 sws_scale( context, (const uint8_t* const*) input->data, input->linesize, 0, height,
1667 output->data, output->linesize);
1668 sws_freeContext( context );
1670 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1673 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1675 // Apply the alpha if applicable
1676 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1678 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1681 for ( i = 0; i < height; i ++ )
1683 n = ( width + 7 ) / 8;
1684 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1688 case 0: do { *p = *alpha++; p += 4;
1689 case 7: *p = *alpha++; p += 4;
1690 case 6: *p = *alpha++; p += 4;
1691 case 5: *p = *alpha++; p += 4;
1692 case 4: *p = *alpha++; p += 4;
1693 case 3: *p = *alpha++; p += 4;
1694 case 2: *p = *alpha++; p += 4;
1695 case 1: *p = *alpha++; p += 4;
1703 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1705 // raw video case. The API will change slightly in the near future for that
1707 av_init_packet(&pkt);
1709 pkt.flags |= PKT_FLAG_KEY;
1710 pkt.stream_index= video_st->index;
1711 pkt.data= (uint8_t *)output;
1712 pkt.size= sizeof(AVPicture);
1714 ret = av_write_frame(oc, &pkt);
1715 video_pts += c->frame_size;
1720 output->quality = c->global_quality;
1722 // Set frame interlace hints
1723 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1724 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1725 output->pts = frame_count;
1728 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1730 // If zero size, it means the image was buffered
1734 av_init_packet( &pkt );
1736 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1737 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1738 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %"PRId64" frame pts %"PRId64, pkt.pts, c->coded_frame->pts );
1739 if( c->coded_frame && c->coded_frame->key_frame )
1740 pkt.flags |= PKT_FLAG_KEY;
1741 pkt.stream_index= video_st->index;
1742 pkt.data= video_outbuf;
1745 // write the compressed frame in the media file
1746 ret = av_interleaved_write_frame(oc, &pkt);
1747 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1748 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1750 // Dual pass logging
1751 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1752 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1754 else if ( out_size < 0 )
1756 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1762 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1763 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1764 goto on_fatal_error;
1766 mlt_frame_close( frame );
1775 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1777 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1778 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1781 if ( real_time_output == 1 && frames % 2 == 0 )
1783 long passed = time_difference( &ante );
1786 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1789 if ( passed < total_time )
1791 long total = ( total_time - passed );
1792 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1793 nanosleep( &t, NULL );
1798 // Flush the encoder buffers
1799 if ( real_time_output <= 0 )
1802 // TODO: flush all audio streams
1803 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1805 AVCodecContext *c = audio_st[0]->codec;
1807 av_init_packet( &pkt );
1810 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1811 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1813 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size );
1814 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1816 if ( pkt.size <= 0 )
1817 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1818 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1819 if ( pkt.size <= 0 )
1822 // Write the compressed frame in the media file
1823 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1824 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1825 pkt.flags |= PKT_FLAG_KEY;
1826 pkt.stream_index = audio_st[0]->index;
1827 pkt.data = audio_outbuf;
1828 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1830 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1831 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1832 goto on_fatal_error;
1837 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1839 AVCodecContext *c = video_st->codec;
1841 av_init_packet( &pkt );
1844 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1845 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1846 if ( pkt.size <= 0 )
1849 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1850 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1851 if( c->coded_frame && c->coded_frame->key_frame )
1852 pkt.flags |= PKT_FLAG_KEY;
1853 pkt.stream_index = video_st->index;
1854 pkt.data = video_outbuf;
1856 // write the compressed frame in the media file
1857 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1859 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1860 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1861 goto on_fatal_error;
1863 // Dual pass logging
1864 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1865 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1871 // Write the trailer, if any
1872 av_write_trailer( oc );
1876 close_video(oc, video_st);
1877 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1878 close_audio( oc, audio_st[i] );
1881 for ( i = 0; i < oc->nb_streams; i++ )
1882 av_freep( &oc->streams[i] );
1884 // Close the output file
1885 if ( !( fmt->flags & AVFMT_NOFILE ) )
1887 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1888 if ( !mlt_properties_get_int( properties, "redirect" ) )
1889 avio_close( oc->pb );
1890 #elif LIBAVFORMAT_VERSION_MAJOR >= 52
1891 url_fclose( oc->pb );
1893 url_fclose( &oc->pb );
1897 // Clean up input and output frames
1899 av_free( output->data[0] );
1901 av_free( input->data[0] );
1903 av_free( video_outbuf );
1904 av_free( audio_buf_1 );
1905 av_free( audio_buf_2 );
1910 // Just in case we terminated on pause
1911 mlt_properties_set_int( properties, "running", 0 );
1913 mlt_consumer_stopped( consumer );
1914 mlt_properties_close( frame_meta_properties );
1916 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1918 // Remove the dual pass log file
1919 if ( mlt_properties_get( properties, "_logfilename" ) )
1920 remove( mlt_properties_get( properties, "_logfilename" ) );
1922 // Remove the x264 dual pass logs
1923 char *cwd = getcwd( NULL, 0 );
1924 const char *file = "x264_2pass.log";
1925 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1926 sprintf( full, "%s/%s", cwd, file );
1929 file = "x264_2pass.log.temp";
1930 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1931 sprintf( full, "%s/%s", cwd, file );
1934 file = "x264_2pass.log.mbtree";
1935 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1936 sprintf( full, "%s/%s", cwd, file );
1940 remove( "x264_2pass.log.temp" );
1943 while ( ( frame = mlt_deque_pop_back( queue ) ) )
1944 mlt_frame_close( frame );
1949 /** Close the consumer.
1952 static void consumer_close( mlt_consumer consumer )
1954 // Stop the consumer
1955 mlt_consumer_stop( consumer );
1958 mlt_consumer_close( consumer );