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 #include <libavcodec/opt.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 > 52
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
59 #define MAX_AUDIO_STREAMS (8)
60 #define AUDIO_ENCODE_BUFFER_SIZE (48000 * 2 * MAX_AUDIO_STREAMS)
61 #define AUDIO_BUFFER_SIZE (1024 * 42)
62 #define VIDEO_BUFFER_SIZE (2048 * 1024)
64 void avformat_lock( );
65 void avformat_unlock( );
68 // This structure should be extended and made globally available in mlt
80 *sample_fifo, sample_fifo_s;
82 sample_fifo sample_fifo_init( int frequency, int channels )
84 sample_fifo fifo = calloc( 1, sizeof( sample_fifo_s ) );
85 fifo->frequency = frequency;
86 fifo->channels = channels;
90 // sample_fifo_clear and check are temporarily aborted (not working as intended)
92 void sample_fifo_clear( sample_fifo fifo, double time )
94 int words = ( float )( time - fifo->time ) * fifo->frequency * fifo->channels;
95 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )fifo->time * 100 ) && fifo->used > words && words > 0 )
97 memmove( fifo->buffer, &fifo->buffer[ words ], ( fifo->used - words ) * sizeof( int16_t ) );
101 else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )fifo->time * 100 ) )
108 void sample_fifo_check( sample_fifo fifo, double time )
110 if ( fifo->used == 0 )
112 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )fifo->time * 100 ) )
117 void sample_fifo_append( sample_fifo fifo, int16_t *samples, int count )
119 if ( ( fifo->size - fifo->used ) < count )
121 fifo->size += count * 5;
122 fifo->buffer = realloc( fifo->buffer, fifo->size * sizeof( int16_t ) );
125 memcpy( &fifo->buffer[ fifo->used ], samples, count * sizeof( int16_t ) );
129 int sample_fifo_used( sample_fifo fifo )
134 int sample_fifo_fetch( sample_fifo fifo, int16_t *samples, int count )
136 if ( count > fifo->used )
139 memcpy( samples, fifo->buffer, count * sizeof( int16_t ) );
141 memmove( fifo->buffer, &fifo->buffer[ count ], fifo->used * sizeof( int16_t ) );
143 fifo->time += ( double )count / fifo->channels / fifo->frequency;
148 void sample_fifo_close( sample_fifo fifo )
150 free( fifo->buffer );
154 // Forward references.
155 static int consumer_start( mlt_consumer consumer );
156 static int consumer_stop( mlt_consumer consumer );
157 static int consumer_is_stopped( mlt_consumer consumer );
158 static void *consumer_thread( void *arg );
159 static void consumer_close( mlt_consumer consumer );
161 /** Initialise the consumer.
164 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
166 // Allocate the consumer
167 mlt_consumer consumer = mlt_consumer_new( profile );
169 // If memory allocated and initialises without error
170 if ( consumer != NULL )
172 // Get properties from the consumer
173 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
175 // Assign close callback
176 consumer->close = consumer_close;
178 // Interpret the argument
180 mlt_properties_set( properties, "target", arg );
182 // sample and frame queue
183 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
185 // Audio options not fully handled by AVOptions
186 #define QSCALE_NONE (-99999)
187 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
189 // Video options not fully handled by AVOptions
190 mlt_properties_set_int( properties, "dc", 8 );
192 // Muxer options not fully handled by AVOptions
193 mlt_properties_set_double( properties, "muxdelay", 0.7 );
194 mlt_properties_set_double( properties, "muxpreload", 0.5 );
196 // Ensure termination at end of the stream
197 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
199 // Default to separate processing threads for producer and consumer with no frame dropping!
200 mlt_properties_set_int( properties, "real_time", -1 );
201 mlt_properties_set_int( properties, "prefill", 1 );
203 // Set up start/stop/terminated callbacks
204 consumer->start = consumer_start;
205 consumer->stop = consumer_stop;
206 consumer->is_stopped = consumer_is_stopped;
208 mlt_events_register( properties, "consumer-fatal-error", NULL );
215 /** Start the consumer.
218 static int consumer_start( mlt_consumer consumer )
220 // Get the properties
221 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
224 // Report information about available muxers and codecs as YAML Tiny
225 char *s = mlt_properties_get( properties, "f" );
226 if ( s && strcmp( s, "list" ) == 0 )
228 mlt_properties doc = mlt_properties_new();
229 mlt_properties formats = mlt_properties_new();
231 AVOutputFormat *format = NULL;
233 mlt_properties_set_data( properties, "f", formats, 0, (mlt_destructor) mlt_properties_close, NULL );
234 mlt_properties_set_data( doc, "formats", formats, 0, NULL, NULL );
235 while ( ( format = av_oformat_next( format ) ) )
237 snprintf( key, sizeof(key), "%d", mlt_properties_count( formats ) );
238 mlt_properties_set( formats, key, format->name );
240 fprintf( stderr, "%s", mlt_properties_serialise_yaml( doc ) );
241 mlt_properties_close( doc );
244 s = mlt_properties_get( properties, "acodec" );
245 if ( s && strcmp( s, "list" ) == 0 )
247 mlt_properties doc = mlt_properties_new();
248 mlt_properties codecs = mlt_properties_new();
250 AVCodec *codec = NULL;
252 mlt_properties_set_data( properties, "acodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
253 mlt_properties_set_data( doc, "audio_codecs", codecs, 0, NULL, NULL );
254 while ( ( codec = av_codec_next( codec ) ) )
255 if ( codec->encode && codec->type == CODEC_TYPE_AUDIO )
257 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
258 mlt_properties_set( codecs, key, codec->name );
260 fprintf( stderr, "%s", mlt_properties_serialise_yaml( doc ) );
261 mlt_properties_close( doc );
264 s = mlt_properties_get( properties, "vcodec" );
265 if ( s && strcmp( s, "list" ) == 0 )
267 mlt_properties doc = mlt_properties_new();
268 mlt_properties codecs = mlt_properties_new();
270 AVCodec *codec = NULL;
272 mlt_properties_set_data( properties, "vcodec", codecs, 0, (mlt_destructor) mlt_properties_close, NULL );
273 mlt_properties_set_data( doc, "video_codecs", codecs, 0, NULL, NULL );
274 while ( ( codec = av_codec_next( codec ) ) )
275 if ( codec->encode && codec->type == CODEC_TYPE_VIDEO )
277 snprintf( key, sizeof(key), "%d", mlt_properties_count( codecs ) );
278 mlt_properties_set( codecs, key, codec->name );
280 fprintf( stderr, "%s", mlt_properties_serialise_yaml( doc ) );
281 mlt_properties_close( doc );
285 // Check that we're not already running
286 if ( !error && !mlt_properties_get_int( properties, "running" ) )
289 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
291 // Get the width and height
292 int width = mlt_properties_get_int( properties, "width" );
293 int height = mlt_properties_get_int( properties, "height" );
295 // Obtain the size property
296 char *size = mlt_properties_get( properties, "s" );
302 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
309 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Invalid size property %s - ignoring.\n", size );
313 // Now ensure we honour the multiple of two requested by libavformat
314 width = ( width / 2 ) * 2;
315 height = ( height / 2 ) * 2;
316 mlt_properties_set_int( properties, "width", width );
317 mlt_properties_set_int( properties, "height", height );
319 // We need to set these on the profile as well because the s property is
320 // an alias to mlt properties that correspond to profile settings.
321 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
324 profile->width = width;
325 profile->height = height;
328 // Handle the ffmpeg command line "-r" property for frame rate
329 if ( mlt_properties_get( properties, "r" ) )
331 double frame_rate = mlt_properties_get_double( properties, "r" );
332 AVRational rational = av_d2q( frame_rate, 255 );
333 mlt_properties_set_int( properties, "frame_rate_num", rational.num );
334 mlt_properties_set_int( properties, "frame_rate_den", rational.den );
337 profile->frame_rate_num = rational.num;
338 profile->frame_rate_den = rational.den;
339 mlt_properties_set_double( properties, "fps", mlt_profile_fps( profile ) );
343 // Apply AVOptions that are synonyms for standard mlt_consumer options
344 if ( mlt_properties_get( properties, "ac" ) )
345 mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
346 if ( mlt_properties_get( properties, "ar" ) )
347 mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
349 // Assign the thread to properties
350 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
352 // Set the running state
353 mlt_properties_set_int( properties, "running", 1 );
356 pthread_create( thread, NULL, consumer_thread, consumer );
361 /** Stop the consumer.
364 static int consumer_stop( mlt_consumer consumer )
366 // Get the properties
367 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
369 // Check that we're running
370 if ( mlt_properties_get_int( properties, "running" ) )
373 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
376 mlt_properties_set_int( properties, "running", 0 );
378 // Wait for termination
379 pthread_join( *thread, NULL );
385 /** Determine if the consumer is stopped.
388 static int consumer_is_stopped( mlt_consumer consumer )
390 // Get the properties
391 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
392 return !mlt_properties_get_int( properties, "running" );
395 /** Process properties as AVOptions and apply to AV context obj
398 static void apply_properties( void *obj, mlt_properties properties, int flags, int alloc )
401 int count = mlt_properties_count( properties );
402 for ( i = 0; i < count; i++ )
404 const char *opt_name = mlt_properties_get_name( properties, i );
405 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
407 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
408 av_set_string3( obj, opt_name, mlt_properties_get_value( properties, i), alloc, NULL );
409 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
410 av_set_string2( obj, opt_name, mlt_properties_get_value( properties, i), alloc );
412 av_set_string( obj, opt_name, mlt_properties_get_value( properties, i) );
417 /** Add an audio output stream
420 static AVStream *add_audio_stream( mlt_consumer consumer, AVFormatContext *oc, int codec_id, int channels )
422 // Get the properties
423 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
425 // Create a new stream
426 AVStream *st = av_new_stream( oc, oc->nb_streams );
428 // If created, then initialise from properties
431 AVCodecContext *c = st->codec;
433 // Establish defaults from AVOptions
434 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
436 c->codec_id = codec_id;
437 c->codec_type = CODEC_TYPE_AUDIO;
438 c->sample_fmt = SAMPLE_FMT_S16;
440 #if 0 // disabled until some audio codecs are multi-threaded
441 // Setup multi-threading
442 int thread_count = mlt_properties_get_int( properties, "threads" );
443 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
444 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
445 if ( thread_count > 1 )
446 c->thread_count = thread_count;
449 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
450 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
452 // Allow the user to override the audio fourcc
453 if ( mlt_properties_get( properties, "atag" ) )
456 char *arg = mlt_properties_get( properties, "atag" );
457 int tag = strtol( arg, &tail, 0);
459 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
463 // Process properties as AVOptions
464 char *apre = mlt_properties_get( properties, "apre" );
467 mlt_properties p = mlt_properties_load( apre );
468 apply_properties( c, p, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
469 mlt_properties_close( p );
471 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
473 int audio_qscale = mlt_properties_get_int( properties, "aq" );
474 if ( audio_qscale > QSCALE_NONE )
476 c->flags |= CODEC_FLAG_QSCALE;
477 c->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
480 // Set parameters controlled by MLT
481 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
482 c->time_base = ( AVRational ){ 1, c->sample_rate };
483 c->channels = channels;
485 if ( mlt_properties_get( properties, "alang" ) != NULL )
486 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
487 av_metadata_set2( &oc->metadata, "language", mlt_properties_get( properties, "alang" ), 0 );
490 strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
495 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for audio\n" );
501 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size, const char *codec_name )
503 // We will return the audio input size from here
504 int audio_input_frame_size = 0;
507 AVCodecContext *c = st->codec;
512 codec = avcodec_find_encoder_by_name( codec_name );
514 codec = avcodec_find_encoder( c->codec_id );
518 // Continue if codec found and we can open it
519 if ( codec != NULL && avcodec_open( c, codec ) >= 0 )
521 // ugly hack for PCM codecs (will be removed ASAP with new PCM
522 // support to compute the input frame size in samples
523 if ( c->frame_size <= 1 )
525 audio_input_frame_size = audio_outbuf_size / c->channels;
526 switch(st->codec->codec_id)
528 case CODEC_ID_PCM_S16LE:
529 case CODEC_ID_PCM_S16BE:
530 case CODEC_ID_PCM_U16LE:
531 case CODEC_ID_PCM_U16BE:
532 audio_input_frame_size >>= 1;
540 audio_input_frame_size = c->frame_size;
543 // Some formats want stream headers to be seperate (hmm)
544 if ( !strcmp( oc->oformat->name, "mp4" ) ||
545 !strcmp( oc->oformat->name, "mov" ) ||
546 !strcmp( oc->oformat->name, "3gp" ) )
547 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
551 mlt_log_warning( NULL, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
556 return audio_input_frame_size;
559 static void close_audio( AVFormatContext *oc, AVStream *st )
561 if ( st && st->codec )
564 avcodec_close( st->codec );
569 /** Add a video output stream
572 static AVStream *add_video_stream( mlt_consumer consumer, AVFormatContext *oc, int codec_id )
574 // Get the properties
575 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
577 // Create a new stream
578 AVStream *st = av_new_stream( oc, oc->nb_streams );
582 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
583 AVCodecContext *c = st->codec;
585 // Establish defaults from AVOptions
586 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
588 c->codec_id = codec_id;
589 c->codec_type = CODEC_TYPE_VIDEO;
591 // Setup multi-threading
592 int thread_count = mlt_properties_get_int( properties, "threads" );
593 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
594 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
595 if ( thread_count > 1 )
596 c->thread_count = thread_count;
598 // Process properties as AVOptions
599 char *vpre = mlt_properties_get( properties, "vpre" );
602 mlt_properties p = mlt_properties_load( vpre );
604 if ( mlt_properties_count( p ) < 1 )
606 AVCodec *codec = avcodec_find_encoder( c->codec_id );
609 char *path = malloc( strlen(AVDATADIR) + strlen(codec->name) + strlen(vpre) + strlen(".ffpreset") + 2 );
610 strcpy( path, AVDATADIR );
611 strcat( path, codec->name );
613 strcat( path, vpre );
614 strcat( path, ".ffpreset" );
616 mlt_properties_close( p );
617 p = mlt_properties_load( path );
618 mlt_properties_debug( p, path, stderr );
624 mlt_properties_debug( p, vpre, stderr );
627 apply_properties( c, p, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 1 );
628 mlt_properties_close( p );
630 int colorspace = mlt_properties_get_int( properties, "colorspace" );
631 mlt_properties_set( properties, "colorspace", NULL );
632 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, 0 );
633 mlt_properties_set_int( properties, "colorspace", colorspace );
635 // Set options controlled by MLT
636 c->width = mlt_properties_get_int( properties, "width" );
637 c->height = mlt_properties_get_int( properties, "height" );
638 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
639 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
640 if ( st->time_base.den == 0 )
641 st->time_base = c->time_base;
642 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(8<<8)+0)
643 c->pix_fmt = pix_fmt ? av_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
645 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
648 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
649 switch ( colorspace )
652 c->colorspace = AVCOL_SPC_SMPTE170M;
655 c->colorspace = AVCOL_SPC_SMPTE240M;
658 c->colorspace = AVCOL_SPC_BT470BG;
661 c->colorspace = ( 576 % c->height ) ? AVCOL_SPC_SMPTE170M : AVCOL_SPC_BT470BG;
664 c->colorspace = AVCOL_SPC_BT709;
669 if ( mlt_properties_get( properties, "aspect" ) )
671 // "-aspect" on ffmpeg command line is display aspect ratio
672 double ar = mlt_properties_get_double( properties, "aspect" );
673 AVRational rational = av_d2q( ar, 255 );
675 // Update the profile and properties as well since this is an alias
676 // for mlt properties that correspond to profile settings
677 mlt_properties_set_int( properties, "display_aspect_num", rational.num );
678 mlt_properties_set_int( properties, "display_aspect_den", rational.den );
679 mlt_profile profile = mlt_service_profile( MLT_CONSUMER_SERVICE( consumer ) );
682 profile->display_aspect_num = rational.num;
683 profile->display_aspect_den = rational.den;
684 mlt_properties_set_double( properties, "display_ratio", mlt_profile_dar( profile ) );
687 // Now compute the sample aspect ratio
688 rational = av_d2q( ar * c->height / c->width, 255 );
689 c->sample_aspect_ratio = rational;
690 // Update the profile and properties as well since this is an alias
691 // for mlt properties that correspond to profile settings
692 mlt_properties_set_int( properties, "sample_aspect_num", rational.num );
693 mlt_properties_set_int( properties, "sample_aspect_den", rational.den );
696 profile->sample_aspect_num = rational.num;
697 profile->sample_aspect_den = rational.den;
698 mlt_properties_set_double( properties, "aspect_ratio", mlt_profile_sar( profile ) );
703 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
704 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
706 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
707 st->sample_aspect_ratio = c->sample_aspect_ratio;
710 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
712 c->flags |= CODEC_FLAG_QSCALE;
713 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
716 // Allow the user to override the video fourcc
717 if ( mlt_properties_get( properties, "vtag" ) )
720 const char *arg = mlt_properties_get( properties, "vtag" );
721 int tag = strtol( arg, &tail, 0);
723 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
727 // Some formats want stream headers to be seperate
728 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
729 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
731 // Translate these standard mlt consumer properties to ffmpeg
732 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
733 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
735 if ( ! mlt_properties_get( properties, "ildct" ) || mlt_properties_get_int( properties, "ildct" ) )
736 c->flags |= CODEC_FLAG_INTERLACED_DCT;
737 if ( ! mlt_properties_get( properties, "ilme" ) || mlt_properties_get_int( properties, "ilme" ) )
738 c->flags |= CODEC_FLAG_INTERLACED_ME;
741 // parse the ratecontrol override string
743 char *rc_override = mlt_properties_get( properties, "rc_override" );
744 for ( i = 0; rc_override; i++ )
747 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
749 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "Error parsing rc_override\n" );
750 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
751 c->rc_override[i].start_frame = start;
752 c->rc_override[i].end_frame = end;
755 c->rc_override[i].qscale = q;
756 c->rc_override[i].quality_factor = 1.0;
760 c->rc_override[i].qscale = 0;
761 c->rc_override[i].quality_factor = -q / 100.0;
763 rc_override = strchr( rc_override, '/' );
767 c->rc_override_count = i;
768 if ( !c->rc_initial_buffer_occupancy )
769 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
770 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
773 i = mlt_properties_get_int( properties, "pass" );
775 c->flags |= CODEC_FLAG_PASS1;
777 c->flags |= CODEC_FLAG_PASS2;
778 if ( codec_id != CODEC_ID_H264 && ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) ) )
780 char logfilename[1024];
785 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
786 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
787 if ( c->flags & CODEC_FLAG_PASS1 )
789 f = fopen( logfilename, "w" );
791 perror( logfilename );
793 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
797 /* read the log file */
798 f = fopen( logfilename, "r" );
805 mlt_properties_set( properties, "_logfilename", logfilename );
806 fseek( f, 0, SEEK_END );
808 fseek( f, 0, SEEK_SET );
809 logbuffer = av_malloc( size + 1 );
811 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate log buffer\n" );
814 size = fread( logbuffer, 1, size, f );
816 logbuffer[size] = '\0';
817 c->stats_in = logbuffer;
818 mlt_properties_set_data( properties, "_logbuffer", logbuffer, 0, ( mlt_destructor )av_free, NULL );
826 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not allocate a stream for video\n" );
832 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
835 AVFrame *picture = avcodec_alloc_frame();
837 // Determine size of the
838 int size = avpicture_get_size(pix_fmt, width, height);
840 // Allocate the picture buf
841 uint8_t *picture_buf = av_malloc(size);
843 // If we have both, then fill the image
844 if ( picture != NULL && picture_buf != NULL )
846 // Fill the frame with the allocated buffer
847 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
851 // Something failed - clean up what we can
853 av_free( picture_buf );
860 static int open_video(AVFormatContext *oc, AVStream *st, const char *codec_name)
863 AVCodecContext *video_enc = st->codec;
865 // find the video encoder
868 codec = avcodec_find_encoder_by_name( codec_name );
870 codec = avcodec_find_encoder( video_enc->codec_id );
872 if( codec && codec->pix_fmts )
874 const enum PixelFormat *p = codec->pix_fmts;
877 if( *p == video_enc->pix_fmt )
881 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
884 // Open the codec safely
886 int result = codec != NULL && avcodec_open( video_enc, codec ) >= 0;
892 void close_video(AVFormatContext *oc, AVStream *st)
894 if ( st && st->codec )
897 avcodec_close(st->codec);
902 static inline long time_difference( struct timeval *time1 )
904 struct timeval time2;
905 gettimeofday( &time2, NULL );
906 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
909 /** The main thread - the argument is simply the consumer.
912 static void *consumer_thread( void *arg )
914 // Map the argument to the object
915 mlt_consumer consumer = arg;
917 // Get the properties
918 mlt_properties properties = MLT_CONSUMER_PROPERTIES( consumer );
920 // Get the terminate on pause property
921 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
924 // Determine if feed is slow (for realtime stuff)
925 int real_time_output = mlt_properties_get_int( properties, "real_time" );
930 // Get the frame rate
931 double fps = mlt_properties_get_double( properties, "fps" );
933 // Get width and height
934 int width = mlt_properties_get_int( properties, "width" );
935 int height = mlt_properties_get_int( properties, "height" );
936 int img_width = width;
937 int img_height = height;
939 // Get default audio properties
940 mlt_audio_format aud_fmt = mlt_audio_s16;
941 int channels = mlt_properties_get_int( properties, "channels" );
942 int total_channels = channels;
943 int frequency = mlt_properties_get_int( properties, "frequency" );
947 // AVFormat audio buffer and frame size
948 int audio_outbuf_size = AUDIO_BUFFER_SIZE;
949 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
950 int audio_input_frame_size = 0;
952 // AVFormat video buffer and frame count
954 int video_outbuf_size = VIDEO_BUFFER_SIZE;
955 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
957 // Used for the frame properties
958 mlt_frame frame = NULL;
959 mlt_properties frame_properties = NULL;
962 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
963 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
965 // Need two av pictures for converting
966 AVFrame *output = NULL;
967 AVFrame *input = alloc_picture( PIX_FMT_YUYV422, width, height );
969 // For receiving images from an mlt_frame
971 mlt_image_format img_fmt = mlt_image_yuv422;
973 // For receiving audio samples back from the fifo
974 int16_t *audio_buf_1 = av_malloc( AUDIO_ENCODE_BUFFER_SIZE );
975 int16_t *audio_buf_2 = NULL;
978 // Allocate the context
979 #if (LIBAVFORMAT_VERSION_INT >= ((52<<16)+(26<<8)+0))
980 AVFormatContext *oc = avformat_alloc_context( );
982 AVFormatContext *oc = av_alloc_format_context( );
986 AVStream *video_st = NULL;
987 AVStream *audio_st[ MAX_AUDIO_STREAMS ];
990 double audio_pts = 0;
991 double video_pts = 0;
995 long int total_time = 0;
997 // Determine the format
998 AVOutputFormat *fmt = NULL;
999 const char *filename = mlt_properties_get( properties, "target" );
1000 char *format = mlt_properties_get( properties, "f" );
1001 char *vcodec = mlt_properties_get( properties, "vcodec" );
1002 char *acodec = mlt_properties_get( properties, "acodec" );
1004 // Used to store and override codec ids
1010 mlt_properties frame_meta_properties = mlt_properties_new();
1012 // Initialize audio_st
1013 int i = MAX_AUDIO_STREAMS;
1017 // Check for user selected format first
1018 if ( format != NULL )
1019 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1020 fmt = guess_format( format, NULL, NULL );
1022 fmt = av_guess_format( format, NULL, NULL );
1025 // Otherwise check on the filename
1026 if ( fmt == NULL && filename != NULL )
1027 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1028 fmt = guess_format( NULL, filename, NULL );
1030 fmt = av_guess_format( NULL, filename, NULL );
1033 // Otherwise default to mpeg
1035 #if LIBAVFORMAT_VERSION_INT < ((52<<16)+(45<<8)+0)
1036 fmt = guess_format( "mpeg", NULL, NULL );
1038 fmt = av_guess_format( "mpeg", NULL, NULL );
1041 // We need a filename - default to stdout?
1042 if ( filename == NULL || !strcmp( filename, "" ) )
1045 // Get the codec ids selected
1046 audio_codec_id = fmt->audio_codec;
1047 video_codec_id = fmt->video_codec;
1049 // Check for audio codec overides
1050 if ( ( acodec && strcmp( acodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "an" ) )
1051 audio_codec_id = CODEC_ID_NONE;
1054 AVCodec *p = avcodec_find_encoder_by_name( acodec );
1057 audio_codec_id = p->id;
1058 if ( audio_codec_id == CODEC_ID_AC3 && avcodec_find_encoder_by_name( "ac3_fixed" ) )
1060 mlt_properties_set( properties, "_acodec", "ac3_fixed" );
1061 acodec = mlt_properties_get( properties, "_acodec" );
1066 audio_codec_id = CODEC_ID_NONE;
1067 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "audio codec %s unrecognised - ignoring\n", acodec );
1071 // Check for video codec overides
1072 if ( ( vcodec && strcmp( vcodec, "none" ) == 0 ) || mlt_properties_get_int( properties, "vn" ) )
1073 video_codec_id = CODEC_ID_NONE;
1076 AVCodec *p = avcodec_find_encoder_by_name( vcodec );
1079 video_codec_id = p->id;
1083 video_codec_id = CODEC_ID_NONE;
1084 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "video codec %s unrecognised - ignoring\n", vcodec );
1089 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
1090 for ( i = 0; i < mlt_properties_count( properties ); i++ )
1092 char *name = mlt_properties_get_name( properties, i );
1093 if ( name && !strncmp( name, "meta.attr.", 10 ) )
1095 char *key = strdup( name + 10 );
1096 char *markup = strrchr( key, '.' );
1097 if ( markup && !strcmp( markup, ".markup") )
1100 if ( !strstr( key, ".stream." ) )
1101 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(43<<8)+0)
1102 av_metadata_set2( &oc->metadata, key, mlt_properties_get_value( properties, i ), 0 );
1104 av_metadata_set( &oc->metadata, key, mlt_properties_get_value( properties, i ) );
1114 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
1115 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
1117 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
1118 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
1120 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
1121 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
1123 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
1124 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
1126 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
1127 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
1129 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
1130 if (metavalue != 0) oc->year = metavalue;
1132 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
1133 if (metavalue != 0) oc->track = metavalue;
1137 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
1139 // Add audio and video streams
1140 if ( video_codec_id != CODEC_ID_NONE )
1141 video_st = add_video_stream( consumer, oc, video_codec_id );
1142 if ( audio_codec_id != CODEC_ID_NONE )
1148 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
1150 sprintf( key, "channels.%d", i );
1151 int j = mlt_properties_get_int( properties, key );
1155 total_channels += j;
1156 audio_st[i] = add_audio_stream( consumer, oc, audio_codec_id, j );
1162 audio_st[0] = add_audio_stream( consumer, oc, audio_codec_id, channels );
1163 total_channels = channels;
1167 // Set the parameters (even though we have none...)
1168 if ( av_set_parameters(oc, NULL) >= 0 )
1170 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
1171 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
1173 // Process properties as AVOptions
1174 char *fpre = mlt_properties_get( properties, "fpre" );
1177 mlt_properties p = mlt_properties_load( fpre );
1178 apply_properties( oc, p, AV_OPT_FLAG_ENCODING_PARAM, 1 );
1179 mlt_properties_close( p );
1181 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM, 0 );
1183 if ( video_st && !open_video( oc, video_st, vcodec? vcodec : NULL ) )
1185 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1187 audio_input_frame_size = open_audio( oc, audio_st[i], audio_outbuf_size,
1188 acodec? acodec : NULL );
1189 if ( !audio_input_frame_size )
1193 // Open the output file, if needed
1194 if ( !( fmt->flags & AVFMT_NOFILE ) )
1196 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
1198 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Could not open '%s'\n", filename );
1199 mlt_properties_set_int( properties, "running", 0 );
1203 // Write the stream header.
1204 if ( mlt_properties_get_int( properties, "running" ) )
1205 av_write_header( oc );
1209 mlt_log_error( MLT_CONSUMER_SERVICE( consumer ), "Invalid output format parameters\n" );
1210 mlt_properties_set_int( properties, "running", 0 );
1215 output = alloc_picture( video_st->codec->pix_fmt, width, height );
1217 // Last check - need at least one stream
1218 if ( !audio_st[0] && !video_st )
1219 mlt_properties_set_int( properties, "running", 0 );
1221 // Get the starting time (can ignore the times above)
1222 gettimeofday( &ante, NULL );
1224 // Loop while running
1225 while( mlt_properties_get_int( properties, "running" ) &&
1226 ( !terminated || ( video_st && mlt_deque_count( queue ) ) ) )
1228 frame = mlt_consumer_rt_frame( consumer );
1230 // Check that we have a frame to work with
1231 if ( frame != NULL )
1233 // Increment frames dispatched
1236 // Default audio args
1237 frame_properties = MLT_FRAME_PROPERTIES( frame );
1239 // Check for the terminated condition
1240 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
1242 // Get audio and append to the fifo
1243 if ( !terminated && audio_st[0] )
1245 samples = mlt_sample_calculator( fps, frequency, count ++ );
1246 mlt_frame_get_audio( frame, (void**) &pcm, &aud_fmt, &frequency, &channels, &samples );
1248 // Save the audio channel remap properties for later
1249 mlt_properties_pass( frame_meta_properties, frame_properties, "meta.map.audio." );
1251 // Create the fifo if we don't have one
1254 fifo = sample_fifo_init( frequency, channels );
1255 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
1258 // Silence if not normal forward speed
1259 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
1260 memset( pcm, 0, samples * channels * 2 );
1262 // Append the samples
1263 sample_fifo_append( fifo, pcm, samples * channels );
1264 total_time += ( samples * 1000000 ) / frequency;
1267 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1271 if ( !terminated && video_st )
1272 mlt_deque_push_back( queue, frame );
1274 mlt_frame_close( frame );
1277 // While we have stuff to process, process...
1280 // Write interleaved audio and video frames
1281 if ( !video_st || ( video_st && audio_st[0] && audio_pts < video_pts ) )
1284 if ( ( video_st && terminated ) || ( channels * audio_input_frame_size ) < sample_fifo_used( fifo ) )
1286 int j = 0; // channel offset into interleaved source buffer
1287 int n = FFMIN( FFMIN( channels * audio_input_frame_size, sample_fifo_used( fifo ) ), AUDIO_ENCODE_BUFFER_SIZE );
1289 // Get the audio samples
1292 sample_fifo_fetch( fifo, audio_buf_1, n );
1294 else if ( audio_codec_id == CODEC_ID_VORBIS && terminated )
1296 // This prevents an infinite loop when some versions of vorbis do not
1297 // increment pts when encoding silence.
1298 audio_pts = video_pts;
1303 memset( audio_buf_1, 0, AUDIO_ENCODE_BUFFER_SIZE );
1305 samples = n / channels;
1307 // For each output stream
1308 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i] && j < total_channels; i++ )
1310 AVStream *stream = audio_st[i];
1311 AVCodecContext *codec = stream->codec;
1314 av_init_packet( &pkt );
1316 // Optimized for single track and no channel remap
1317 if ( !audio_st[1] && !mlt_properties_count( frame_meta_properties ) )
1319 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1323 // Extract the audio channels according to channel mapping
1324 int dest_offset = 0; // channel offset into interleaved dest buffer
1326 // Get the number of channels for this stream
1327 sprintf( key, "channels.%d", i );
1328 int current_channels = mlt_properties_get_int( properties, key );
1330 // Clear the destination audio buffer.
1332 audio_buf_2 = av_mallocz( AUDIO_ENCODE_BUFFER_SIZE );
1334 memset( audio_buf_2, 0, AUDIO_ENCODE_BUFFER_SIZE );
1336 // For each output channel
1337 while ( dest_offset < current_channels && j < total_channels )
1339 int map_start = -1, map_channels = 0;
1340 int source_offset = 0;
1343 // Look for a mapping that starts at j
1344 for ( k = 0; k < (MAX_AUDIO_STREAMS * 2) && map_start != j; k++ )
1346 sprintf( key, "%d.channels", k );
1347 map_channels = mlt_properties_get_int( frame_meta_properties, key );
1348 sprintf( key, "%d.start", k );
1349 if ( mlt_properties_get( frame_meta_properties, key ) )
1350 map_start = mlt_properties_get_int( frame_meta_properties, key );
1351 if ( map_start != j )
1352 source_offset += map_channels;
1356 if ( map_start != j )
1358 map_channels = current_channels;
1362 // Copy samples if source offset valid
1363 if ( source_offset < channels )
1365 // Interleave the audio buffer with the # channels for this stream/mapping.
1366 for ( k = 0; k < map_channels; k++, j++, source_offset++, dest_offset++ )
1368 int16_t *src = audio_buf_1 + source_offset;
1369 int16_t *dest = audio_buf_2 + dest_offset;
1370 int s = samples + 1;
1374 dest += current_channels;
1379 // Otherwise silence
1382 j += current_channels;
1383 dest_offset += current_channels;
1386 pkt.size = avcodec_encode_audio( codec, audio_outbuf, audio_outbuf_size, audio_buf_2 );
1389 // Write the compressed frame in the media file
1390 if ( codec->coded_frame && codec->coded_frame->pts != AV_NOPTS_VALUE )
1392 pkt.pts = av_rescale_q( codec->coded_frame->pts, codec->time_base, stream->time_base );
1393 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio stream %d pkt pts %lld frame pts %lld",
1394 stream->index, pkt.pts, codec->coded_frame->pts );
1396 pkt.flags |= PKT_FLAG_KEY;
1397 pkt.stream_index = stream->index;
1398 pkt.data = audio_outbuf;
1402 if ( av_interleaved_write_frame( oc, &pkt ) )
1404 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing audio frame\n" );
1405 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1406 goto on_fatal_error;
1410 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", codec->frame_size );
1413 audio_pts = (double)stream->pts.val * av_q2d( stream->time_base );
1422 else if ( video_st )
1425 if ( mlt_deque_count( queue ) )
1427 int out_size, ret = 0;
1430 frame = mlt_deque_pop_front( queue );
1431 frame_properties = MLT_FRAME_PROPERTIES( frame );
1433 c = video_st->codec;
1435 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1441 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1445 // Convert the mlt frame to an AVPicture
1446 for ( i = 0; i < height; i ++ )
1448 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1449 memcpy( p, q, width * 2 );
1453 // Do the colour space conversion
1455 int flags = SWS_BILINEAR;
1457 flags |= SWS_CPU_CAPS_MMX;
1460 flags |= SWS_CPU_CAPS_MMX2;
1462 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUYV422,
1463 width, height, video_st->codec->pix_fmt, flags, NULL, NULL, NULL);
1464 sws_scale( context, input->data, input->linesize, 0, height,
1465 output->data, output->linesize);
1466 sws_freeContext( context );
1468 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUYV422, width, height );
1471 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1473 // Apply the alpha if applicable
1474 if ( video_st->codec->pix_fmt == PIX_FMT_RGB32 )
1476 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1479 for ( i = 0; i < height; i ++ )
1481 n = ( width + 7 ) / 8;
1482 p = output->data[ 0 ] + i * output->linesize[ 0 ] + 3;
1486 case 0: do { *p = *alpha++; p += 4;
1487 case 7: *p = *alpha++; p += 4;
1488 case 6: *p = *alpha++; p += 4;
1489 case 5: *p = *alpha++; p += 4;
1490 case 4: *p = *alpha++; p += 4;
1491 case 3: *p = *alpha++; p += 4;
1492 case 2: *p = *alpha++; p += 4;
1493 case 1: *p = *alpha++; p += 4;
1501 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1503 // raw video case. The API will change slightly in the near future for that
1505 av_init_packet(&pkt);
1507 pkt.flags |= PKT_FLAG_KEY;
1508 pkt.stream_index= video_st->index;
1509 pkt.data= (uint8_t *)output;
1510 pkt.size= sizeof(AVPicture);
1512 ret = av_write_frame(oc, &pkt);
1513 video_pts += c->frame_size;
1518 output->quality = video_st->quality;
1520 // Set frame interlace hints
1521 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1522 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1523 output->pts = frame_count;
1526 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1528 // If zero size, it means the image was buffered
1532 av_init_packet( &pkt );
1534 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1535 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1536 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pkt pts %lld frame pts %lld", pkt.pts, c->coded_frame->pts );
1537 if( c->coded_frame && c->coded_frame->key_frame )
1538 pkt.flags |= PKT_FLAG_KEY;
1539 pkt.stream_index= video_st->index;
1540 pkt.data= video_outbuf;
1543 // write the compressed frame in the media file
1544 ret = av_interleaved_write_frame(oc, &pkt);
1545 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), " frame_size %d\n", c->frame_size );
1546 video_pts = (double)video_st->pts.val * av_q2d( video_st->time_base );
1548 // Dual pass logging
1549 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1550 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1552 else if ( out_size < 0 )
1554 mlt_log_warning( MLT_CONSUMER_SERVICE( consumer ), "error with video encode %d\n", frame_count );
1560 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing video frame\n" );
1561 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1562 goto on_fatal_error;
1564 mlt_frame_close( frame );
1572 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "audio pts %lld (%f) ", audio_st[0]->pts.val, audio_pts );
1574 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "video pts %lld (%f) ", video_st->pts.val, video_pts );
1575 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "\n" );
1578 if ( real_time_output == 1 && frames % 2 == 0 )
1580 long passed = time_difference( &ante );
1583 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1586 if ( passed < total_time )
1588 long total = ( total_time - passed );
1589 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1590 nanosleep( &t, NULL );
1595 // Flush the encoder buffers
1596 if ( real_time_output <= 0 )
1599 // TODO: flush all audio streams
1600 if ( audio_st[0] && audio_st[0]->codec->frame_size > 1 ) for (;;)
1602 AVCodecContext *c = audio_st[0]->codec;
1604 av_init_packet( &pkt );
1607 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1608 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1610 sample_fifo_fetch( fifo, audio_buf_1, channels * audio_input_frame_size );
1611 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, audio_buf_1 );
1613 if ( pkt.size <= 0 )
1614 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1615 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing audio size %d\n", pkt.size );
1616 if ( pkt.size <= 0 )
1619 // Write the compressed frame in the media file
1620 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1621 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st[0]->time_base );
1622 pkt.flags |= PKT_FLAG_KEY;
1623 pkt.stream_index = audio_st[0]->index;
1624 pkt.data = audio_outbuf;
1625 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1627 mlt_log_fatal( MLT_CONSUMER_SERVICE( consumer ), "error writing flushed audio frame\n" );
1628 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1629 goto on_fatal_error;
1634 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1636 AVCodecContext *c = video_st->codec;
1638 av_init_packet( &pkt );
1641 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1642 mlt_log_debug( MLT_CONSUMER_SERVICE( consumer ), "flushing video size %d\n", pkt.size );
1643 if ( pkt.size <= 0 )
1646 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1647 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1648 if( c->coded_frame && c->coded_frame->key_frame )
1649 pkt.flags |= PKT_FLAG_KEY;
1650 pkt.stream_index = video_st->index;
1651 pkt.data = video_outbuf;
1653 // write the compressed frame in the media file
1654 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1656 mlt_log_fatal( MLT_CONSUMER_SERVICE(consumer), "error writing flushed video frame\n" );
1657 mlt_events_fire( properties, "consumer-fatal-error", NULL );
1658 goto on_fatal_error;
1660 // Dual pass logging
1661 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out )
1662 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1668 // Write the trailer, if any
1669 av_write_trailer( oc );
1673 close_video(oc, video_st);
1674 for ( i = 0; i < MAX_AUDIO_STREAMS && audio_st[i]; i++ )
1675 close_audio( oc, audio_st[i] );
1678 for ( i = 0; i < oc->nb_streams; i++ )
1679 av_freep( &oc->streams[i] );
1681 // Close the output file
1682 if ( !( fmt->flags & AVFMT_NOFILE ) )
1683 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1684 url_fclose( oc->pb );
1686 url_fclose( &oc->pb );
1689 // Clean up input and output frames
1691 av_free( output->data[0] );
1693 av_free( input->data[0] );
1695 av_free( video_outbuf );
1696 av_free( audio_buf_1 );
1697 av_free( audio_buf_2 );
1702 // Just in case we terminated on pause
1703 mlt_properties_set_int( properties, "running", 0 );
1705 mlt_consumer_stopped( consumer );
1706 mlt_properties_close( frame_meta_properties );
1708 if ( mlt_properties_get_int( properties, "pass" ) > 1 )
1710 // Remove the dual pass log file
1711 if ( mlt_properties_get( properties, "_logfilename" ) )
1712 remove( mlt_properties_get( properties, "_logfilename" ) );
1714 // Remove the x264 dual pass logs
1715 char *cwd = getcwd( NULL, 0 );
1716 const char *file = "x264_2pass.log";
1717 char *full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1718 sprintf( full, "%s/%s", cwd, file );
1721 file = "x264_2pass.log.temp";
1722 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1723 sprintf( full, "%s/%s", cwd, file );
1726 file = "x264_2pass.log.mbtree";
1727 full = malloc( strlen( cwd ) + strlen( file ) + 2 );
1728 sprintf( full, "%s/%s", cwd, file );
1732 remove( "x264_2pass.log.temp" );
1738 /** Close the consumer.
1741 static void consumer_close( mlt_consumer consumer )
1743 // Stop the consumer
1744 mlt_consumer_stop( consumer );
1747 mlt_consumer_close( consumer );