2 * consumer_avformat.c -- an encoder based on avformat
3 * Copyright (C) 2003-2004 Ushodaya Enterprises Limited
4 * Author: Charles Yates <charles.yates@pandora.be>
5 * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #include <framework/mlt_consumer.h>
24 #include <framework/mlt_frame.h>
25 #include <framework/mlt_profile.h>
26 #include <framework/mlt_log.h>
27 #include <framework/mlt_events.h>
29 // System header files
38 // avformat header files
39 #include <libavformat/avformat.h>
40 #include <libavformat/avio.h>
42 #include <libswscale/swscale.h>
44 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
45 #include <libavutil/pixdesc.h>
48 #if LIBAVUTIL_VERSION_INT < (50<<16)
49 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
50 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
53 #if LIBAVCODEC_VERSION_MAJOR >= 53
54 #include <libavutil/opt.h>
55 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
56 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
57 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
59 #include <libavcodec/opt.h>
62 #define MAX_AUDIO_STREAMS (8)
63 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
64 #define AUDIO_BUFFER_SIZE (1024 * 42)
65 #define VIDEO_BUFFER_SIZE (2048 * 1024)
67 void avformat_lock( );
68 void avformat_unlock( );
71 // This structure should be extended and made globally available in mlt
83 *sample_fifo, sample_fifo_s;
85 sample_fifo sample_fifo_init( int frequency, int channels )
87 sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
88 fifo->frequency = frequency;
89 fifo->channels = channels;
93 // sample_fifo_clear and check are temporarily aborted (not working as intended)
95 void sample_fifo_clear( sample_fifo fifo, double time )
97 int words = ( float )( time - fifo->time ) * fifo->frequency * fifo->channels;
98 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )fifo->time * 100 ) && fifo->used > words && words > 0 )
100 memmove( fifo->buffer, &fifo->buffer[ words ], ( fifo->used - words ) * sizeof( int16_t ) );
104 else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )fifo->time * 100 ) )
111 void sample_fifo_check( sample_fifo fifo, double time )
113 if ( fifo->used == 0 )
115 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )fifo->time * 100 ) )
120 void sample_fifo_append( sample_fifo fifo, int16_t *samples, int count )
122 if ( ( fifo->size - fifo->used ) < count )
124 fifo->size += count * 5;
125 fifo->buffer = realloc( fifo->buffer, fifo->size * sizeof( int16_t ) );
128 memcpy( &fifo->buffer[ fifo->used ], samples, count * sizeof( int16_t ) );
132 int sample_fifo_used( sample_fifo fifo )
137 int sample_fifo_fetch( sample_fifo fifo, int16_t *samples, int count )
139 if ( count > fifo->used )
142 memcpy( samples, fifo->buffer, count * sizeof( int16_t ) );
144 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used * sizeof( int16_t ) );
146 fifo->time += ( double )count / fifo->channels / fifo->frequency;
151 void sample_fifo_close( sample_fifo fifo )
153 free( fifo->buffer );
157 // Forward references.
158 static int consumer_start( mlt_consumer consumer );
159 static int consumer_stop( mlt_consumer consumer );
160 static int consumer_is_stopped( mlt_consumer consumer );
161 static void *consumer_thread( void *arg );
162 static void consumer_close( mlt_consumer consumer );
164 /** Initialise the consumer.
167 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
169 // Allocate the consumer
170 mlt_consumer consumer = mlt_consumer_new( profile );
172 // If memory allocated and initialises without error
173 if ( consumer != NULL )
175 // Get properties from the consumer
176 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
178 // Assign close callback
179 consumer->close = consumer_close;
181 // Interpret the argument
183 mlt_properties_set( properties, "target", arg );
185 // sample and frame queue
186 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
188 // Audio options not fully handled by AVOptions
189 #define QSCALE_NONE (-99999)
190 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
192 // Video options not fully handled by AVOptions
193 mlt_properties_set_int( properties, "dc", 8 );
195 // Muxer options not fully handled by AVOptions
196 mlt_properties_set_double( properties, "muxdelay", 0.7 );
197 mlt_properties_set_double( properties, "muxpreload", 0.5 );
199 // Ensure termination at end of the stream
200 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
202 // Default to separate processing threads for producer and consumer with no frame dropping!
203 mlt_properties_set_int( properties, "real_time", -1 );
204 mlt_properties_set_int( properties, "prefill", 1 );
206 // Set up start/stop/terminated callbacks
207 consumer->start = consumer_start;
208 consumer->stop = consumer_stop;
209 consumer->is_stopped = consumer_is_stopped;
211 mlt_events_register( properties, "consumer-fatal-error", NULL );
218 /** Start the consumer.
221 static int consumer_start( mlt_consumer consumer )
223 // Get the properties
224 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
227 // Report information about available muxers and codecs as YAML Tiny
228 char *s = mlt_properties_get( properties, "f" );
229 if ( s && strcmp( s, "list" ) == 0 )
231 mlt_properties doc = mlt_properties_new();
232 mlt_properties formats = mlt_properties_new();
234 AVOutputFormat *format = NULL;
236 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
237 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
238 while ( ( format = av_oformat_next( format ) ) )
240 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
241 mlt_properties_set( formats, key, format->name );
243 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
244 mlt_properties_close( doc );
247 s = mlt_properties_get( properties, "acodec" );
248 if ( s && strcmp( s, "list" ) == 0 )
250 mlt_properties doc = mlt_properties_new();
251 mlt_properties codecs = mlt_properties_new();
253 AVCodec *codec = NULL;
255 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
256 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
257 while ( ( codec = av_codec_next( codec ) ) )
258 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
260 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
261 mlt_properties_set( codecs, key, codec->name );
263 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
264 mlt_properties_close( doc );
267 s = mlt_properties_get( properties, "vcodec" );
268 if ( s && strcmp( s, "list" ) == 0 )
270 mlt_properties doc = mlt_properties_new();
271 mlt_properties codecs = mlt_properties_new();
273 AVCodec *codec = NULL;
275 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
276 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
277 while ( ( codec = av_codec_next( codec ) ) )
278 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
280 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
281 mlt_properties_set( codecs, key, codec->name );
283 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
284 mlt_properties_close( doc );
288 // Check that we're not already running
289 if ( !error && !mlt_properties_get_int( properties, "running" ) )
292 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
294 // Get the width and height
295 int width = mlt_properties_get_int( properties, "width" );
296 int height = mlt_properties_get_int( properties, "height" );
298 // Obtain the size property
299 char *size = mlt_properties_get( properties, "s" );
305 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
312 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Invalid size property %s - ignoring.\n", size );
316 // Now ensure we honour the multiple of two requested by libavformat
317 width = ( width / 2 ) * 2;
318 height = ( height / 2 ) * 2;
319 mlt_properties_set_int( properties, "width", width );
320 mlt_properties_set_int( properties, "height", height );
322 // We need to set these on the profile as well because the s property is
323 // an alias to mlt properties that correspond to profile settings.
324 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
327 profile->width = width;
328 profile->height = height;
331 // Handle the ffmpeg command line "-r" property for frame rate
332 if ( mlt_properties_get( properties, "r" ) )
334 double frame_rate = mlt_properties_get_double( properties, "r" );
335 AVRational rational = av_d2q( frame_rate, 255 );
336 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
337 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
340 profile->frame_rate_num = rational.num;
341 profile->frame_rate_den = rational.den;
342 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
346 // Apply AVOptions that are synonyms for standard mlt_consumer options
347 if ( mlt_properties_get( properties, "ac" ) )
348 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
349 if ( mlt_properties_get( properties, "ar" ) )
350 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
352 // Assign the thread to properties
353 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
355 // Set the running state
356 mlt_properties_set_int( properties, "running", 1 );
359 pthread_create( thread, NULL, consumer_thread, consumer );
364 /** Stop the consumer.
367 static int consumer_stop( mlt_consumer consumer )
369 // Get the properties
370 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
372 // Check that we're running
373 if ( mlt_properties_get_int( properties, "running" ) )
376 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
379 mlt_properties_set_int( properties, "running", 0 );
381 // Wait for termination
382 pthread_join( *thread, NULL );
388 /** Determine if the consumer is stopped.
391 static int consumer_is_stopped( mlt_consumer consumer )
393 // Get the properties
394 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
395 return !mlt_properties_get_int( properties, "running" );
398 /** Process properties as AVOptions and apply to AV context obj
401 static void apply_properties( void *obj, mlt_properties properties, int flags )
404 int count = mlt_properties_count( properties );
407 for ( i = 0; i < count; i++ )
409 const char *opt_name = mlt_properties_get_name( properties, i );
410 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
412 // If option not found, see if it was prefixed with a or v (-vb)
414 ( opt_name[0] == 'v' && ( flags & AV_OPT_FLAG_VIDEO_PARAM ) ) ||
415 ( opt_name[0] == 'a' && ( flags & AV_OPT_FLAG_AUDIO_PARAM ) ) ) )
416 opt = av_find_opt( obj, ++opt_name, NULL, flags, flags );
417 // Apply option if found
419 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
420 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
421 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
422 av_set_string2( obj, opt_name, mlt_properties_get_value( properties, i), alloc );
424 av_set_string( obj, opt_name, mlt_properties_get_value( properties, i) );
429 /** Add an audio output stream
432 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec, int channels )
434 // Get the properties
435 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
437 // Create a new stream
438 AVStream *st = av_new_stream( oc, oc->nb_streams );
440 // If created, then initialise from properties
443 AVCodecContext *c = st->codec;
445 // Establish defaults from AVOptions
446 #if LIBAVCODEC_VERSION_MAJOR >= 53
447 avcodec_get_context_defaults3( c, codec );
449 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
452 c->codec_id = codec->id;
453 c->codec_type = CODEC_TYPE_AUDIO;
454 c->sample_fmt = SAMPLE_FMT_S16;
456 #if 0 // disabled until some audio codecs are multi-threaded
457 // Setup multi-threading
458 int thread_count = mlt_properties_get_int( properties, "threads" );
459 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
460 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
461 if ( thread_count > 1 )
462 c->thread_count = thread_count;
465 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
466 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
468 // Allow the user to override the audio fourcc
469 if ( mlt_properties_get( properties, "atag" ) )
472 char *arg = mlt_properties_get( properties, "atag" );
473 int tag = strtol( arg, &tail, 0);
475 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
479 // Process properties as AVOptions
480 char *apre = mlt_properties_get( properties, "apre" );
483 mlt_properties p = mlt_properties_load( apre );
484 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
485 mlt_properties_close( p );
487 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
489 int audio_qscale = mlt_properties_get_int( properties, "aq" );
490 if ( audio_qscale > QSCALE_NONE )
492 c->flags |= CODEC_FLAG_QSCALE;
493 c->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
496 // Set parameters controlled by MLT
497 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
498 c->time_base = ( AVRational ){ 1, c->sample_rate };
499 c->channels = channels;
501 if ( mlt_properties_get( properties, "alang" ) != NULL )
502 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
503 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
506 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
511 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
517 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
519 // We will return the audio input size from here
520 int audio_input_frame_size = 0;
523 AVCodecContext *c = st->codec;
528 codec = avcodec_find_encoder_by_name( codec_name );
530 codec = avcodec_find_encoder( c->codec_id );
532 #if LIBAVCODEC_VERSION_MAJOR >= 53
533 // Process properties as AVOptions on the AVCodec
534 if ( codec && codec->priv_class )
536 char *apre = mlt_properties_get( properties, "apre" );
537 if ( !c->priv_data && codec->priv_data_size )
539 c->priv_data = av_mallocz( codec->priv_data_size );
540 *(const AVClass **) c->priv_data = codec->priv_class;
541 // av_opt_set_defaults( c );
545 mlt_properties p = mlt_properties_load( apre );
546 apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
547 mlt_properties_close( p );
549 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
555 // Continue if codec found and we can open it
556 if ( codec != NULL && avcodec_open( c, codec ) >= 0 )
558 // ugly hack for PCM codecs (will be removed ASAP with new PCM
559 // support to compute the input frame size in samples
560 if ( c->frame_size <= 1 )
562 audio_input_frame_size = audio_outbuf_size / c->channels;
563 switch(st->codec->codec_id)
565 case CODEC_ID_PCM_S16LE:
566 case CODEC_ID_PCM_S16BE:
567 case CODEC_ID_PCM_U16LE:
568 case CODEC_ID_PCM_U16BE:
569 audio_input_frame_size >>= 1;
577 audio_input_frame_size = c->frame_size;
580 // Some formats want stream headers to be seperate (hmm)
581 if ( !strcmp( oc->oformat->name, "mp4" ) ||
582 !strcmp( oc->oformat->name, "mov" ) ||
583 !strcmp( oc->oformat->name, "3gp" ) )
584 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
588 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
593 return audio_input_frame_size;
596 static void close_audio( AVFormatContext *oc, AVStream *st )
598 if ( st && st->codec )
601 avcodec_close( st->codec );
606 /** Add a video output stream
609 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, AVCodec *codec )
611 // Get the properties
612 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
614 // Create a new stream
615 AVStream *st = av_new_stream( oc, oc->nb_streams );
619 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
620 AVCodecContext *c = st->codec;
622 // Establish defaults from AVOptions
623 #if LIBAVCODEC_VERSION_MAJOR >= 53
624 avcodec_get_context_defaults3( c, codec );
626 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
629 c->codec_id = codec->id;
630 c->codec_type = CODEC_TYPE_VIDEO;
632 // Setup multi-threading
633 int thread_count = mlt_properties_get_int( properties, "threads" );
634 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
635 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
636 if ( thread_count > 1 )
637 #if LIBAVCODEC_VERSION_MAJOR >= 53
638 c->thread_count = thread_count;
640 avcodec_thread_init( c, thread_count );
643 // Process properties as AVOptions
644 char *vpre = mlt_properties_get( properties, "vpre" );
647 mlt_properties p = mlt_properties_load( vpre );
649 if ( mlt_properties_count( p ) < 1 )
651 AVCodec *codec = avcodec_find_encoder( c->codec_id );
654 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
655 strcpy( path, AVDATADIR );
656 strcat( path, codec->name );
658 strcat( path, vpre );
659 strcat( path, ".ffpreset" );
661 mlt_properties_close( p );
662 p = mlt_properties_load( path );
663 if ( mlt_properties_count( p ) > 0 )
664 mlt_properties_debug( p, path, stderr );
670 mlt_properties_debug( p, vpre, stderr );
673 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
674 mlt_properties_close( p );
676 int colorspace = mlt_properties_get_int( properties, "colorspace" );
677 mlt_properties_set( properties, "colorspace", NULL );
678 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
679 mlt_properties_set_int( properties, "colorspace", colorspace );
681 // Set options controlled by MLT
682 c->width = mlt_properties_get_int( properties, "width" );
683 c->height = mlt_properties_get_int( properties, "height" );
684 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
685 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
686 if ( st->time_base.den == 0 )
687 st->time_base = c->time_base;
688 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
689 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
691 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
694 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
695 switch ( colorspace )
698 c->colorspace = AVCOL_SPC_SMPTE170M;
701 c->colorspace = AVCOL_SPC_SMPTE240M;
704 c->colorspace = AVCOL_SPC_BT470BG;
707 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
710 c->colorspace = AVCOL_SPC_BT709;
715 if ( mlt_properties_get( properties, "aspect" ) )
717 // "-aspect" on ffmpeg command line is display aspect ratio
718 double ar = mlt_properties_get_double( properties, "aspect" );
719 AVRational rational = av_d2q( ar, 255 );
721 // Update the profile and properties as well since this is an alias
722 // for mlt properties that correspond to profile settings
723 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
724 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
725 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
728 profile->display_aspect_num = rational.num;
729 profile->display_aspect_den = rational.den;
730 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
733 // Now compute the sample aspect ratio
734 rational = av_d2q( ar * c->height / c->width, 255 );
735 c->sample_aspect_ratio = rational;
736 // Update the profile and properties as well since this is an alias
737 // for mlt properties that correspond to profile settings
738 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
739 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
742 profile->sample_aspect_num = rational.num;
743 profile->sample_aspect_den = rational.den;
744 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
749 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
750 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
752 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
753 st->sample_aspect_ratio = c->sample_aspect_ratio;
756 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
758 c->flags |= CODEC_FLAG_QSCALE;
759 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
762 // Allow the user to override the video fourcc
763 if ( mlt_properties_get( properties, "vtag" ) )
766 const char *arg = mlt_properties_get( properties, "vtag" );
767 int tag = strtol( arg, &tail, 0);
769 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
773 // Some formats want stream headers to be seperate
774 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
775 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
777 // Translate these standard mlt consumer properties to ffmpeg
778 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
779 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
781 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
782 c->flags |= CODEC_FLAG_INTERLACED_DCT;
783 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
784 c->flags |= CODEC_FLAG_INTERLACED_ME;
787 // parse the ratecontrol override string
789 char *rc_override = mlt_properties_get( properties, "rc_override" );
790 for ( i = 0; rc_override; i++ )
793 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
795 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
796 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
797 c->rc_override[i].start_frame = start;
798 c->rc_override[i].end_frame = end;
801 c->rc_override[i].qscale = q;
802 c->rc_override[i].quality_factor = 1.0;
806 c->rc_override[i].qscale = 0;
807 c->rc_override[i].quality_factor = -q / 100.0;
809 rc_override = strchr( rc_override, '/' );
813 c->rc_override_count = i;
814 if ( !c->rc_initial_buffer_occupancy )
815 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
816 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
819 i = mlt_properties_get_int( properties, "pass" );
821 c->flags |= CODEC_FLAG_PASS1;
823 c->flags |= CODEC_FLAG_PASS2;
824 if ( codec->id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
826 char logfilename[1024];
831 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
832 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
833 if ( c->flags & CODEC_FLAG_PASS1 )
835 f = fopen( logfilename, "w" );
837 perror( logfilename );
839 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
843 /* read the log file */
844 f = fopen( logfilename, "r" );
851 mlt_properties_set( properties, "_logfilename", logfilename );
852 fseek( f, 0, SEEK_END );
854 fseek( f, 0, SEEK_SET );
855 logbuffer = av_malloc( size + 1 );
857 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
860 size = fread( logbuffer, 1, size, f );
862 logbuffer[size] = '\0';
863 c->stats_in = logbuffer;
871 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
877 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
880 AVFrame *picture = avcodec_alloc_frame();
882 // Determine size of the
883 int size = avpicture_get_size(pix_fmt, width, height);
885 // Allocate the picture buf
886 uint8_t *picture_buf = av_malloc(size);
888 // If we have both, then fill the image
889 if ( picture != NULL && picture_buf != NULL )
891 // Fill the frame with the allocated buffer
892 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
896 // Something failed - clean up what we can
898 av_free( picture_buf );
905 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
908 AVCodecContext *video_enc = st->codec;
910 // find the video encoder
913 codec = avcodec_find_encoder_by_name( codec_name );
915 codec = avcodec_find_encoder( video_enc->codec_id );
917 #if LIBAVCODEC_VERSION_MAJOR >= 53
918 // Process properties as AVOptions on the AVCodec
919 if ( codec && codec->priv_class )
921 char *vpre = mlt_properties_get( properties, "vpre" );
922 if ( !video_enc->priv_data && codec->priv_data_size )
924 video_enc->priv_data = av_mallocz( codec->priv_data_size );
925 *(const AVClass **) video_enc->priv_data = codec->priv_class;
926 // av_opt_set_defaults( video_enc );
930 mlt_properties p = mlt_properties_load( vpre );
931 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
932 mlt_properties_close( p );
934 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
938 if( codec && codec->pix_fmts )
940 const enum PixelFormat *p = codec->pix_fmts;
943 if( *p == video_enc->pix_fmt )
947 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
950 // Open the codec safely
952 int result = codec != NULL && avcodec_open( video_enc, codec ) >= 0;
958 void close_video(AVFormatContext *oc, AVStream *st)
960 if ( st && st->codec )
963 av_freep( &st->codec->stats_in );
964 avcodec_close(st->codec);
969 static inline long time_difference( struct timeval *time1 )
971 struct timeval time2;
972 gettimeofday( &time2, NULL );
973 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
976 static int mlt_write(void *h, uint8_t *buf, int size)
978 mlt_properties properties = (mlt_properties) h;
979 mlt_events_fire( properties, "avformat-write", buf, size, NULL );
983 static void write_transmitter( mlt_listener listener, mlt_properties owner, mlt_service service, void **args )
985 listener( owner, service, (uint8_t*) args[0], (int) args[1] );
989 /** The main thread - the argument is simply the consumer.
992 static void *consumer_thread( void *arg )
994 // Map the argument to the object
995 mlt_consumer consumer = arg;
997 // Get the properties
998 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
1000 // Get the terminate on pause property
1001 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
1004 // Determine if feed is slow (for realtime stuff)
1005 int real_time_output = mlt_properties_get_int( properties, "real_time" );
1008 struct timeval ante;
1010 // Get the frame rate
1011 double fps = mlt_properties_get_double( properties, "fps" );
1013 // Get width and height
1014 int width = mlt_properties_get_int( properties, "width" );
1015 int height = mlt_properties_get_int( properties, "height" );
1016 int img_width = width;
1017 int img_height = height;
1019 // Get default audio properties
1020 mlt_audio_format aud_fmt = mlt_audio_s16;
1021 int channels = mlt_properties_get_int( properties, "channels" );
1022 int total_channels = channels;
1023 int frequency = mlt_properties_get_int( properties, "frequency" );
1024 int16_t *pcm = NULL;
1027 // AVFormat audio buffer and frame size
1028 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
1029 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
1030 int audio_input_frame_size = 0;
1032 // AVFormat video buffer and frame count
1033 int frame_count = 0;
1034 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1035 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1037 // Used for the frame properties
1038 mlt_frame frame = NULL;
1039 mlt_properties frame_properties = NULL;
1042 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1043 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1045 // Need two av pictures for converting
1046 AVFrame *output = NULL;
1047 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
1049 // For receiving images from an mlt_frame
1051 mlt_image_format img_fmt = mlt_image_yuv422;
1053 // For receiving audio samples back from the fifo
1054 int16_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1055 int16_t *audio_buf_2 = NULL;
1058 // Allocate the context
1059 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
1060 AVFormatContext *oc = avformat_alloc_context( );
1062 AVFormatContext *oc = av_alloc_format_context( );
1066 AVStream *video_st = NULL;
1067 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1070 double audio_pts = 0;
1071 double video_pts = 0;
1073 // Frames dispatched
1074 long int frames = 0;
1075 long int total_time = 0;
1077 // Determine the format
1078 AVOutputFormat *fmt = NULL;
1079 const char *filename = mlt_properties_get( properties, "target" );
1080 char *format = mlt_properties_get( properties, "f" );
1081 char *vcodec = mlt_properties_get( properties, "vcodec" );
1082 char *acodec = mlt_properties_get( properties, "acodec" );
1083 AVCodec *audio_codec = NULL;
1084 AVCodec *video_codec = NULL;
1086 // Used to store and override codec ids
1092 mlt_properties frame_meta_properties = mlt_properties_new();
1094 // Initialize audio_st
1095 int i = MAX_AUDIO_STREAMS;
1099 // Check for user selected format first
1100 if ( format != NULL )
1101 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1102 fmt = guess_format( format, NULL, NULL );
1104 fmt = av_guess_format( format, NULL, NULL );
1107 // Otherwise check on the filename
1108 if ( fmt == NULL && filename != NULL )
1109 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1110 fmt = guess_format( NULL, filename, NULL );
1112 fmt = av_guess_format( NULL, filename, NULL );
1115 // Otherwise default to mpeg
1117 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1118 fmt = guess_format( "mpeg", NULL, NULL );
1120 fmt = av_guess_format( "mpeg", NULL, NULL );
1123 // We need a filename - default to stdout?
1124 if ( filename == NULL || !strcmp( filename, "" ) )
1127 // Get the codec ids selected
1128 audio_codec_id = fmt->audio_codec;
1129 video_codec_id = fmt->video_codec;
1131 // Check for audio codec overides
1132 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1133 audio_codec_id = CODEC_ID_NONE;
1136 audio_codec = avcodec_find_encoder_by_name( acodec );
1139 audio_codec_id = audio_codec->id;
1140 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1142 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1143 acodec = mlt_properties_get( properties, "_acodec" );
1144 audio_codec = avcodec_find_encoder_by_name( acodec );
1149 audio_codec_id = CODEC_ID_NONE;
1150 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1155 audio_codec = avcodec_find_encoder( audio_codec_id );
1158 // Check for video codec overides
1159 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1160 video_codec_id = CODEC_ID_NONE;
1163 video_codec = avcodec_find_encoder_by_name( vcodec );
1166 video_codec_id = video_codec->id;
1170 video_codec_id = CODEC_ID_NONE;
1171 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1176 video_codec = avcodec_find_encoder( video_codec_id );
1180 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1181 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1183 char *name = mlt_properties_get_name( properties, i );
1184 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1186 char *key = strdup( name + 10 );
1187 char *markup = strrchr( key, '.' );
1188 if ( markup && !strcmp( markup, ".markup") )
1191 if ( !strstr( key, ".stream." ) )
1192 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1193 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1195 av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1205 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1206 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1208 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1209 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1211 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1212 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1214 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1215 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1217 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1218 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1220 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1221 if (metavalue != 0) oc->year = metavalue;
1223 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1224 if (metavalue != 0) oc->track = metavalue;
1228 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1230 // Get a frame now, so we can set some AVOptions from properties.
1231 frame = mlt_consumer_rt_frame( consumer );
1233 // Set the timecode from the MLT metadata if available.
1234 const char *timecode = mlt_properties_get( MLT_FRAME_PROPERTIES(frame), "meta.attr.vitc.markup" );
1235 if ( timecode && strcmp( timecode, "" ) )
1237 mlt_properties_set( properties, "timecode", timecode );
1238 if ( strchr( timecode, ';' ) )
1239 mlt_properties_set_int( properties, "drop_frame_timecode", 1 );
1242 // Add audio and video streams
1243 if ( video_codec_id != CODEC_ID_NONE )
1244 video_st = add_video_stream( consumer, oc, video_codec );
1245 if ( audio_codec_id != CODEC_ID_NONE )
1251 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1253 sprintf( key, "channels.%d", i );
1254 int j = mlt_properties_get_int( properties, key );
1258 total_channels += j;
1259 audio_st[i] = add_audio_stream( consumer, oc, audio_codec, j );
1265 audio_st[0] = add_audio_stream( consumer, oc, audio_codec, channels );
1266 total_channels = channels;
1269 mlt_properties_set_int( properties, "channels", total_channels );
1271 // Set the parameters (even though we have none...)
1272 if ( av_set_parameters(oc, NULL) >= 0 )
1274 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1275 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1277 // Process properties as AVOptions
1278 char *fpre = mlt_properties_get( properties, "fpre" );
1281 mlt_properties p = mlt_properties_load( fpre );
1282 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM );
1283 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1284 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1285 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM );
1287 mlt_properties_close( p );
1289 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
1290 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1291 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1292 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM );
1295 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1297 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1299 audio_input_frame_size = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1300 acodec? acodec : NULL );
1301 if ( !audio_input_frame_size )
1305 // Setup custom I/O if redirecting
1306 if ( mlt_properties_get_int( properties, "redirect" ) )
1308 int buffer_size = 32768;
1309 unsigned char *buffer = av_malloc( buffer_size );
1310 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1311 AVIOContext* io = avio_alloc_context( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1313 ByteIOContext* io = av_alloc_put_byte( buffer, buffer_size, 1, properties, NULL, mlt_write, NULL );
1318 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1319 oc->flags |= AVFMT_FLAG_CUSTOM_IO;
1321 mlt_properties_set_data( properties, "avio_buffer", buffer, buffer_size, av_free, NULL );
1322 mlt_properties_set_data( properties, "avio_context", io, 0, av_free, NULL );
1323 mlt_events_register( properties, "avformat-write", (mlt_transmitter) write_transmitter );
1328 mlt_log_error( MLT_CONSUMER_SERVICE(consumer), "failed to setup output redirection\n" );
1331 // Open the output file, if needed
1332 else if ( !( fmt->flags & AVFMT_NOFILE ) )
1334 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1335 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1337 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1340 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1341 mlt_properties_set_int( properties, "running", 0 );
1345 // Write the stream header.
1346 if ( mlt_properties_get_int( properties, "running" ) )
1347 av_write_header( oc );
1351 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1352 mlt_properties_set_int( properties, "running", 0 );
1357 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1359 // Last check - need at least one stream
1360 if ( !audio_st[0] && !video_st )
1361 mlt_properties_set_int( properties, "running", 0 );
1363 // Get the starting time (can ignore the times above)
1364 gettimeofday( &ante, NULL );
1366 // Loop while running
1367 while( mlt_properties_get_int( properties, "running" ) &&
1368 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1371 frame = mlt_consumer_rt_frame( consumer );
1373 // Check that we have a frame to work with
1374 if ( frame != NULL )
1376 // Increment frames dispatched
1379 // Default audio args
1380 frame_properties = MLT_FRAME_PROPERTIES( frame );
1382 // Check for the terminated condition
1383 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1385 // Get audio and append to the fifo
1386 if ( !terminated && audio_st[0] )
1388 samples = mlt_sample_calculator( fps, frequency, count ++ );
1389 channels = total_channels;
1390 mlt_frame_get_audio( frame, (void**) &pcm, &aud_fmt, &frequency, &channels, &samples );
1392 // Save the audio channel remap properties for later
1393 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1395 // Create the fifo if we don't have one
1398 fifo = sample_fifo_init( frequency, channels );
1399 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1402 // Silence if not normal forward speed
1403 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1404 memset( pcm, 0, samples * channels * 2 );
1406 // Append the samples
1407 sample_fifo_append( fifo, pcm, samples * channels );
1408 total_time += ( samples * 1000000 ) / frequency;
1411 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1415 if ( !terminated && video_st )
1416 mlt_deque_push_back( queue, frame );
1418 mlt_frame_close( frame );
1422 // While we have stuff to process, process...
1425 // Write interleaved audio and video frames
1426 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1429 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1431 int j = 0; // channel offset into interleaved source buffer
1432 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) ), AUDIO_ENCODE_BUFFER_SIZE );
1434 // Get the audio samples
1437 sample_fifo_fetch( fifo, audio_buf_1, n );
1439 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1441 // This prevents an infinite loop when some versions of vorbis do not
1442 // increment pts when encoding silence.
1443 audio_pts = video_pts;
1448 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1450 samples = n / channels;
1452 // For each output stream
1453 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1455 AVStream *stream = audio_st[i];
1456 AVCodecContext *codec = stream->codec;
1459 av_init_packet( &pkt );
1461 // Optimized for single track and no channel remap
1462 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1464 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1468 // Extract the audio channels according to channel mapping
1469 int dest_offset = 0; // channel offset into interleaved dest buffer
1471 // Get the number of channels for this stream
1472 sprintf( key, "channels.%d", i );
1473 int current_channels = mlt_properties_get_int( properties, key );
1475 // Clear the destination audio buffer.
1477 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1479 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1481 // For each output channel
1482 while ( dest_offset < current_channels && j < total_channels )
1484 int map_start = -1, map_channels = 0;
1485 int source_offset = 0;
1488 // Look for a mapping that starts at j
1489 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1491 sprintf( key, "%d.channels", k );
1492 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1493 sprintf( key, "%d.start", k );
1494 if ( mlt_properties_get( frame_meta_properties, key ) )
1495 map_start = mlt_properties_get_int( frame_meta_properties, key );
1496 if ( map_start != j )
1497 source_offset += map_channels;
1501 if ( map_start != j )
1503 map_channels = current_channels;
1507 // Copy samples if source offset valid
1508 if ( source_offset < channels )
1510 // Interleave the audio buffer with the # channels for this stream/mapping.
1511 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1513 int16_t *src = audio_buf_1 + source_offset;
1514 int16_t *dest = audio_buf_2 + dest_offset;
1515 int s = samples + 1;
1519 dest += current_channels;
1524 // Otherwise silence
1527 j += current_channels;
1528 dest_offset += current_channels;
1531 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_2 );
1534 // Write the compressed frame in the media file
1535 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1537 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1538 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame pts %"PRId64,
1539 stream->index, pkt.pts, codec->coded_frame->pts );
1541 pkt.flags |= PKT_FLAG_KEY;
1542 pkt.stream_index = stream->index;
1543 pkt.data = audio_outbuf;
1547 if ( av_interleaved_write_frame( oc, &pkt ) )
1549 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1550 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1551 goto on_fatal_error;
1555 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1558 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1567 else if ( video_st )
1570 if ( mlt_deque_count( queue ) )
1572 int out_size, ret = 0;
1575 frame = mlt_deque_pop_front( queue );
1576 frame_properties = MLT_FRAME_PROPERTIES( frame );
1578 c = video_st->codec;
1580 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1586 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1590 // Convert the mlt frame to an AVPicture
1591 for ( i = 0; i < height; i ++ )
1593 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1594 memcpy( p, q, width * 2 );
1598 // Do the colour space conversion
1600 int flags = SWS_BILINEAR;
1602 flags |= SWS_CPU_CAPS_MMX;
1605 flags |= SWS_CPU_CAPS_MMX2;
1607 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1608 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1609 sws_scale( context, (const uint8_t* const*) input->data, input->linesize, 0, height,
1610 output->data, output->linesize);
1611 sws_freeContext( context );
1613 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1616 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1618 // Apply the alpha if applicable
1619 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1621 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1624 for ( i = 0; i < height; i ++ )
1626 n = ( width + 7 ) / 8;
1627 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1631 case 0: do { *p = *alpha++; p += 4;
1632 case 7: *p = *alpha++; p += 4;
1633 case 6: *p = *alpha++; p += 4;
1634 case 5: *p = *alpha++; p += 4;
1635 case 4: *p = *alpha++; p += 4;
1636 case 3: *p = *alpha++; p += 4;
1637 case 2: *p = *alpha++; p += 4;
1638 case 1: *p = *alpha++; p += 4;
1646 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1648 // raw video case. The API will change slightly in the near future for that
1650 av_init_packet(&pkt);
1652 pkt.flags |= PKT_FLAG_KEY;
1653 pkt.stream_index= video_st->index;
1654 pkt.data= (uint8_t *)output;
1655 pkt.size= sizeof(AVPicture);
1657 ret = av_write_frame(oc, &pkt);
1658 video_pts += c->frame_size;
1663 output->quality = video_st->quality;
1665 // Set frame interlace hints
1666 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1667 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1668 output->pts = frame_count;
1671 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1673 // If zero size, it means the image was buffered
1677 av_init_packet( &pkt );
1679 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1680 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1681 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %"PRId64" frame pts %"PRId64, pkt.pts, c->coded_frame->pts );
1682 if( c->coded_frame && c->coded_frame->key_frame )
1683 pkt.flags |= PKT_FLAG_KEY;
1684 pkt.stream_index= video_st->index;
1685 pkt.data= video_outbuf;
1688 // write the compressed frame in the media file
1689 ret = av_interleaved_write_frame(oc, &pkt);
1690 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1691 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1693 // Dual pass logging
1694 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1695 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1697 else if ( out_size < 0 )
1699 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1705 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1706 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1707 goto on_fatal_error;
1709 mlt_frame_close( frame );
1718 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1720 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1721 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1724 if ( real_time_output == 1 && frames % 2 == 0 )
1726 long passed = time_difference( &ante );
1729 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1732 if ( passed < total_time )
1734 long total = ( total_time - passed );
1735 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1736 nanosleep( &t, NULL );
1741 // Flush the encoder buffers
1742 if ( real_time_output <= 0 )
1745 // TODO: flush all audio streams
1746 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1748 AVCodecContext *c = audio_st[0]->codec;
1750 av_init_packet( &pkt );
1753 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1754 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1756 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size );
1757 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1759 if ( pkt.size <= 0 )
1760 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1761 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1762 if ( pkt.size <= 0 )
1765 // Write the compressed frame in the media file
1766 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1767 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1768 pkt.flags |= PKT_FLAG_KEY;
1769 pkt.stream_index = audio_st[0]->index;
1770 pkt.data = audio_outbuf;
1771 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1773 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1774 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1775 goto on_fatal_error;
1780 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1782 AVCodecContext *c = video_st->codec;
1784 av_init_packet( &pkt );
1787 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1788 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1789 if ( pkt.size <= 0 )
1792 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1793 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1794 if( c->coded_frame && c->coded_frame->key_frame )
1795 pkt.flags |= PKT_FLAG_KEY;
1796 pkt.stream_index = video_st->index;
1797 pkt.data = video_outbuf;
1799 // write the compressed frame in the media file
1800 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1802 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1803 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1804 goto on_fatal_error;
1806 // Dual pass logging
1807 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1808 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1814 // Write the trailer, if any
1815 av_write_trailer( oc );
1819 close_video(oc, video_st);
1820 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1821 close_audio( oc, audio_st[i] );
1824 for ( i = 0; i < oc->nb_streams; i++ )
1825 av_freep( &oc->streams[i] );
1827 // Close the output file
1828 if ( !( fmt->flags & AVFMT_NOFILE ) )
1830 #if LIBAVFORMAT_VERSION_MAJOR >= 53
1831 if ( !mlt_properties_get_int( properties, "redirect" ) )
1832 avio_close( oc->pb );
1833 #elif LIBAVFORMAT_VERSION_MAJOR >= 52
1834 url_fclose( oc->pb );
1836 url_fclose( &oc->pb );
1840 // Clean up input and output frames
1842 av_free( output->data[0] );
1844 av_free( input->data[0] );
1846 av_free( video_outbuf );
1847 av_free( audio_buf_1 );
1848 av_free( audio_buf_2 );
1853 // Just in case we terminated on pause
1854 mlt_properties_set_int( properties, "running", 0 );
1856 mlt_consumer_stopped( consumer );
1857 mlt_properties_close( frame_meta_properties );
1859 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1861 // Remove the dual pass log file
1862 if ( mlt_properties_get( properties, "_logfilename" ) )
1863 remove( mlt_properties_get( properties, "_logfilename" ) );
1865 // Remove the x264 dual pass logs
1866 char *cwd = getcwd( NULL, 0 );
1867 const char *file = "x264_2pass.log";
1868 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1869 sprintf( full, "%s/%s", cwd, file );
1872 file = "x264_2pass.log.temp";
1873 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1874 sprintf( full, "%s/%s", cwd, file );
1877 file = "x264_2pass.log.mbtree";
1878 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1879 sprintf( full, "%s/%s", cwd, file );
1883 remove( "x264_2pass.log.temp" );
1886 while ( ( frame = mlt_deque_pop_back( queue ) ) )
1887 mlt_frame_close( frame );
1892 /** Close the consumer.
1895 static void consumer_close( mlt_consumer consumer )
1897 // Stop the consumer
1898 mlt_consumer_stop( consumer );
1901 mlt_consumer_close( consumer );