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>
26 // System header files
36 // avformat header files
44 // This structure should be extended and made globally available in mlt
56 *sample_fifo
, sample_fifo_s
;
58 sample_fifo
sample_fifo_init( int frequency
, int channels
)
60 sample_fifo
this = calloc( 1, sizeof( sample_fifo_s
) );
61 this->frequency
= frequency
;
62 this->channels
= channels
;
66 // sample_fifo_clear and check are temporarily aborted (not working as intended)
68 void sample_fifo_clear( sample_fifo
this, double time
)
70 int words
= ( float )( time
- this->time
) * this->frequency
* this->channels
;
71 if ( ( int )( ( float )time
* 100 ) < ( int )( ( float )this->time
* 100 ) && this->used
> words
&& words
> 0 )
73 memmove( this->buffer
, &this->buffer
[ words
], ( this->used
- words
) * sizeof( int16_t ) );
77 else if ( ( int )( ( float )time
* 100 ) != ( int )( ( float )this->time
* 100 ) )
84 void sample_fifo_check( sample_fifo
this, double time
)
86 if ( this->used
== 0 )
88 if ( ( int )( ( float )time
* 100 ) < ( int )( ( float )this->time
* 100 ) )
93 void sample_fifo_append( sample_fifo
this, int16_t *samples
, int count
)
95 if ( ( this->size
- this->used
) < count
)
97 this->size
+= count
* 5;
98 this->buffer
= realloc( this->buffer
, this->size
* sizeof( int16_t ) );
101 memcpy( &this->buffer
[ this->used
], samples
, count
* sizeof( int16_t ) );
105 int sample_fifo_used( sample_fifo
this )
110 int sample_fifo_fetch( sample_fifo
this, int16_t *samples
, int count
)
112 if ( count
> this->used
)
115 memcpy( samples
, this->buffer
, count
* sizeof( int16_t ) );
117 memmove( this->buffer
, &this->buffer
[ count
], this->used
* sizeof( int16_t ) );
119 this->time
+= ( double )count
/ this->channels
/ this->frequency
;
124 void sample_fifo_close( sample_fifo
this )
126 free( this->buffer
);
130 // Forward references.
131 static int consumer_start( mlt_consumer
this );
132 static int consumer_stop( mlt_consumer
this );
133 static int consumer_is_stopped( mlt_consumer
this );
134 static void *consumer_thread( void *arg
);
135 static void consumer_close( mlt_consumer
this );
137 /** Initialise the dv consumer.
140 mlt_consumer
consumer_avformat_init( mlt_profile profile
, char *arg
)
142 // Allocate the consumer
143 mlt_consumer
this = mlt_consumer_new( profile
);
145 // If memory allocated and initialises without error
148 // Get properties from the consumer
149 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
151 // Assign close callback
152 this->close
= consumer_close
;
154 // Interpret the argument
156 mlt_properties_set( properties
, "target", arg
);
158 // sample and frame queue
159 mlt_properties_set_data( properties
, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor
)mlt_deque_close
, NULL
);
161 // Audio options not fully handled by AVOptions
162 #define QSCALE_NONE (-99999)
163 mlt_properties_set_int( properties
, "aq", QSCALE_NONE
);
165 // Video options not fully handled by AVOptions
166 mlt_properties_set_int( properties
, "dc", 8 );
168 // Muxer options not fully handled by AVOptions
169 mlt_properties_set_double( properties
, "muxdelay", 0.7 );
170 mlt_properties_set_double( properties
, "muxpreload", 0.5 );
172 // Ensure termination at end of the stream
173 mlt_properties_set_int( properties
, "terminate_on_pause", 1 );
175 // Default to separate processing threads for producer and consumer with no frame dropping!
176 mlt_properties_set_int( properties
, "real_time", -1 );
178 // Set up start/stop/terminated callbacks
179 this->start
= consumer_start
;
180 this->stop
= consumer_stop
;
181 this->is_stopped
= consumer_is_stopped
;
188 /** Start the consumer.
191 static int consumer_start( mlt_consumer
this )
193 // Get the properties
194 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
197 // Report information about available muxers and codecs as YAML Tiny
198 char *s
= mlt_properties_get( properties
, "f" );
199 if ( s
&& strcmp( s
, "list" ) == 0 )
201 fprintf( stderr
, "---\nformats:\n" );
202 AVOutputFormat
*format
= NULL
;
203 while ( ( format
= av_oformat_next( format
) ) )
204 fprintf( stderr
, " - %s\n", format
->name
);
205 fprintf( stderr
, "...\n" );
208 s
= mlt_properties_get( properties
, "acodec" );
209 if ( s
&& strcmp( s
, "list" ) == 0 )
211 fprintf( stderr
, "---\naudio_codecs:\n" );
212 AVCodec
*codec
= NULL
;
213 while ( ( codec
= av_codec_next( codec
) ) )
214 if ( codec
->encode
&& codec
->type
== CODEC_TYPE_AUDIO
)
215 fprintf( stderr
, " - %s\n", codec
->name
);
216 fprintf( stderr
, "...\n" );
219 s
= mlt_properties_get( properties
, "vcodec" );
220 if ( s
&& strcmp( s
, "list" ) == 0 )
222 fprintf( stderr
, "---\nvideo_codecs:\n" );
223 AVCodec
*codec
= NULL
;
224 while ( ( codec
= av_codec_next( codec
) ) )
225 if ( codec
->encode
&& codec
->type
== CODEC_TYPE_VIDEO
)
226 fprintf( stderr
, " - %s\n", codec
->name
);
227 fprintf( stderr
, "...\n" );
231 // Check that we're not already running
232 if ( !error
&& !mlt_properties_get_int( properties
, "running" ) )
235 pthread_t
*thread
= calloc( 1, sizeof( pthread_t
) );
237 // Get the width and height
238 int width
= mlt_properties_get_int( properties
, "width" );
239 int height
= mlt_properties_get_int( properties
, "height" );
241 // Obtain the size property
242 char *size
= mlt_properties_get( properties
, "s" );
248 if ( sscanf( size
, "%dx%d", &tw
, &th
) == 2 && tw
> 0 && th
> 0 )
255 fprintf( stderr
, "%s: Invalid size property %s - ignoring.\n", __FILE__
, size
);
259 // Now ensure we honour the multiple of two requested by libavformat
260 width
= ( width
/ 2 ) * 2;
261 height
= ( height
/ 2 ) * 2;
262 mlt_properties_set_int( properties
, "width", width
);
263 mlt_properties_set_int( properties
, "height", height
);
265 // We need to set these on the profile as well because the s property is
266 // an alias to mlt properties that correspond to profile settings.
267 mlt_profile profile
= mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
270 profile
->width
= width
;
271 profile
->height
= height
;
274 // Handle the ffmpeg command line "-r" property for frame rate
275 if ( mlt_properties_get( properties
, "r" ) )
277 double frame_rate
= mlt_properties_get_double( properties
, "r" );
278 AVRational rational
= av_d2q( frame_rate
, 255 );
279 mlt_properties_set_int( properties
, "frame_rate_num", rational
.num
);
280 mlt_properties_set_int( properties
, "frame_rate_den", rational
.den
);
283 profile
->frame_rate_num
= rational
.num
;
284 profile
->frame_rate_den
= rational
.den
;
285 mlt_properties_set_double( properties
, "fps", mlt_profile_fps( profile
) );
289 // Apply AVOptions that are synonyms for standard mlt_consumer options
290 if ( mlt_properties_get( properties
, "ac" ) )
291 mlt_properties_set_int( properties
, "channels", mlt_properties_get_int( properties
, "ac" ) );
292 if ( mlt_properties_get( properties
, "ar" ) )
293 mlt_properties_set_int( properties
, "frequency", mlt_properties_get_int( properties
, "ar" ) );
295 // Assign the thread to properties
296 mlt_properties_set_data( properties
, "thread", thread
, sizeof( pthread_t
), free
, NULL
);
298 // Set the running state
299 mlt_properties_set_int( properties
, "running", 1 );
302 pthread_create( thread
, NULL
, consumer_thread
, this );
307 /** Stop the consumer.
310 static int consumer_stop( mlt_consumer
this )
312 // Get the properties
313 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
315 // Check that we're running
316 if ( mlt_properties_get_int( properties
, "running" ) )
319 pthread_t
*thread
= mlt_properties_get_data( properties
, "thread", NULL
);
322 mlt_properties_set_int( properties
, "running", 0 );
324 // Wait for termination
325 pthread_join( *thread
, NULL
);
331 /** Determine if the consumer is stopped.
334 static int consumer_is_stopped( mlt_consumer
this )
336 // Get the properties
337 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
338 return !mlt_properties_get_int( properties
, "running" );
341 /** Process properties as AVOptions and apply to AV context obj
344 static void apply_properties( void *obj
, mlt_properties properties
, int flags
)
347 int count
= mlt_properties_count( properties
);
348 for ( i
= 0; i
< count
; i
++ )
350 const char *opt_name
= mlt_properties_get_name( properties
, i
);
351 const AVOption
*opt
= av_find_opt( obj
, opt_name
, NULL
, flags
, flags
);
353 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
354 av_set_string3( obj
, opt_name
, mlt_properties_get( properties
, opt_name
), 0, NULL
);
355 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
356 av_set_string2( obj
, opt_name
, mlt_properties_get( properties
, opt_name
), 0 );
358 av_set_string( obj
, opt_name
, mlt_properties_get( properties
, opt_name
) );
363 /** Add an audio output stream
366 static AVStream
*add_audio_stream( mlt_consumer
this, AVFormatContext
*oc
, int codec_id
)
368 // Get the properties
369 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
371 // Create a new stream
372 AVStream
*st
= av_new_stream( oc
, 1 );
374 // If created, then initialise from properties
377 AVCodecContext
*c
= st
->codec
;
379 // Establish defaults from AVOptions
380 avcodec_get_context_defaults2( c
, CODEC_TYPE_AUDIO
);
382 c
->codec_id
= codec_id
;
383 c
->codec_type
= CODEC_TYPE_AUDIO
;
385 // Setup multi-threading
386 int thread_count
= mlt_properties_get_int( properties
, "threads" );
387 if ( thread_count
== 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
388 thread_count
= atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
389 if ( thread_count
> 1 )
390 avcodec_thread_init( c
, thread_count
);
392 if (oc
->oformat
->flags
& AVFMT_GLOBALHEADER
)
393 c
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
395 // Allow the user to override the audio fourcc
396 if ( mlt_properties_get( properties
, "atag" ) )
399 char *arg
= mlt_properties_get( properties
, "atag" );
400 int tag
= strtol( arg
, &tail
, 0);
402 tag
= arg
[ 0 ] + ( arg
[ 1 ] << 8 ) + ( arg
[ 2 ] << 16 ) + ( arg
[ 3 ] << 24 );
406 // Process properties as AVOptions
407 apply_properties( c
, properties
, AV_OPT_FLAG_AUDIO_PARAM
| AV_OPT_FLAG_ENCODING_PARAM
);
409 int audio_qscale
= mlt_properties_get_int( properties
, "aq" );
410 if ( audio_qscale
> QSCALE_NONE
)
412 c
->flags
|= CODEC_FLAG_QSCALE
;
413 c
->global_quality
= st
->quality
= FF_QP2LAMBDA
* audio_qscale
;
416 // Set parameters controlled by MLT
417 c
->sample_rate
= mlt_properties_get_int( properties
, "frequency" );
418 c
->channels
= mlt_properties_get_int( properties
, "channels" );
420 if ( mlt_properties_get( properties
, "alang" ) != NULL
)
421 strncpy( st
->language
, mlt_properties_get( properties
, "alang" ), sizeof( st
->language
) );
425 fprintf( stderr
, "%s: Could not allocate a stream for audio\n", __FILE__
);
431 static int open_audio( AVFormatContext
*oc
, AVStream
*st
, int audio_outbuf_size
)
433 // We will return the audio input size from here
434 int audio_input_frame_size
= 0;
437 AVCodecContext
*c
= st
->codec
;
440 AVCodec
*codec
= avcodec_find_encoder( c
->codec_id
);
442 // Continue if codec found and we can open it
443 if ( codec
!= NULL
&& avcodec_open( c
, codec
) >= 0 )
445 // ugly hack for PCM codecs (will be removed ASAP with new PCM
446 // support to compute the input frame size in samples
447 if ( c
->frame_size
<= 1 )
449 audio_input_frame_size
= audio_outbuf_size
/ c
->channels
;
450 switch(st
->codec
->codec_id
)
452 case CODEC_ID_PCM_S16LE
:
453 case CODEC_ID_PCM_S16BE
:
454 case CODEC_ID_PCM_U16LE
:
455 case CODEC_ID_PCM_U16BE
:
456 audio_input_frame_size
>>= 1;
464 audio_input_frame_size
= c
->frame_size
;
467 // Some formats want stream headers to be seperate (hmm)
468 if( !strcmp( oc
->oformat
->name
, "mp4" ) ||
469 !strcmp( oc
->oformat
->name
, "mov" ) ||
470 !strcmp( oc
->oformat
->name
, "3gp" ) )
471 c
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
475 fprintf( stderr
, "%s: Unable to encode audio - disabling audio output.\n", __FILE__
);
478 return audio_input_frame_size
;
481 static void close_audio( AVFormatContext
*oc
, AVStream
*st
)
483 avcodec_close( st
->codec
);
486 /** Add a video output stream
489 static AVStream
*add_video_stream( mlt_consumer
this, AVFormatContext
*oc
, int codec_id
)
491 // Get the properties
492 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
494 // Create a new stream
495 AVStream
*st
= av_new_stream( oc
, 0 );
499 char *pix_fmt
= mlt_properties_get( properties
, "pix_fmt" );
500 AVCodecContext
*c
= st
->codec
;
502 // Establish defaults from AVOptions
503 avcodec_get_context_defaults2( c
, CODEC_TYPE_VIDEO
);
505 c
->codec_id
= codec_id
;
506 c
->codec_type
= CODEC_TYPE_VIDEO
;
508 // Setup multi-threading
509 int thread_count
= mlt_properties_get_int( properties
, "threads" );
510 if ( thread_count
== 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
511 thread_count
= atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
512 if ( thread_count
> 1 )
513 avcodec_thread_init( c
, thread_count
);
515 // Process properties as AVOptions
516 apply_properties( c
, properties
, AV_OPT_FLAG_VIDEO_PARAM
| AV_OPT_FLAG_ENCODING_PARAM
);
518 // Set options controlled by MLT
519 c
->width
= mlt_properties_get_int( properties
, "width" );
520 c
->height
= mlt_properties_get_int( properties
, "height" );
521 c
->time_base
.num
= mlt_properties_get_int( properties
, "frame_rate_den" );
522 c
->time_base
.den
= mlt_properties_get_int( properties
, "frame_rate_num" );
523 if ( st
->time_base
.den
== 0 )
524 st
->time_base
= c
->time_base
;
525 c
->pix_fmt
= pix_fmt ?
avcodec_get_pix_fmt( pix_fmt
) : PIX_FMT_YUV420P
;
527 if ( mlt_properties_get( properties
, "aspect" ) )
529 // "-aspect" on ffmpeg command line is display aspect ratio
530 double ar
= mlt_properties_get_double( properties
, "aspect" );
531 AVRational rational
= av_d2q( ar
, 255 );
533 // Update the profile and properties as well since this is an alias
534 // for mlt properties that correspond to profile settings
535 mlt_properties_set_int( properties
, "display_aspect_num", rational
.num
);
536 mlt_properties_set_int( properties
, "display_aspect_den", rational
.den
);
537 mlt_profile profile
= mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
540 profile
->display_aspect_num
= rational
.num
;
541 profile
->display_aspect_den
= rational
.den
;
542 mlt_properties_set_double( properties
, "display_ratio", mlt_profile_dar( profile
) );
545 // Now compute the sample aspect ratio
546 rational
= av_d2q( ar
* c
->height
/ c
->width
, 255 );
547 c
->sample_aspect_ratio
= rational
;
548 // Update the profile and properties as well since this is an alias
549 // for mlt properties that correspond to profile settings
550 mlt_properties_set_int( properties
, "sample_aspect_num", rational
.num
);
551 mlt_properties_set_int( properties
, "sample_aspect_den", rational
.den
);
554 profile
->sample_aspect_num
= rational
.num
;
555 profile
->sample_aspect_den
= rational
.den
;
556 mlt_properties_set_double( properties
, "aspect_ratio", mlt_profile_sar( profile
) );
561 c
->sample_aspect_ratio
.num
= mlt_properties_get_int( properties
, "sample_aspect_num" );
562 c
->sample_aspect_ratio
.den
= mlt_properties_get_int( properties
, "sample_aspect_den" );
564 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
565 st
->sample_aspect_ratio
= c
->sample_aspect_ratio
;
568 if ( mlt_properties_get_double( properties
, "qscale" ) > 0 )
570 c
->flags
|= CODEC_FLAG_QSCALE
;
571 st
->quality
= FF_QP2LAMBDA
* mlt_properties_get_double( properties
, "qscale" );
574 // Allow the user to override the video fourcc
575 if ( mlt_properties_get( properties
, "vtag" ) )
578 const char *arg
= mlt_properties_get( properties
, "vtag" );
579 int tag
= strtol( arg
, &tail
, 0);
581 tag
= arg
[ 0 ] + ( arg
[ 1 ] << 8 ) + ( arg
[ 2 ] << 16 ) + ( arg
[ 3 ] << 24 );
585 // Some formats want stream headers to be seperate
586 if ( oc
->oformat
->flags
& AVFMT_GLOBALHEADER
)
587 c
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
589 // Translate these standard mlt consumer properties to ffmpeg
590 if ( mlt_properties_get_int( properties
, "progressive" ) == 0 &&
591 mlt_properties_get_int( properties
, "deinterlace" ) == 0 )
593 if ( mlt_properties_get_int( properties
, "ildct" ) )
594 c
->flags
|= CODEC_FLAG_INTERLACED_DCT
;
595 if ( mlt_properties_get_int( properties
, "ilme" ) )
596 c
->flags
|= CODEC_FLAG_INTERLACED_ME
;
599 // parse the ratecontrol override string
601 char *rc_override
= mlt_properties_get( properties
, "rc_override" );
602 for ( i
= 0; rc_override
; i
++ )
605 int e
= sscanf( rc_override
, "%d,%d,%d", &start
, &end
, &q
);
607 fprintf( stderr
, "%s: Error parsing rc_override\n", __FILE__
);
608 c
->rc_override
= av_realloc( c
->rc_override
, sizeof( RcOverride
) * ( i
+ 1 ) );
609 c
->rc_override
[i
].start_frame
= start
;
610 c
->rc_override
[i
].end_frame
= end
;
613 c
->rc_override
[i
].qscale
= q
;
614 c
->rc_override
[i
].quality_factor
= 1.0;
618 c
->rc_override
[i
].qscale
= 0;
619 c
->rc_override
[i
].quality_factor
= -q
/ 100.0;
621 rc_override
= strchr( rc_override
, '/' );
625 c
->rc_override_count
= i
;
626 if ( !c
->rc_initial_buffer_occupancy
)
627 c
->rc_initial_buffer_occupancy
= c
->rc_buffer_size
* 3/4;
628 c
->intra_dc_precision
= mlt_properties_get_int( properties
, "dc" ) - 8;
631 i
= mlt_properties_get_int( properties
, "pass" );
633 c
->flags
|= CODEC_FLAG_PASS1
;
635 c
->flags
|= CODEC_FLAG_PASS2
;
636 if ( codec_id
!= CODEC_ID_H264
&& ( c
->flags
& ( CODEC_FLAG_PASS1
| CODEC_FLAG_PASS2
) ) )
638 char logfilename
[1024];
643 snprintf( logfilename
, sizeof(logfilename
), "%s_2pass.log",
644 mlt_properties_get( properties
, "passlogfile" ) ?
mlt_properties_get( properties
, "passlogfile" ) : mlt_properties_get( properties
, "target" ) );
645 if ( c
->flags
& CODEC_FLAG_PASS1
)
647 f
= fopen( logfilename
, "w" );
649 perror( logfilename
);
651 mlt_properties_set_data( properties
, "_logfile", f
, 0, ( mlt_destructor
)fclose
, NULL
);
655 /* read the log file */
656 f
= fopen( logfilename
, "r" );
663 mlt_properties_set( properties
, "_logfilename", logfilename
);
664 fseek( f
, 0, SEEK_END
);
666 fseek( f
, 0, SEEK_SET
);
667 logbuffer
= av_malloc( size
+ 1 );
669 fprintf( stderr
, "%s: Could not allocate log buffer\n", __FILE__
);
672 size
= fread( logbuffer
, 1, size
, f
);
674 logbuffer
[size
] = '\0';
675 c
->stats_in
= logbuffer
;
676 mlt_properties_set_data( properties
, "_logbuffer", logbuffer
, 0, ( mlt_destructor
)av_free
, NULL
);
684 fprintf( stderr
, "%s: Could not allocate a stream for video\n", __FILE__
);
690 static AVFrame
*alloc_picture( int pix_fmt
, int width
, int height
)
693 AVFrame
*picture
= avcodec_alloc_frame();
695 // Determine size of the
696 int size
= avpicture_get_size(pix_fmt
, width
, height
);
698 // Allocate the picture buf
699 uint8_t *picture_buf
= av_malloc(size
);
701 // If we have both, then fill the image
702 if ( picture
!= NULL
&& picture_buf
!= NULL
)
704 // Fill the frame with the allocated buffer
705 avpicture_fill( (AVPicture
*)picture
, picture_buf
, pix_fmt
, width
, height
);
709 // Something failed - clean up what we can
711 av_free( picture_buf
);
718 static int open_video(AVFormatContext
*oc
, AVStream
*st
)
721 AVCodecContext
*video_enc
= st
->codec
;
723 // find the video encoder
724 AVCodec
*codec
= avcodec_find_encoder( video_enc
->codec_id
);
726 if( codec
&& codec
->pix_fmts
)
728 const enum PixelFormat
*p
= codec
->pix_fmts
;
731 if( *p
== video_enc
->pix_fmt
)
735 video_enc
->pix_fmt
= codec
->pix_fmts
[ 0 ];
738 // Open the codec safely
739 return codec
!= NULL
&& avcodec_open( video_enc
, codec
) >= 0;
742 void close_video(AVFormatContext
*oc
, AVStream
*st
)
744 avcodec_close(st
->codec
);
747 static inline long time_difference( struct timeval
*time1
)
749 struct timeval time2
;
750 gettimeofday( &time2
, NULL
);
751 return time2
.tv_sec
* 1000000 + time2
.tv_usec
- time1
->tv_sec
* 1000000 - time1
->tv_usec
;
754 /** The main thread - the argument is simply the consumer.
757 static void *consumer_thread( void *arg
)
759 // Map the argument to the object
760 mlt_consumer
this = arg
;
762 // Get the properties
763 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
765 // Get the terminate on pause property
766 int terminate_on_pause
= mlt_properties_get_int( properties
, "terminate_on_pause" );
769 // Determine if feed is slow (for realtime stuff)
770 int real_time_output
= mlt_properties_get_int( properties
, "real_time" );
775 // Get the frame rate
776 double fps
= mlt_properties_get_double( properties
, "fps" );
778 // Get width and height
779 int width
= mlt_properties_get_int( properties
, "width" );
780 int height
= mlt_properties_get_int( properties
, "height" );
781 int img_width
= width
;
782 int img_height
= height
;
784 // Get default audio properties
785 mlt_audio_format aud_fmt
= mlt_audio_pcm
;
786 int channels
= mlt_properties_get_int( properties
, "channels" );
787 int frequency
= mlt_properties_get_int( properties
, "frequency" );
791 // AVFormat audio buffer and frame size
792 int audio_outbuf_size
= 10000;
793 uint8_t *audio_outbuf
= av_malloc( audio_outbuf_size
);
794 int audio_input_frame_size
= 0;
796 // AVFormat video buffer and frame count
798 int video_outbuf_size
= ( 1024 * 1024 );
799 uint8_t *video_outbuf
= av_malloc( video_outbuf_size
);
801 // Used for the frame properties
802 mlt_frame frame
= NULL
;
803 mlt_properties frame_properties
= NULL
;
806 mlt_deque queue
= mlt_properties_get_data( properties
, "frame_queue", NULL
);
807 sample_fifo fifo
= mlt_properties_get_data( properties
, "sample_fifo", NULL
);
809 // Need two av pictures for converting
810 AVFrame
*output
= NULL
;
811 AVFrame
*input
= alloc_picture( PIX_FMT_YUV422
, width
, height
);
813 // For receiving images from an mlt_frame
815 mlt_image_format img_fmt
= mlt_image_yuv422
;
817 // For receiving audio samples back from the fifo
818 int16_t *buffer
= av_malloc( 48000 * 2 );
821 // Allocate the context
822 AVFormatContext
*oc
= av_alloc_format_context( );
825 AVStream
*audio_st
= NULL
;
826 AVStream
*video_st
= NULL
;
829 double audio_pts
= 0;
830 double video_pts
= 0;
837 long int total_time
= 0;
839 // Determine the format
840 AVOutputFormat
*fmt
= NULL
;
841 char *filename
= mlt_properties_get( properties
, "target" );
842 char *format
= mlt_properties_get( properties
, "f" );
843 char *vcodec
= mlt_properties_get( properties
, "vcodec" );
844 char *acodec
= mlt_properties_get( properties
, "acodec" );
846 // Used to store and override codec ids
850 // Check for user selected format first
851 if ( format
!= NULL
)
852 fmt
= guess_format( format
, NULL
, NULL
);
854 // Otherwise check on the filename
855 if ( fmt
== NULL
&& filename
!= NULL
)
856 fmt
= guess_format( NULL
, filename
, NULL
);
858 // Otherwise default to mpeg
860 fmt
= guess_format( "mpeg", NULL
, NULL
);
862 // We need a filename - default to stdout?
863 if ( filename
== NULL
|| !strcmp( filename
, "" ) )
866 // Get the codec ids selected
867 audio_codec_id
= fmt
->audio_codec
;
868 video_codec_id
= fmt
->video_codec
;
870 // Check for audio codec overides
871 if ( ( acodec
&& strcmp( "acodec", "none" ) == 0 ) || mlt_properties_get_int( properties
, "an" ) )
872 audio_codec_id
= CODEC_ID_NONE
;
875 AVCodec
*p
= avcodec_find_encoder_by_name( acodec
);
877 audio_codec_id
= p
->id
;
879 fprintf( stderr
, "%s: audio codec %s unrecognised - ignoring\n", __FILE__
, acodec
);
882 // Check for video codec overides
883 if ( ( vcodec
&& strcmp( "vcodec", "none" ) == 0 ) || mlt_properties_get_int( properties
, "vn" ) )
884 video_codec_id
= CODEC_ID_NONE
;
887 AVCodec
*p
= avcodec_find_encoder_by_name( vcodec
);
889 video_codec_id
= p
->id
;
891 fprintf( stderr
, "%s: video codec %s unrecognised - ignoring\n", __FILE__
, vcodec
);
898 tmp
= mlt_properties_get( properties
, "meta.attr.title.markup");
899 if (tmp
!= NULL
) snprintf( oc
->title
, sizeof(oc
->title
), "%s", tmp
);
901 tmp
= mlt_properties_get( properties
, "meta.attr.comment.markup");
902 if (tmp
!= NULL
) snprintf( oc
->comment
, sizeof(oc
->comment
), "%s", tmp
);
904 tmp
= mlt_properties_get( properties
, "meta.attr.author.markup");
905 if (tmp
!= NULL
) snprintf( oc
->author
, sizeof(oc
->author
), "%s", tmp
);
907 tmp
= mlt_properties_get( properties
, "meta.attr.copyright.markup");
908 if (tmp
!= NULL
) snprintf( oc
->copyright
, sizeof(oc
->copyright
), "%s", tmp
);
910 tmp
= mlt_properties_get( properties
, "meta.attr.album.markup");
911 if (tmp
!= NULL
) snprintf( oc
->album
, sizeof(oc
->album
), "%s", tmp
);
913 metavalue
= mlt_properties_get_int( properties
, "meta.attr.year.markup");
914 if (metavalue
!= 0) oc
->year
= metavalue
;
916 metavalue
= mlt_properties_get_int( properties
, "meta.attr.track.markup");
917 if (metavalue
!= 0) oc
->track
= metavalue
;
920 snprintf( oc
->filename
, sizeof(oc
->filename
), "%s", filename
);
922 // Add audio and video streams
923 if ( video_codec_id
!= CODEC_ID_NONE
)
924 video_st
= add_video_stream( this, oc
, video_codec_id
);
925 if ( audio_codec_id
!= CODEC_ID_NONE
)
926 audio_st
= add_audio_stream( this, oc
, audio_codec_id
);
928 // Set the parameters (even though we have none...)
929 if ( av_set_parameters(oc
, NULL
) >= 0 )
931 oc
->preload
= ( int )( mlt_properties_get_double( properties
, "muxpreload" ) * AV_TIME_BASE
);
932 oc
->max_delay
= ( int )( mlt_properties_get_double( properties
, "muxdelay" ) * AV_TIME_BASE
);
934 // Process properties as AVOptions
935 apply_properties( oc
, properties
, AV_OPT_FLAG_ENCODING_PARAM
);
937 if ( video_st
&& !open_video( oc
, video_st
) )
940 audio_input_frame_size
= open_audio( oc
, audio_st
, audio_outbuf_size
);
942 // Open the output file, if needed
943 if ( !( fmt
->flags
& AVFMT_NOFILE
) )
945 if ( url_fopen( &oc
->pb
, filename
, URL_WRONLY
) < 0 )
947 fprintf( stderr
, "%s: Could not open '%s'\n", __FILE__
, filename
);
948 mlt_properties_set_int( properties
, "running", 0 );
952 // Write the stream header, if any
953 if ( mlt_properties_get_int( properties
, "running" ) )
954 av_write_header( oc
);
958 fprintf( stderr
, "%s: Invalid output format parameters\n", __FILE__
);
959 mlt_properties_set_int( properties
, "running", 0 );
964 output
= alloc_picture( video_st
->codec
->pix_fmt
, width
, height
);
966 // Last check - need at least one stream
967 if ( audio_st
== NULL
&& video_st
== NULL
)
968 mlt_properties_set_int( properties
, "running", 0 );
970 // Get the starting time (can ignore the times above)
971 gettimeofday( &ante
, NULL
);
973 // Loop while running
974 while( mlt_properties_get_int( properties
, "running" ) && !terminated
)
977 frame
= mlt_consumer_rt_frame( this );
979 // Check that we have a frame to work with
982 // Increment frames despatched
985 // Default audio args
986 frame_properties
= MLT_FRAME_PROPERTIES( frame
);
988 // Check for the terminated condition
989 terminated
= terminate_on_pause
&& mlt_properties_get_double( frame_properties
, "_speed" ) == 0.0;
991 // Get audio and append to the fifo
992 if ( !terminated
&& audio_st
)
994 samples
= mlt_sample_calculator( fps
, frequency
, count
++ );
995 mlt_frame_get_audio( frame
, &pcm
, &aud_fmt
, &frequency
, &channels
, &samples
);
997 // Create the fifo if we don't have one
1000 fifo
= sample_fifo_init( frequency
, channels
);
1001 mlt_properties_set_data( properties
, "sample_fifo", fifo
, 0, ( mlt_destructor
)sample_fifo_close
, NULL
);
1004 if ( mlt_properties_get_double( frame_properties
, "_speed" ) != 1.0 )
1005 memset( pcm
, 0, samples
* channels
* 2 );
1007 // Append the samples
1008 sample_fifo_append( fifo
, pcm
, samples
* channels
);
1009 total_time
+= ( samples
* 1000000 ) / frequency
;
1013 if ( !terminated
&& video_st
)
1014 mlt_deque_push_back( queue
, frame
);
1016 mlt_frame_close( frame
);
1019 // While we have stuff to process, process...
1023 audio_pts
= (double)audio_st
->pts
.val
* audio_st
->time_base
.num
/ audio_st
->time_base
.den
;
1028 video_pts
= (double)video_st
->pts
.val
* video_st
->time_base
.num
/ video_st
->time_base
.den
;
1032 // Write interleaved audio and video frames
1033 if ( !video_st
|| ( video_st
&& audio_st
&& audio_pts
< video_pts
) )
1035 if ( channels
* audio_input_frame_size
< sample_fifo_used( fifo
) )
1039 av_init_packet( &pkt
);
1041 c
= audio_st
->codec
;
1043 sample_fifo_fetch( fifo
, buffer
, channels
* audio_input_frame_size
);
1045 pkt
.size
= avcodec_encode_audio( c
, audio_outbuf
, audio_outbuf_size
, buffer
);
1046 // Write the compressed frame in the media file
1047 if ( c
->coded_frame
&& c
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
1048 pkt
.pts
= av_rescale_q( c
->coded_frame
->pts
, c
->time_base
, audio_st
->time_base
);
1049 pkt
.flags
|= PKT_FLAG_KEY
;
1050 pkt
.stream_index
= audio_st
->index
;
1051 pkt
.data
= audio_outbuf
;
1054 if ( av_interleaved_write_frame( oc
, &pkt
) != 0)
1055 fprintf( stderr
, "%s: Error while writing audio frame\n", __FILE__
);
1057 audio_pts
+= c
->frame_size
;
1064 else if ( video_st
)
1066 if ( mlt_deque_count( queue
) )
1071 frame
= mlt_deque_pop_front( queue
);
1072 frame_properties
= MLT_FRAME_PROPERTIES( frame
);
1074 c
= video_st
->codec
;
1076 if ( mlt_properties_get_int( frame_properties
, "rendered" ) )
1083 mlt_events_fire( properties
, "consumer-frame-show", frame
, NULL
);
1085 mlt_frame_get_image( frame
, &image
, &img_fmt
, &img_width
, &img_height
, 0 );
1089 // Convert the mlt frame to an AVPicture
1090 for ( i
= 0; i
< height
; i
++ )
1092 p
= input
->data
[ 0 ] + i
* input
->linesize
[ 0 ];
1101 // Do the colour space conversion
1103 struct SwsContext
*context
= sws_getContext( width
, height
, PIX_FMT_YUV422
,
1104 width
, height
, video_st
->codec
->pix_fmt
, SWS_FAST_BILINEAR
, NULL
, NULL
, NULL
);
1105 sws_scale( context
, input
->data
, input
->linesize
, 0, height
,
1106 output
->data
, output
->linesize
);
1107 sws_freeContext( context
);
1109 img_convert( ( AVPicture
* )output
, video_st
->codec
->pix_fmt
, ( AVPicture
* )input
, PIX_FMT_YUV422
, width
, height
);
1112 // Apply the alpha if applicable
1113 if ( video_st
->codec
->pix_fmt
== PIX_FMT_RGBA32
)
1115 uint8_t *alpha
= mlt_frame_get_alpha_mask( frame
);
1118 for ( i
= 0; i
< height
; i
++ )
1120 n
= ( width
+ 7 ) / 8;
1121 p
= output
->data
[ 0 ] + i
* output
->linesize
[ 0 ];
1129 case 0: do { *p
= *alpha
++; p
+= 4;
1130 case 7: *p
= *alpha
++; p
+= 4;
1131 case 6: *p
= *alpha
++; p
+= 4;
1132 case 5: *p
= *alpha
++; p
+= 4;
1133 case 4: *p
= *alpha
++; p
+= 4;
1134 case 3: *p
= *alpha
++; p
+= 4;
1135 case 2: *p
= *alpha
++; p
+= 4;
1136 case 1: *p
= *alpha
++; p
+= 4;
1144 if (oc
->oformat
->flags
& AVFMT_RAWPICTURE
)
1146 // raw video case. The API will change slightly in the near future for that
1148 av_init_packet(&pkt
);
1150 pkt
.flags
|= PKT_FLAG_KEY
;
1151 pkt
.stream_index
= video_st
->index
;
1152 pkt
.data
= (uint8_t *)output
;
1153 pkt
.size
= sizeof(AVPicture
);
1155 ret
= av_write_frame(oc
, &pkt
);
1156 video_pts
+= c
->frame_size
;
1161 output
->quality
= video_st
->quality
;
1163 // Set frame interlace hints
1164 output
->interlaced_frame
= !mlt_properties_get_int( frame_properties
, "progressive" );
1165 output
->top_field_first
= mlt_properties_get_int( frame_properties
, "top_field_first" );
1168 out_size
= avcodec_encode_video(c
, video_outbuf
, video_outbuf_size
, output
);
1170 // If zero size, it means the image was buffered
1174 av_init_packet( &pkt
);
1176 if ( c
->coded_frame
&& c
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
1177 pkt
.pts
= av_rescale_q( c
->coded_frame
->pts
, c
->time_base
, video_st
->time_base
);
1178 if( c
->coded_frame
&& c
->coded_frame
->key_frame
)
1179 pkt
.flags
|= PKT_FLAG_KEY
;
1180 pkt
.stream_index
= video_st
->index
;
1181 pkt
.data
= video_outbuf
;
1184 // write the compressed frame in the media file
1185 ret
= av_interleaved_write_frame(oc
, &pkt
);
1186 video_pts
+= c
->frame_size
;
1188 // Dual pass logging
1189 if ( mlt_properties_get_data( properties
, "_logfile", NULL
) && c
->stats_out
)
1190 fprintf( mlt_properties_get_data( properties
, "_logfile", NULL
), "%s", c
->stats_out
);
1194 fprintf( stderr
, "%s: error with video encode\n", __FILE__
);
1198 mlt_frame_close( frame
);
1207 if ( real_time_output
== 1 && frames
% 12 == 0 )
1209 long passed
= time_difference( &ante
);
1212 long pending
= ( ( ( long )sample_fifo_used( fifo
) * 1000 ) / frequency
) * 1000;
1215 if ( passed
< total_time
)
1217 long total
= ( total_time
- passed
);
1218 struct timespec t
= { total
/ 1000000, ( total
% 1000000 ) * 1000 };
1219 nanosleep( &t
, NULL
);
1225 if ( ! real_time_output
)
1228 if ( audio_st
&& audio_st
->codec
->frame_size
> 1 ) for (;;)
1230 AVCodecContext
*c
= audio_st
->codec
;
1232 av_init_packet( &pkt
);
1235 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1236 ( channels
* audio_input_frame_size
< sample_fifo_used( fifo
) ) )
1238 sample_fifo_fetch( fifo
, buffer
, channels
* audio_input_frame_size
);
1239 pkt
.size
= avcodec_encode_audio( c
, audio_outbuf
, audio_outbuf_size
, buffer
);
1241 if ( pkt
.size
<= 0 )
1242 pkt
.size
= avcodec_encode_audio( c
, audio_outbuf
, audio_outbuf_size
, NULL
);
1243 if ( pkt
.size
<= 0 )
1246 // Write the compressed frame in the media file
1247 if ( c
->coded_frame
&& c
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
1248 pkt
.pts
= av_rescale_q( c
->coded_frame
->pts
, c
->time_base
, audio_st
->time_base
);
1249 pkt
.flags
|= PKT_FLAG_KEY
;
1250 pkt
.stream_index
= audio_st
->index
;
1251 pkt
.data
= audio_outbuf
;
1252 if ( av_interleaved_write_frame( oc
, &pkt
) != 0 )
1254 fprintf( stderr
, "%s: Error while writing flushed audio frame\n", __FILE__
);
1260 if ( video_st
&& !( oc
->oformat
->flags
& AVFMT_RAWPICTURE
) ) for (;;)
1262 AVCodecContext
*c
= video_st
->codec
;
1264 av_init_packet( &pkt
);
1267 pkt
.size
= avcodec_encode_video( c
, video_outbuf
, video_outbuf_size
, NULL
);
1268 if ( pkt
.size
<= 0 )
1271 if ( c
->coded_frame
&& c
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
1272 pkt
.pts
= av_rescale_q( c
->coded_frame
->pts
, c
->time_base
, video_st
->time_base
);
1273 if( c
->coded_frame
&& c
->coded_frame
->key_frame
)
1274 pkt
.flags
|= PKT_FLAG_KEY
;
1275 pkt
.stream_index
= video_st
->index
;
1276 pkt
.data
= video_outbuf
;
1278 // write the compressed frame in the media file
1279 if ( av_interleaved_write_frame( oc
, &pkt
) != 0 )
1281 fprintf( stderr
, "%s: Error while writing flushed video frame\n". __FILE__
);
1290 close_video(oc
, video_st
);
1292 close_audio(oc
, audio_st
);
1294 // Write the trailer, if any
1295 av_write_trailer(oc
);
1298 for(i
= 0; i
< oc
->nb_streams
; i
++)
1299 av_freep(&oc
->streams
[i
]);
1301 // Close the output file
1302 if (!(fmt
->flags
& AVFMT_NOFILE
))
1303 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1306 url_fclose(&oc
->pb
);
1309 // Clean up input and output frames
1311 av_free( output
->data
[0] );
1313 av_free( input
->data
[0] );
1315 av_free( video_outbuf
);
1321 // Just in case we terminated on pause
1322 mlt_properties_set_int( properties
, "running", 0 );
1324 mlt_consumer_stopped( this );
1326 if ( mlt_properties_get_int( properties
, "pass" ) == 2 )
1328 // Remove the dual pass log file
1329 if ( mlt_properties_get( properties
, "_logfilename" ) )
1330 remove( mlt_properties_get( properties
, "_logfilename" ) );
1332 // Remove the x264 dual pass logs
1333 char *cwd
= getcwd( NULL
, 0 );
1334 char *file
= "x264_2pass.log";
1335 char *full
= malloc( strlen( cwd
) + strlen( file
) + 2 );
1336 sprintf( full
, "%s/%s", cwd
, file
);
1339 file
= "x264_2pass.log.temp";
1340 full
= malloc( strlen( cwd
) + strlen( file
) + 2 );
1341 sprintf( full
, "%s/%s", cwd
, file
);
1345 remove( "x264_2pass.log.temp" );
1351 /** Close the consumer.
1354 static void consumer_close( mlt_consumer
this )
1356 // Stop the consumer
1357 mlt_consumer_stop( this );
1360 mlt_consumer_close( this );