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>
41 #include <libswscale/swscale.h>
43 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
44 #include <libavutil/pixdesc.h>
47 #if LIBAVUTIL_VERSION_INT < (50<<16)
48 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
49 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
52 #if LIBAVCODEC_VERSION_MAJOR > 52
53 #include <libavutil/opt.h>
54 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
55 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
56 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
58 #include <libavcodec/opt.h>
61 #define MAX_AUDIO_STREAMS (8)
62 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
63 #define AUDIO_BUFFER_SIZE (1024 * 42)
64 #define VIDEO_BUFFER_SIZE (2048 * 1024)
66 void avformat_lock( );
67 void avformat_unlock( );
70 // This structure should be extended and made globally available in mlt
82 *sample_fifo, sample_fifo_s;
84 sample_fifo sample_fifo_init( int frequency, int channels )
86 sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
87 fifo->frequency = frequency;
88 fifo->channels = channels;
92 // sample_fifo_clear and check are temporarily aborted (not working as intended)
94 void sample_fifo_clear( sample_fifo fifo, double time )
96 int words = ( float )( time - fifo->time ) * fifo->frequency * fifo->channels;
97 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )fifo->time * 100 ) && fifo->used > words && words > 0 )
99 memmove( fifo->buffer, &fifo->buffer[ words ], ( fifo->used - words ) * sizeof( int16_t ) );
103 else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )fifo->time * 100 ) )
110 void sample_fifo_check( sample_fifo fifo, double time )
112 if ( fifo->used == 0 )
114 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )fifo->time * 100 ) )
119 void sample_fifo_append( sample_fifo fifo, int16_t *samples, int count )
121 if ( ( fifo->size - fifo->used ) < count )
123 fifo->size += count * 5;
124 fifo->buffer = realloc( fifo->buffer, fifo->size * sizeof( int16_t ) );
127 memcpy( &fifo->buffer[ fifo->used ], samples, count * sizeof( int16_t ) );
131 int sample_fifo_used( sample_fifo fifo )
136 int sample_fifo_fetch( sample_fifo fifo, int16_t *samples, int count )
138 if ( count > fifo->used )
141 memcpy( samples, fifo->buffer, count * sizeof( int16_t ) );
143 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used * sizeof( int16_t ) );
145 fifo->time += ( double )count / fifo->channels / fifo->frequency;
150 void sample_fifo_close( sample_fifo fifo )
152 free( fifo->buffer );
156 // Forward references.
157 static int consumer_start( mlt_consumer consumer );
158 static int consumer_stop( mlt_consumer consumer );
159 static int consumer_is_stopped( mlt_consumer consumer );
160 static void *consumer_thread( void *arg );
161 static void consumer_close( mlt_consumer consumer );
163 /** Initialise the consumer.
166 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
168 // Allocate the consumer
169 mlt_consumer consumer = mlt_consumer_new( profile );
171 // If memory allocated and initialises without error
172 if ( consumer != NULL )
174 // Get properties from the consumer
175 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
177 // Assign close callback
178 consumer->close = consumer_close;
180 // Interpret the argument
182 mlt_properties_set( properties, "target", arg );
184 // sample and frame queue
185 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
187 // Audio options not fully handled by AVOptions
188 #define QSCALE_NONE (-99999)
189 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
191 // Video options not fully handled by AVOptions
192 mlt_properties_set_int( properties, "dc", 8 );
194 // Muxer options not fully handled by AVOptions
195 mlt_properties_set_double( properties, "muxdelay", 0.7 );
196 mlt_properties_set_double( properties, "muxpreload", 0.5 );
198 // Ensure termination at end of the stream
199 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
201 // Default to separate processing threads for producer and consumer with no frame dropping!
202 mlt_properties_set_int( properties, "real_time", -1 );
203 mlt_properties_set_int( properties, "prefill", 1 );
205 // Set up start/stop/terminated callbacks
206 consumer->start = consumer_start;
207 consumer->stop = consumer_stop;
208 consumer->is_stopped = consumer_is_stopped;
210 mlt_events_register( properties, "consumer-fatal-error", NULL );
217 /** Start the consumer.
220 static int consumer_start( mlt_consumer consumer )
222 // Get the properties
223 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
226 // Report information about available muxers and codecs as YAML Tiny
227 char *s = mlt_properties_get( properties, "f" );
228 if ( s && strcmp( s, "list" ) == 0 )
230 mlt_properties doc = mlt_properties_new();
231 mlt_properties formats = mlt_properties_new();
233 AVOutputFormat *format = NULL;
235 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
236 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
237 while ( ( format = av_oformat_next( format ) ) )
239 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
240 mlt_properties_set( formats, key, format->name );
242 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
243 mlt_properties_close( doc );
246 s = mlt_properties_get( properties, "acodec" );
247 if ( s && strcmp( s, "list" ) == 0 )
249 mlt_properties doc = mlt_properties_new();
250 mlt_properties codecs = mlt_properties_new();
252 AVCodec *codec = NULL;
254 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
255 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
256 while ( ( codec = av_codec_next( codec ) ) )
257 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
259 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
260 mlt_properties_set( codecs, key, codec->name );
262 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
263 mlt_properties_close( doc );
266 s = mlt_properties_get( properties, "vcodec" );
267 if ( s && strcmp( s, "list" ) == 0 )
269 mlt_properties doc = mlt_properties_new();
270 mlt_properties codecs = mlt_properties_new();
272 AVCodec *codec = NULL;
274 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
275 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
276 while ( ( codec = av_codec_next( codec ) ) )
277 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
279 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
280 mlt_properties_set( codecs, key, codec->name );
282 fprintf( stdout, "%s", mlt_properties_serialise_yaml( doc ) );
283 mlt_properties_close( doc );
287 // Check that we're not already running
288 if ( !error && !mlt_properties_get_int( properties, "running" ) )
291 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
293 // Get the width and height
294 int width = mlt_properties_get_int( properties, "width" );
295 int height = mlt_properties_get_int( properties, "height" );
297 // Obtain the size property
298 char *size = mlt_properties_get( properties, "s" );
304 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
311 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Invalid size property %s - ignoring.\n", size );
315 // Now ensure we honour the multiple of two requested by libavformat
316 width = ( width / 2 ) * 2;
317 height = ( height / 2 ) * 2;
318 mlt_properties_set_int( properties, "width", width );
319 mlt_properties_set_int( properties, "height", height );
321 // We need to set these on the profile as well because the s property is
322 // an alias to mlt properties that correspond to profile settings.
323 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
326 profile->width = width;
327 profile->height = height;
330 // Handle the ffmpeg command line "-r" property for frame rate
331 if ( mlt_properties_get( properties, "r" ) )
333 double frame_rate = mlt_properties_get_double( properties, "r" );
334 AVRational rational = av_d2q( frame_rate, 255 );
335 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
336 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
339 profile->frame_rate_num = rational.num;
340 profile->frame_rate_den = rational.den;
341 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
345 // Apply AVOptions that are synonyms for standard mlt_consumer options
346 if ( mlt_properties_get( properties, "ac" ) )
347 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
348 if ( mlt_properties_get( properties, "ar" ) )
349 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
351 // Assign the thread to properties
352 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
354 // Set the running state
355 mlt_properties_set_int( properties, "running", 1 );
358 pthread_create( thread, NULL, consumer_thread, consumer );
363 /** Stop the consumer.
366 static int consumer_stop( mlt_consumer consumer )
368 // Get the properties
369 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
371 // Check that we're running
372 if ( mlt_properties_get_int( properties, "running" ) )
375 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
378 mlt_properties_set_int( properties, "running", 0 );
380 // Wait for termination
381 pthread_join( *thread, NULL );
387 /** Determine if the consumer is stopped.
390 static int consumer_is_stopped( mlt_consumer consumer )
392 // Get the properties
393 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
394 return !mlt_properties_get_int( properties, "running" );
397 /** Process properties as AVOptions and apply to AV context obj
400 static void apply_properties( void *obj, mlt_properties properties, int flags, int alloc )
403 int count = mlt_properties_count( properties );
404 for ( i = 0; i < count; i++ )
406 const char *opt_name = mlt_properties_get_name( properties, i );
407 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
410 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
411 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
412 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
413 av_set_string2( obj, opt_name, mlt_properties_get_value( properties, i), alloc );
415 av_set_string( obj, opt_name, mlt_properties_get_value( properties, i) );
420 /** Add an audio output stream
423 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, int codec_id, int channels )
425 // Get the properties
426 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
428 // Create a new stream
429 AVStream *st = av_new_stream( oc, oc->nb_streams );
431 // If created, then initialise from properties
434 AVCodecContext *c = st->codec;
436 // Establish defaults from AVOptions
437 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
439 c->codec_id = codec_id;
440 c->codec_type = CODEC_TYPE_AUDIO;
441 c->sample_fmt = SAMPLE_FMT_S16;
443 #if 0 // disabled until some audio codecs are multi-threaded
444 // Setup multi-threading
445 int thread_count = mlt_properties_get_int( properties, "threads" );
446 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
447 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
448 if ( thread_count > 1 )
449 c->thread_count = thread_count;
452 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
453 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
455 // Allow the user to override the audio fourcc
456 if ( mlt_properties_get( properties, "atag" ) )
459 char *arg = mlt_properties_get( properties, "atag" );
460 int tag = strtol( arg, &tail, 0);
462 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
466 // Process properties as AVOptions
467 char *apre = mlt_properties_get( properties, "apre" );
470 mlt_properties p = mlt_properties_load( apre );
471 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
472 mlt_properties_close( p );
474 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
476 int audio_qscale = mlt_properties_get_int( properties, "aq" );
477 if ( audio_qscale > QSCALE_NONE )
479 c->flags |= CODEC_FLAG_QSCALE;
480 c->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
483 // Set parameters controlled by MLT
484 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
485 c->time_base = ( AVRational ){ 1, c->sample_rate };
486 c->channels = channels;
488 if ( mlt_properties_get( properties, "alang" ) != NULL )
489 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
490 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
493 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
498 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
504 static int open_audio( mlt_properties properties, AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
506 // We will return the audio input size from here
507 int audio_input_frame_size = 0;
510 AVCodecContext *c = st->codec;
515 codec = avcodec_find_encoder_by_name( codec_name );
517 codec = avcodec_find_encoder( c->codec_id );
519 #if LIBAVCODEC_VERSION_MAJOR > 52
520 // Process properties as AVOptions on the AVCodec
521 if ( codec && codec->priv_class )
523 char *apre = mlt_properties_get( properties, "apre" );
524 if ( !c->priv_data && codec->priv_data_size )
526 c->priv_data = av_mallocz( codec->priv_data_size );
527 *(const AVClass **) c->priv_data = codec->priv_class;
528 // av_opt_set_defaults( c );
532 mlt_properties p = mlt_properties_load( apre );
533 apply_properties( c->priv_data, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
534 mlt_properties_close( p );
536 apply_properties( c->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
542 // Continue if codec found and we can open it
543 if ( codec != NULL && avcodec_open( c, codec ) >= 0 )
545 // ugly hack for PCM codecs (will be removed ASAP with new PCM
546 // support to compute the input frame size in samples
547 if ( c->frame_size <= 1 )
549 audio_input_frame_size = audio_outbuf_size / c->channels;
550 switch(st->codec->codec_id)
552 case CODEC_ID_PCM_S16LE:
553 case CODEC_ID_PCM_S16BE:
554 case CODEC_ID_PCM_U16LE:
555 case CODEC_ID_PCM_U16BE:
556 audio_input_frame_size >>= 1;
564 audio_input_frame_size = c->frame_size;
567 // Some formats want stream headers to be seperate (hmm)
568 if ( !strcmp( oc->oformat->name, "mp4" ) ||
569 !strcmp( oc->oformat->name, "mov" ) ||
570 !strcmp( oc->oformat->name, "3gp" ) )
571 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
575 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
580 return audio_input_frame_size;
583 static void close_audio( AVFormatContext *oc, AVStream *st )
585 if ( st && st->codec )
588 avcodec_close( st->codec );
593 /** Add a video output stream
596 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, int codec_id )
598 // Get the properties
599 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
601 // Create a new stream
602 AVStream *st = av_new_stream( oc, oc->nb_streams );
606 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
607 AVCodecContext *c = st->codec;
609 // Establish defaults from AVOptions
610 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
612 c->codec_id = codec_id;
613 c->codec_type = CODEC_TYPE_VIDEO;
615 // Setup multi-threading
616 int thread_count = mlt_properties_get_int( properties, "threads" );
617 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
618 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
619 if ( thread_count > 1 )
620 c->thread_count = thread_count;
622 // Process properties as AVOptions
623 char *vpre = mlt_properties_get( properties, "vpre" );
626 mlt_properties p = mlt_properties_load( vpre );
628 if ( mlt_properties_count( p ) < 1 )
630 AVCodec *codec = avcodec_find_encoder( c->codec_id );
633 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
634 strcpy( path, AVDATADIR );
635 strcat( path, codec->name );
637 strcat( path, vpre );
638 strcat( path, ".ffpreset" );
640 mlt_properties_close( p );
641 p = mlt_properties_load( path );
642 mlt_properties_debug( p, path, stderr );
648 mlt_properties_debug( p, vpre, stderr );
651 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
652 mlt_properties_close( p );
654 int colorspace = mlt_properties_get_int( properties, "colorspace" );
655 mlt_properties_set( properties, "colorspace", NULL );
656 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
657 mlt_properties_set_int( properties, "colorspace", colorspace );
659 // Set options controlled by MLT
660 c->width = mlt_properties_get_int( properties, "width" );
661 c->height = mlt_properties_get_int( properties, "height" );
662 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
663 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
664 if ( st->time_base.den == 0 )
665 st->time_base = c->time_base;
666 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
667 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
669 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
672 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
673 switch ( colorspace )
676 c->colorspace = AVCOL_SPC_SMPTE170M;
679 c->colorspace = AVCOL_SPC_SMPTE240M;
682 c->colorspace = AVCOL_SPC_BT470BG;
685 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
688 c->colorspace = AVCOL_SPC_BT709;
693 if ( mlt_properties_get( properties, "aspect" ) )
695 // "-aspect" on ffmpeg command line is display aspect ratio
696 double ar = mlt_properties_get_double( properties, "aspect" );
697 AVRational rational = av_d2q( ar, 255 );
699 // Update the profile and properties as well since this is an alias
700 // for mlt properties that correspond to profile settings
701 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
702 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
703 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
706 profile->display_aspect_num = rational.num;
707 profile->display_aspect_den = rational.den;
708 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
711 // Now compute the sample aspect ratio
712 rational = av_d2q( ar * c->height / c->width, 255 );
713 c->sample_aspect_ratio = rational;
714 // Update the profile and properties as well since this is an alias
715 // for mlt properties that correspond to profile settings
716 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
717 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
720 profile->sample_aspect_num = rational.num;
721 profile->sample_aspect_den = rational.den;
722 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
727 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
728 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
730 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
731 st->sample_aspect_ratio = c->sample_aspect_ratio;
734 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
736 c->flags |= CODEC_FLAG_QSCALE;
737 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
740 // Allow the user to override the video fourcc
741 if ( mlt_properties_get( properties, "vtag" ) )
744 const char *arg = mlt_properties_get( properties, "vtag" );
745 int tag = strtol( arg, &tail, 0);
747 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
751 // Some formats want stream headers to be seperate
752 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
753 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
755 // Translate these standard mlt consumer properties to ffmpeg
756 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
757 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
759 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
760 c->flags |= CODEC_FLAG_INTERLACED_DCT;
761 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
762 c->flags |= CODEC_FLAG_INTERLACED_ME;
765 // parse the ratecontrol override string
767 char *rc_override = mlt_properties_get( properties, "rc_override" );
768 for ( i = 0; rc_override; i++ )
771 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
773 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
774 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
775 c->rc_override[i].start_frame = start;
776 c->rc_override[i].end_frame = end;
779 c->rc_override[i].qscale = q;
780 c->rc_override[i].quality_factor = 1.0;
784 c->rc_override[i].qscale = 0;
785 c->rc_override[i].quality_factor = -q / 100.0;
787 rc_override = strchr( rc_override, '/' );
791 c->rc_override_count = i;
792 if ( !c->rc_initial_buffer_occupancy )
793 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
794 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
797 i = mlt_properties_get_int( properties, "pass" );
799 c->flags |= CODEC_FLAG_PASS1;
801 c->flags |= CODEC_FLAG_PASS2;
802 if ( codec_id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
804 char logfilename[1024];
809 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
810 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
811 if ( c->flags & CODEC_FLAG_PASS1 )
813 f = fopen( logfilename, "w" );
815 perror( logfilename );
817 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
821 /* read the log file */
822 f = fopen( logfilename, "r" );
829 mlt_properties_set( properties, "_logfilename", logfilename );
830 fseek( f, 0, SEEK_END );
832 fseek( f, 0, SEEK_SET );
833 logbuffer = av_malloc( size + 1 );
835 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
838 size = fread( logbuffer, 1, size, f );
840 logbuffer[size] = '\0';
841 c->stats_in = logbuffer;
842 mlt_properties_set_data( properties, "_logbuffer", logbuffer, 0, ( mlt_destructor )av_free, NULL );
850 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
856 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
859 AVFrame *picture = avcodec_alloc_frame();
861 // Determine size of the
862 int size = avpicture_get_size(pix_fmt, width, height);
864 // Allocate the picture buf
865 uint8_t *picture_buf = av_malloc(size);
867 // If we have both, then fill the image
868 if ( picture != NULL && picture_buf != NULL )
870 // Fill the frame with the allocated buffer
871 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
875 // Something failed - clean up what we can
877 av_free( picture_buf );
884 static int open_video( mlt_properties properties, AVFormatContext *oc, AVStream *st, const char *codec_name )
887 AVCodecContext *video_enc = st->codec;
889 // find the video encoder
892 codec = avcodec_find_encoder_by_name( codec_name );
894 codec = avcodec_find_encoder( video_enc->codec_id );
896 #if LIBAVCODEC_VERSION_MAJOR > 52
897 // Process properties as AVOptions on the AVCodec
898 if ( codec && codec->priv_class )
900 char *vpre = mlt_properties_get( properties, "vpre" );
901 if ( !video_enc->priv_data && codec->priv_data_size )
903 video_enc->priv_data = av_mallocz( codec->priv_data_size );
904 *(const AVClass **) video_enc->priv_data = codec->priv_class;
905 // av_opt_set_defaults( video_enc );
909 mlt_properties p = mlt_properties_load( vpre );
910 apply_properties( video_enc->priv_data, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
911 mlt_properties_close( p );
913 apply_properties( video_enc->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
917 if( codec && codec->pix_fmts )
919 const enum PixelFormat *p = codec->pix_fmts;
922 if( *p == video_enc->pix_fmt )
926 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
929 // Open the codec safely
931 int result = codec != NULL && avcodec_open( video_enc, codec ) >= 0;
937 void close_video(AVFormatContext *oc, AVStream *st)
939 if ( st && st->codec )
942 avcodec_close(st->codec);
947 static inline long time_difference( struct timeval *time1 )
949 struct timeval time2;
950 gettimeofday( &time2, NULL );
951 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
954 /** The main thread - the argument is simply the consumer.
957 static void *consumer_thread( void *arg )
959 // Map the argument to the object
960 mlt_consumer consumer = arg;
962 // Get the properties
963 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
965 // Get the terminate on pause property
966 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
969 // Determine if feed is slow (for realtime stuff)
970 int real_time_output = mlt_properties_get_int( properties, "real_time" );
975 // Get the frame rate
976 double fps = mlt_properties_get_double( properties, "fps" );
978 // Get width and height
979 int width = mlt_properties_get_int( properties, "width" );
980 int height = mlt_properties_get_int( properties, "height" );
981 int img_width = width;
982 int img_height = height;
984 // Get default audio properties
985 mlt_audio_format aud_fmt = mlt_audio_s16;
986 int channels = mlt_properties_get_int( properties, "channels" );
987 int total_channels = channels;
988 int frequency = mlt_properties_get_int( properties, "frequency" );
992 // AVFormat audio buffer and frame size
993 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
994 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
995 int audio_input_frame_size = 0;
997 // AVFormat video buffer and frame count
999 int video_outbuf_size = VIDEO_BUFFER_SIZE;
1000 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
1002 // Used for the frame properties
1003 mlt_frame frame = NULL;
1004 mlt_properties frame_properties = NULL;
1007 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
1008 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
1010 // Need two av pictures for converting
1011 AVFrame *output = NULL;
1012 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
1014 // For receiving images from an mlt_frame
1016 mlt_image_format img_fmt = mlt_image_yuv422;
1018 // For receiving audio samples back from the fifo
1019 int16_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
1020 int16_t *audio_buf_2 = NULL;
1023 // Allocate the context
1024 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
1025 AVFormatContext *oc = avformat_alloc_context( );
1027 AVFormatContext *oc = av_alloc_format_context( );
1031 AVStream *video_st = NULL;
1032 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
1035 double audio_pts = 0;
1036 double video_pts = 0;
1038 // Frames dispatched
1039 long int frames = 0;
1040 long int total_time = 0;
1042 // Determine the format
1043 AVOutputFormat *fmt = NULL;
1044 const char *filename = mlt_properties_get( properties, "target" );
1045 char *format = mlt_properties_get( properties, "f" );
1046 char *vcodec = mlt_properties_get( properties, "vcodec" );
1047 char *acodec = mlt_properties_get( properties, "acodec" );
1049 // Used to store and override codec ids
1055 mlt_properties frame_meta_properties = mlt_properties_new();
1057 // Initialize audio_st
1058 int i = MAX_AUDIO_STREAMS;
1062 // Check for user selected format first
1063 if ( format != NULL )
1064 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1065 fmt = guess_format( format, NULL, NULL );
1067 fmt = av_guess_format( format, NULL, NULL );
1070 // Otherwise check on the filename
1071 if ( fmt == NULL && filename != NULL )
1072 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1073 fmt = guess_format( NULL, filename, NULL );
1075 fmt = av_guess_format( NULL, filename, NULL );
1078 // Otherwise default to mpeg
1080 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1081 fmt = guess_format( "mpeg", NULL, NULL );
1083 fmt = av_guess_format( "mpeg", NULL, NULL );
1086 // We need a filename - default to stdout?
1087 if ( filename == NULL || !strcmp( filename, "" ) )
1090 // Get the codec ids selected
1091 audio_codec_id = fmt->audio_codec;
1092 video_codec_id = fmt->video_codec;
1094 // Check for audio codec overides
1095 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1096 audio_codec_id = CODEC_ID_NONE;
1099 AVCodec *p = avcodec_find_encoder_by_name( acodec );
1102 audio_codec_id = p->id;
1103 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1105 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1106 acodec = mlt_properties_get( properties, "_acodec" );
1111 audio_codec_id = CODEC_ID_NONE;
1112 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1116 // Check for video codec overides
1117 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1118 video_codec_id = CODEC_ID_NONE;
1121 AVCodec *p = avcodec_find_encoder_by_name( vcodec );
1124 video_codec_id = p->id;
1128 video_codec_id = CODEC_ID_NONE;
1129 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1134 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1135 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1137 char *name = mlt_properties_get_name( properties, i );
1138 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1140 char *key = strdup( name + 10 );
1141 char *markup = strrchr( key, '.' );
1142 if ( markup && !strcmp( markup, ".markup") )
1145 if ( !strstr( key, ".stream." ) )
1146 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1147 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1149 av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1159 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1160 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1162 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1163 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1165 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1166 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1168 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1169 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1171 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1172 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1174 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1175 if (metavalue != 0) oc->year = metavalue;
1177 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1178 if (metavalue != 0) oc->track = metavalue;
1182 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1184 // Add audio and video streams
1185 if ( video_codec_id != CODEC_ID_NONE )
1186 video_st = add_video_stream( consumer, oc, video_codec_id );
1187 if ( audio_codec_id != CODEC_ID_NONE )
1193 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1195 sprintf( key, "channels.%d", i );
1196 int j = mlt_properties_get_int( properties, key );
1200 total_channels += j;
1201 audio_st[i] = add_audio_stream( consumer, oc, audio_codec_id, j );
1207 audio_st[0] = add_audio_stream( consumer, oc, audio_codec_id, channels );
1208 total_channels = channels;
1212 // Set the parameters (even though we have none...)
1213 if ( av_set_parameters(oc, NULL) >= 0 )
1215 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1216 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1218 // Process properties as AVOptions
1219 char *fpre = mlt_properties_get( properties, "fpre" );
1222 mlt_properties p = mlt_properties_load( fpre );
1223 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM, 1 );
1224 #if LIBAVFORMAT_VERSION_MAJOR > 52
1225 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1226 apply_properties( oc->priv_data, p, AV_OPT_FLAG_ENCODING_PARAM, 1 );
1228 mlt_properties_close( p );
1230 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM, 0 );
1231 #if LIBAVFORMAT_VERSION_MAJOR > 52
1232 if ( oc->oformat && oc->oformat->priv_class && oc->priv_data )
1233 apply_properties( oc->priv_data, properties, AV_OPT_FLAG_ENCODING_PARAM, 1 );
1236 if ( video_st && !open_video( properties, oc, video_st, vcodec? vcodec : NULL ) )
1238 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1240 audio_input_frame_size = open_audio( properties, oc, audio_st[i], audio_outbuf_size,
1241 acodec? acodec : NULL );
1242 if ( !audio_input_frame_size )
1246 // Open the output file, if needed
1247 if ( !( fmt->flags & AVFMT_NOFILE ) )
1249 #if LIBAVFORMAT_VERSION_MAJOR > 52
1250 if ( avio_open( &oc->pb, filename, AVIO_FLAG_WRITE ) < 0 )
1252 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1255 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1256 mlt_properties_set_int( properties, "running", 0 );
1260 // Write the stream header.
1261 if ( mlt_properties_get_int( properties, "running" ) )
1262 av_write_header( oc );
1266 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1267 mlt_properties_set_int( properties, "running", 0 );
1272 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1274 // Last check - need at least one stream
1275 if ( !audio_st[0] && !video_st )
1276 mlt_properties_set_int( properties, "running", 0 );
1278 // Get the starting time (can ignore the times above)
1279 gettimeofday( &ante, NULL );
1281 // Loop while running
1282 while( mlt_properties_get_int( properties, "running" ) &&
1283 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1285 frame = mlt_consumer_rt_frame( consumer );
1287 // Check that we have a frame to work with
1288 if ( frame != NULL )
1290 // Increment frames dispatched
1293 // Default audio args
1294 frame_properties = MLT_FRAME_PROPERTIES( frame );
1296 // Check for the terminated condition
1297 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1299 // Get audio and append to the fifo
1300 if ( !terminated && audio_st[0] )
1302 samples = mlt_sample_calculator( fps, frequency, count ++ );
1303 mlt_frame_get_audio( frame, (void**) &pcm, &aud_fmt, &frequency, &channels, &samples );
1305 // Save the audio channel remap properties for later
1306 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1308 // Create the fifo if we don't have one
1311 fifo = sample_fifo_init( frequency, channels );
1312 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1315 // Silence if not normal forward speed
1316 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1317 memset( pcm, 0, samples * channels * 2 );
1319 // Append the samples
1320 sample_fifo_append( fifo, pcm, samples * channels );
1321 total_time += ( samples * 1000000 ) / frequency;
1324 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1328 if ( !terminated && video_st )
1329 mlt_deque_push_back( queue, frame );
1331 mlt_frame_close( frame );
1334 // While we have stuff to process, process...
1337 // Write interleaved audio and video frames
1338 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1341 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1343 int j = 0; // channel offset into interleaved source buffer
1344 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) ), AUDIO_ENCODE_BUFFER_SIZE );
1346 // Get the audio samples
1349 sample_fifo_fetch( fifo, audio_buf_1, n );
1351 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1353 // This prevents an infinite loop when some versions of vorbis do not
1354 // increment pts when encoding silence.
1355 audio_pts = video_pts;
1360 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1362 samples = n / channels;
1364 // For each output stream
1365 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1367 AVStream *stream = audio_st[i];
1368 AVCodecContext *codec = stream->codec;
1371 av_init_packet( &pkt );
1373 // Optimized for single track and no channel remap
1374 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1376 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1380 // Extract the audio channels according to channel mapping
1381 int dest_offset = 0; // channel offset into interleaved dest buffer
1383 // Get the number of channels for this stream
1384 sprintf( key, "channels.%d", i );
1385 int current_channels = mlt_properties_get_int( properties, key );
1387 // Clear the destination audio buffer.
1389 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1391 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1393 // For each output channel
1394 while ( dest_offset < current_channels && j < total_channels )
1396 int map_start = -1, map_channels = 0;
1397 int source_offset = 0;
1400 // Look for a mapping that starts at j
1401 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1403 sprintf( key, "%d.channels", k );
1404 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1405 sprintf( key, "%d.start", k );
1406 if ( mlt_properties_get( frame_meta_properties, key ) )
1407 map_start = mlt_properties_get_int( frame_meta_properties, key );
1408 if ( map_start != j )
1409 source_offset += map_channels;
1413 if ( map_start != j )
1415 map_channels = current_channels;
1419 // Copy samples if source offset valid
1420 if ( source_offset < channels )
1422 // Interleave the audio buffer with the # channels for this stream/mapping.
1423 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1425 int16_t *src = audio_buf_1 + source_offset;
1426 int16_t *dest = audio_buf_2 + dest_offset;
1427 int s = samples + 1;
1431 dest += current_channels;
1436 // Otherwise silence
1439 j += current_channels;
1440 dest_offset += current_channels;
1443 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_2 );
1446 // Write the compressed frame in the media file
1447 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1449 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1450 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %"PRId64" frame pts %"PRId64,
1451 stream->index, pkt.pts, codec->coded_frame->pts );
1453 pkt.flags |= PKT_FLAG_KEY;
1454 pkt.stream_index = stream->index;
1455 pkt.data = audio_outbuf;
1459 if ( av_interleaved_write_frame( oc, &pkt ) )
1461 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1462 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1463 goto on_fatal_error;
1467 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1470 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1479 else if ( video_st )
1482 if ( mlt_deque_count( queue ) )
1484 int out_size, ret = 0;
1487 frame = mlt_deque_pop_front( queue );
1488 frame_properties = MLT_FRAME_PROPERTIES( frame );
1490 c = video_st->codec;
1492 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1498 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1502 // Convert the mlt frame to an AVPicture
1503 for ( i = 0; i < height; i ++ )
1505 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1506 memcpy( p, q, width * 2 );
1510 // Do the colour space conversion
1512 int flags = SWS_BILINEAR;
1514 flags |= SWS_CPU_CAPS_MMX;
1517 flags |= SWS_CPU_CAPS_MMX2;
1519 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1520 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1521 sws_scale( context, (const uint8_t* const*) input->data, input->linesize, 0, height,
1522 output->data, output->linesize);
1523 sws_freeContext( context );
1525 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1528 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1530 // Apply the alpha if applicable
1531 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1533 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1536 for ( i = 0; i < height; i ++ )
1538 n = ( width + 7 ) / 8;
1539 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1543 case 0: do { *p = *alpha++; p += 4;
1544 case 7: *p = *alpha++; p += 4;
1545 case 6: *p = *alpha++; p += 4;
1546 case 5: *p = *alpha++; p += 4;
1547 case 4: *p = *alpha++; p += 4;
1548 case 3: *p = *alpha++; p += 4;
1549 case 2: *p = *alpha++; p += 4;
1550 case 1: *p = *alpha++; p += 4;
1558 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1560 // raw video case. The API will change slightly in the near future for that
1562 av_init_packet(&pkt);
1564 pkt.flags |= PKT_FLAG_KEY;
1565 pkt.stream_index= video_st->index;
1566 pkt.data= (uint8_t *)output;
1567 pkt.size= sizeof(AVPicture);
1569 ret = av_write_frame(oc, &pkt);
1570 video_pts += c->frame_size;
1575 output->quality = video_st->quality;
1577 // Set frame interlace hints
1578 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1579 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1580 output->pts = frame_count;
1583 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1585 // If zero size, it means the image was buffered
1589 av_init_packet( &pkt );
1591 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1592 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1593 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %"PRId64" frame pts %"PRId64, pkt.pts, c->coded_frame->pts );
1594 if( c->coded_frame && c->coded_frame->key_frame )
1595 pkt.flags |= PKT_FLAG_KEY;
1596 pkt.stream_index= video_st->index;
1597 pkt.data= video_outbuf;
1600 // write the compressed frame in the media file
1601 ret = av_interleaved_write_frame(oc, &pkt);
1602 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1603 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1605 // Dual pass logging
1606 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1607 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1609 else if ( out_size < 0 )
1611 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1617 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1618 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1619 goto on_fatal_error;
1621 mlt_frame_close( frame );
1629 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %"PRId64" (%f) ", audio_st[0]->pts.val, audio_pts );
1631 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %"PRId64" (%f) ", video_st->pts.val, video_pts );
1632 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1635 if ( real_time_output == 1 && frames % 2 == 0 )
1637 long passed = time_difference( &ante );
1640 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1643 if ( passed < total_time )
1645 long total = ( total_time - passed );
1646 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1647 nanosleep( &t, NULL );
1652 // Flush the encoder buffers
1653 if ( real_time_output <= 0 )
1656 // TODO: flush all audio streams
1657 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1659 AVCodecContext *c = audio_st[0]->codec;
1661 av_init_packet( &pkt );
1664 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1665 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1667 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size );
1668 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1670 if ( pkt.size <= 0 )
1671 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1672 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1673 if ( pkt.size <= 0 )
1676 // Write the compressed frame in the media file
1677 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1678 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1679 pkt.flags |= PKT_FLAG_KEY;
1680 pkt.stream_index = audio_st[0]->index;
1681 pkt.data = audio_outbuf;
1682 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1684 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1685 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1686 goto on_fatal_error;
1691 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1693 AVCodecContext *c = video_st->codec;
1695 av_init_packet( &pkt );
1698 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1699 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1700 if ( pkt.size <= 0 )
1703 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1704 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1705 if( c->coded_frame && c->coded_frame->key_frame )
1706 pkt.flags |= PKT_FLAG_KEY;
1707 pkt.stream_index = video_st->index;
1708 pkt.data = video_outbuf;
1710 // write the compressed frame in the media file
1711 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1713 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1714 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1715 goto on_fatal_error;
1717 // Dual pass logging
1718 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1719 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1725 // Write the trailer, if any
1726 av_write_trailer( oc );
1730 close_video(oc, video_st);
1731 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1732 close_audio( oc, audio_st[i] );
1735 for ( i = 0; i < oc->nb_streams; i++ )
1736 av_freep( &oc->streams[i] );
1738 // Close the output file
1739 if ( !( fmt->flags & AVFMT_NOFILE ) )
1740 #if LIBAVFORMAT_VERSION_MAJOR > 52
1741 avio_close( oc->pb );
1742 #elif LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1743 url_fclose( oc->pb );
1745 url_fclose( &oc->pb );
1748 // Clean up input and output frames
1750 av_free( output->data[0] );
1752 av_free( input->data[0] );
1754 av_free( video_outbuf );
1755 av_free( audio_buf_1 );
1756 av_free( audio_buf_2 );
1761 // Just in case we terminated on pause
1762 mlt_properties_set_int( properties, "running", 0 );
1764 mlt_consumer_stopped( consumer );
1765 mlt_properties_close( frame_meta_properties );
1767 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1769 // Remove the dual pass log file
1770 if ( mlt_properties_get( properties, "_logfilename" ) )
1771 remove( mlt_properties_get( properties, "_logfilename" ) );
1773 // Remove the x264 dual pass logs
1774 char *cwd = getcwd( NULL, 0 );
1775 const char *file = "x264_2pass.log";
1776 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1777 sprintf( full, "%s/%s", cwd, file );
1780 file = "x264_2pass.log.temp";
1781 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1782 sprintf( full, "%s/%s", cwd, file );
1785 file = "x264_2pass.log.mbtree";
1786 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1787 sprintf( full, "%s/%s", cwd, file );
1791 remove( "x264_2pass.log.temp" );
1797 /** Close the consumer.
1800 static void consumer_close( mlt_consumer consumer )
1802 // Stop the consumer
1803 mlt_consumer_stop( consumer );
1806 mlt_consumer_close( consumer );