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
35 // avformat header files
43 // This structure should be extended and made globally available in mlt
55 *sample_fifo
, sample_fifo_s
;
57 sample_fifo
sample_fifo_init( int frequency
, int channels
)
59 sample_fifo
this = calloc( 1, sizeof( sample_fifo_s
) );
60 this->frequency
= frequency
;
61 this->channels
= channels
;
65 // sample_fifo_clear and check are temporarily aborted (not working as intended)
67 void sample_fifo_clear( sample_fifo
this, double time
)
69 int words
= ( float )( time
- this->time
) * this->frequency
* this->channels
;
70 if ( ( int )( ( float )time
* 100 ) < ( int )( ( float )this->time
* 100 ) && this->used
> words
&& words
> 0 )
72 memmove( this->buffer
, &this->buffer
[ words
], ( this->used
- words
) * sizeof( int16_t ) );
76 else if ( ( int )( ( float )time
* 100 ) != ( int )( ( float )this->time
* 100 ) )
83 void sample_fifo_check( sample_fifo
this, double time
)
85 if ( this->used
== 0 )
87 if ( ( int )( ( float )time
* 100 ) < ( int )( ( float )this->time
* 100 ) )
92 void sample_fifo_append( sample_fifo
this, int16_t *samples
, int count
)
94 if ( ( this->size
- this->used
) < count
)
96 this->size
+= count
* 5;
97 this->buffer
= realloc( this->buffer
, this->size
* sizeof( int16_t ) );
100 memcpy( &this->buffer
[ this->used
], samples
, count
* sizeof( int16_t ) );
104 int sample_fifo_used( sample_fifo
this )
109 int sample_fifo_fetch( sample_fifo
this, int16_t *samples
, int count
)
111 if ( count
> this->used
)
114 memcpy( samples
, this->buffer
, count
* sizeof( int16_t ) );
116 memmove( this->buffer
, &this->buffer
[ count
], this->used
* sizeof( int16_t ) );
118 this->time
+= ( double )count
/ this->channels
/ this->frequency
;
123 void sample_fifo_close( sample_fifo
this )
125 free( this->buffer
);
129 // Forward references.
130 static int consumer_start( mlt_consumer
this );
131 static int consumer_stop( mlt_consumer
this );
132 static int consumer_is_stopped( mlt_consumer
this );
133 static void *consumer_thread( void *arg
);
134 static void consumer_close( mlt_consumer
this );
136 /** Initialise the dv consumer.
139 mlt_consumer
consumer_avformat_init( mlt_profile profile
, char *arg
)
141 // Allocate the consumer
142 mlt_consumer
this = mlt_consumer_new( profile
);
144 // If memory allocated and initialises without error
147 // Get properties from the consumer
148 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
150 // Assign close callback
151 this->close
= consumer_close
;
153 // Interpret the argument
155 mlt_properties_set( properties
, "target", arg
);
157 // sample and frame queue
158 mlt_properties_set_data( properties
, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor
)mlt_deque_close
, NULL
);
160 // Audio options not fully handled by AVOptions
161 #define QSCALE_NONE (-99999)
162 mlt_properties_set_int( properties
, "aq", QSCALE_NONE
);
164 // Video options not fully handled by AVOptions
165 mlt_properties_set_int( properties
, "dc", 8 );
167 // Muxer options not fully handled by AVOptions
168 mlt_properties_set_double( properties
, "muxdelay", 0.7 );
169 mlt_properties_set_double( properties
, "muxpreload", 0.5 );
171 // Ensure termination at end of the stream
172 mlt_properties_set_int( properties
, "terminate_on_pause", 1 );
174 // Default to separate processing threads for producer and consumer with no frame dropping!
175 mlt_properties_set_int( properties
, "real_time", -1 );
177 // Set up start/stop/terminated callbacks
178 this->start
= consumer_start
;
179 this->stop
= consumer_stop
;
180 this->is_stopped
= consumer_is_stopped
;
187 /** Start the consumer.
190 static int consumer_start( mlt_consumer
this )
192 // Get the properties
193 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
195 // Check that we're not already running
196 if ( !mlt_properties_get_int( properties
, "running" ) )
199 pthread_t
*thread
= calloc( 1, sizeof( pthread_t
) );
201 // Get the width and height
202 int width
= mlt_properties_get_int( properties
, "width" );
203 int height
= mlt_properties_get_int( properties
, "height" );
205 // Obtain the size property
206 char *size
= mlt_properties_get( properties
, "s" );
212 if ( sscanf( size
, "%dx%d", &tw
, &th
) == 2 && tw
> 0 && th
> 0 )
219 fprintf( stderr
, "%s: Invalid size property %s - ignoring.\n", __FILE__
, size
);
223 // Now ensure we honour the multiple of two requested by libavformat
224 width
= ( width
/ 2 ) * 2;
225 height
= ( height
/ 2 ) * 2;
226 mlt_properties_set_int( properties
, "width", width
);
227 mlt_properties_set_int( properties
, "height", height
);
229 // We need to set these on the profile as well because the s property is
230 // an alias to mlt properties that correspond to profile settings.
231 mlt_profile profile
= mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
234 profile
->width
= width
;
235 profile
->height
= height
;
238 // Handle the ffmpeg command line "-r" property for frame rate
239 if ( mlt_properties_get( properties
, "r" ) )
241 double frame_rate
= mlt_properties_get_double( properties
, "r" );
242 AVRational rational
= av_d2q( frame_rate
, 255 );
243 mlt_properties_set_int( properties
, "frame_rate_num", rational
.num
);
244 mlt_properties_set_int( properties
, "frame_rate_den", rational
.den
);
247 profile
->frame_rate_num
= rational
.num
;
248 profile
->frame_rate_den
= rational
.den
;
249 mlt_properties_set_double( properties
, "fps", mlt_profile_fps( profile
) );
253 // Apply AVOptions that are synonyms for standard mlt_consumer options
254 if ( mlt_properties_get( properties
, "ac" ) )
255 mlt_properties_set_int( properties
, "channels", mlt_properties_get_int( properties
, "ac" ) );
256 if ( mlt_properties_get( properties
, "ar" ) )
257 mlt_properties_set_int( properties
, "frequency", mlt_properties_get_int( properties
, "ar" ) );
259 // Assign the thread to properties
260 mlt_properties_set_data( properties
, "thread", thread
, sizeof( pthread_t
), free
, NULL
);
262 // Set the running state
263 mlt_properties_set_int( properties
, "running", 1 );
266 pthread_create( thread
, NULL
, consumer_thread
, this );
271 /** Stop the consumer.
274 static int consumer_stop( mlt_consumer
this )
276 // Get the properties
277 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
279 // Check that we're running
280 if ( mlt_properties_get_int( properties
, "running" ) )
283 pthread_t
*thread
= mlt_properties_get_data( properties
, "thread", NULL
);
286 mlt_properties_set_int( properties
, "running", 0 );
288 // Wait for termination
289 pthread_join( *thread
, NULL
);
295 /** Determine if the consumer is stopped.
298 static int consumer_is_stopped( mlt_consumer
this )
300 // Get the properties
301 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
302 return !mlt_properties_get_int( properties
, "running" );
305 /** Process properties as AVOptions and apply to AV context obj
308 static void apply_properties( void *obj
, mlt_properties properties
, int flags
)
311 int count
= mlt_properties_count( properties
);
312 for ( i
= 0; i
< count
; i
++ )
314 const char *opt_name
= mlt_properties_get_name( properties
, i
);
315 const AVOption
*opt
= av_find_opt( obj
, opt_name
, NULL
, flags
, flags
);
317 #if LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
318 av_set_string2( obj
, opt_name
, mlt_properties_get( properties
, opt_name
), 0 );
320 av_set_string( obj
, opt_name
, mlt_properties_get( properties
, opt_name
) );
325 /** Add an audio output stream
328 static AVStream
*add_audio_stream( mlt_consumer
this, AVFormatContext
*oc
, int codec_id
)
330 // Get the properties
331 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
333 // Create a new stream
334 AVStream
*st
= av_new_stream( oc
, 1 );
336 // If created, then initialise from properties
339 AVCodecContext
*c
= st
->codec
;
341 // Establish defaults from AVOptions
342 avcodec_get_context_defaults2( c
, CODEC_TYPE_AUDIO
);
344 c
->codec_id
= codec_id
;
345 c
->codec_type
= CODEC_TYPE_AUDIO
;
347 // Setup multi-threading
348 int thread_count
= mlt_properties_get_int( properties
, "threads" );
349 if ( thread_count
== 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
350 thread_count
= atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
351 if ( thread_count
> 1 )
352 avcodec_thread_init( c
, thread_count
);
354 if (oc
->oformat
->flags
& AVFMT_GLOBALHEADER
)
355 c
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
357 // Allow the user to override the audio fourcc
358 if ( mlt_properties_get( properties
, "atag" ) )
361 char *arg
= mlt_properties_get( properties
, "atag" );
362 int tag
= strtol( arg
, &tail
, 0);
364 tag
= arg
[ 0 ] + ( arg
[ 1 ] << 8 ) + ( arg
[ 2 ] << 16 ) + ( arg
[ 3 ] << 24 );
368 // Process properties as AVOptions
369 apply_properties( c
, properties
, AV_OPT_FLAG_AUDIO_PARAM
| AV_OPT_FLAG_ENCODING_PARAM
);
371 int audio_qscale
= mlt_properties_get_int( properties
, "aq" );
372 if ( audio_qscale
> QSCALE_NONE
)
374 c
->flags
|= CODEC_FLAG_QSCALE
;
375 c
->global_quality
= st
->quality
= FF_QP2LAMBDA
* audio_qscale
;
378 // Set parameters controlled by MLT
379 c
->sample_rate
= mlt_properties_get_int( properties
, "frequency" );
380 c
->channels
= mlt_properties_get_int( properties
, "channels" );
382 if ( mlt_properties_get( properties
, "alang" ) != NULL
)
383 strncpy( st
->language
, mlt_properties_get( properties
, "alang" ), sizeof( st
->language
) );
387 fprintf( stderr
, "%s: Could not allocate a stream for audio\n", __FILE__
);
393 static int open_audio( AVFormatContext
*oc
, AVStream
*st
, int audio_outbuf_size
)
395 // We will return the audio input size from here
396 int audio_input_frame_size
= 0;
399 AVCodecContext
*c
= st
->codec
;
402 AVCodec
*codec
= avcodec_find_encoder( c
->codec_id
);
404 // Continue if codec found and we can open it
405 if ( codec
!= NULL
&& avcodec_open( c
, codec
) >= 0 )
407 // ugly hack for PCM codecs (will be removed ASAP with new PCM
408 // support to compute the input frame size in samples
409 if ( c
->frame_size
<= 1 )
411 audio_input_frame_size
= audio_outbuf_size
/ c
->channels
;
412 switch(st
->codec
->codec_id
)
414 case CODEC_ID_PCM_S16LE
:
415 case CODEC_ID_PCM_S16BE
:
416 case CODEC_ID_PCM_U16LE
:
417 case CODEC_ID_PCM_U16BE
:
418 audio_input_frame_size
>>= 1;
426 audio_input_frame_size
= c
->frame_size
;
429 // Some formats want stream headers to be seperate (hmm)
430 if( !strcmp( oc
->oformat
->name
, "mp4" ) ||
431 !strcmp( oc
->oformat
->name
, "mov" ) ||
432 !strcmp( oc
->oformat
->name
, "3gp" ) )
433 c
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
437 fprintf( stderr
, "%s: Unable to encode audio - disabling audio output.\n", __FILE__
);
440 return audio_input_frame_size
;
443 static void close_audio( AVFormatContext
*oc
, AVStream
*st
)
445 avcodec_close( st
->codec
);
448 /** Add a video output stream
451 static AVStream
*add_video_stream( mlt_consumer
this, AVFormatContext
*oc
, int codec_id
)
453 // Get the properties
454 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
456 // Create a new stream
457 AVStream
*st
= av_new_stream( oc
, 0 );
461 char *pix_fmt
= mlt_properties_get( properties
, "pix_fmt" );
462 AVCodecContext
*c
= st
->codec
;
464 // Establish defaults from AVOptions
465 avcodec_get_context_defaults2( c
, CODEC_TYPE_VIDEO
);
467 c
->codec_id
= codec_id
;
468 c
->codec_type
= CODEC_TYPE_VIDEO
;
470 // Setup multi-threading
471 int thread_count
= mlt_properties_get_int( properties
, "threads" );
472 if ( thread_count
== 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
473 thread_count
= atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
474 if ( thread_count
> 1 )
475 avcodec_thread_init( c
, thread_count
);
477 // Process properties as AVOptions
478 apply_properties( c
, properties
, AV_OPT_FLAG_VIDEO_PARAM
| AV_OPT_FLAG_ENCODING_PARAM
);
480 // Set options controlled by MLT
481 c
->width
= mlt_properties_get_int( properties
, "width" );
482 c
->height
= mlt_properties_get_int( properties
, "height" );
483 c
->time_base
.num
= mlt_properties_get_int( properties
, "frame_rate_den" );
484 c
->time_base
.den
= mlt_properties_get_int( properties
, "frame_rate_num" );
485 st
->time_base
= c
->time_base
;
486 c
->pix_fmt
= pix_fmt ?
avcodec_get_pix_fmt( pix_fmt
) : PIX_FMT_YUV420P
;
488 if ( codec_id
== CODEC_ID_DVVIDEO
)
490 // Compensate for FFmpeg's notion of DV aspect ratios, which are
491 // based upon a width of 704. Since we do not have a normaliser
492 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
493 // we just coerce the values to facilitate a passive behaviour through
494 // the rescale normaliser when using equivalent producers and consumers.
495 // = display_aspect / (width * height)
496 double ar
= mlt_properties_get_double( properties
, "aspect_ratio" );
497 if ( ar
== 8.0/9.0 ) // 4:3 NTSC
499 c
->sample_aspect_ratio
.num
= 10;
500 c
->sample_aspect_ratio
.den
= 11;
502 else if ( ar
== 16.0/15.0 ) // 4:3 PAL
504 c
->sample_aspect_ratio
.num
= 159;
505 c
->sample_aspect_ratio
.den
= 54;
507 else if ( ar
== 32.0/27.0 ) // 16:9 NTSC
509 c
->sample_aspect_ratio
.num
= 40;
510 c
->sample_aspect_ratio
.den
= 33;
514 c
->sample_aspect_ratio
.num
= 118;
515 c
->sample_aspect_ratio
.den
= 81;
518 else if ( mlt_properties_get( properties
, "aspect" ) )
520 // "-aspect" on ffmpeg command line is display aspect ratio
521 double ar
= mlt_properties_get_double( properties
, "aspect" );
522 AVRational rational
= av_d2q( ar
, 255 );
524 // Update the profile and properties as well since this is an alias
525 // for mlt properties that correspond to profile settings
526 mlt_properties_set_int( properties
, "display_aspect_num", rational
.num
);
527 mlt_properties_set_int( properties
, "display_aspect_den", rational
.den
);
528 mlt_profile profile
= mlt_service_profile( MLT_CONSUMER_SERVICE( this ) );
531 profile
->display_aspect_num
= rational
.num
;
532 profile
->display_aspect_den
= rational
.den
;
533 mlt_properties_set_double( properties
, "display_ratio", mlt_profile_dar( profile
) );
536 // Now compute the sample aspect ratio
537 rational
= av_d2q( ar
* c
->height
/ c
->width
, 255 );
538 c
->sample_aspect_ratio
= rational
;
539 // Update the profile and properties as well since this is an alias
540 // for mlt properties that correspond to profile settings
541 mlt_properties_set_int( properties
, "sample_aspect_num", rational
.num
);
542 mlt_properties_set_int( properties
, "sample_aspect_den", rational
.den
);
545 profile
->sample_aspect_num
= rational
.num
;
546 profile
->sample_aspect_den
= rational
.den
;
547 mlt_properties_set_double( properties
, "aspect_ratio", mlt_profile_sar( profile
) );
553 c
->sample_aspect_ratio
.num
= mlt_properties_get_int( properties
, "sample_aspect_num" );
554 c
->sample_aspect_ratio
.den
= mlt_properties_get_int( properties
, "sample_aspect_den" );
556 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
557 st
->sample_aspect_ratio
= c
->sample_aspect_ratio
;
560 if ( mlt_properties_get_double( properties
, "qscale" ) > 0 )
562 c
->flags
|= CODEC_FLAG_QSCALE
;
563 st
->quality
= FF_QP2LAMBDA
* mlt_properties_get_double( properties
, "qscale" );
566 // Allow the user to override the video fourcc
567 if ( mlt_properties_get( properties
, "vtag" ) )
570 const char *arg
= mlt_properties_get( properties
, "vtag" );
571 int tag
= strtol( arg
, &tail
, 0);
573 tag
= arg
[ 0 ] + ( arg
[ 1 ] << 8 ) + ( arg
[ 2 ] << 16 ) + ( arg
[ 3 ] << 24 );
577 // Some formats want stream headers to be seperate
578 if ( oc
->oformat
->flags
& AVFMT_GLOBALHEADER
)
579 c
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
581 // Translate these standard mlt consumer properties to ffmpeg
582 if ( mlt_properties_get_int( properties
, "progressive" ) == 0 &&
583 mlt_properties_get_int( properties
, "deinterlace" ) == 0 )
585 if ( mlt_properties_get_int( properties
, "ildct" ) )
586 c
->flags
|= CODEC_FLAG_INTERLACED_DCT
;
587 if ( mlt_properties_get_int( properties
, "ilme" ) )
588 c
->flags
|= CODEC_FLAG_INTERLACED_ME
;
591 // parse the ratecontrol override string
593 char *rc_override
= mlt_properties_get( properties
, "rc_override" );
594 for ( i
= 0; rc_override
; i
++ )
597 int e
= sscanf( rc_override
, "%d,%d,%d", &start
, &end
, &q
);
599 fprintf( stderr
, "%s: Error parsing rc_override\n", __FILE__
);
600 c
->rc_override
= av_realloc( c
->rc_override
, sizeof( RcOverride
) * ( i
+ 1 ) );
601 c
->rc_override
[i
].start_frame
= start
;
602 c
->rc_override
[i
].end_frame
= end
;
605 c
->rc_override
[i
].qscale
= q
;
606 c
->rc_override
[i
].quality_factor
= 1.0;
610 c
->rc_override
[i
].qscale
= 0;
611 c
->rc_override
[i
].quality_factor
= -q
/ 100.0;
613 rc_override
= strchr( rc_override
, '/' );
617 c
->rc_override_count
= i
;
618 if ( !c
->rc_initial_buffer_occupancy
)
619 c
->rc_initial_buffer_occupancy
= c
->rc_buffer_size
* 3/4;
620 c
->intra_dc_precision
= mlt_properties_get_int( properties
, "dc" ) - 8;
623 i
= mlt_properties_get_int( properties
, "pass" );
625 c
->flags
|= CODEC_FLAG_PASS1
;
627 c
->flags
|= CODEC_FLAG_PASS2
;
628 if ( c
->flags
& ( CODEC_FLAG_PASS1
| CODEC_FLAG_PASS2
) )
630 char logfilename
[1024];
635 snprintf( logfilename
, sizeof(logfilename
), "%s_2pass.log",
636 mlt_properties_get( properties
, "passlogfile" ) ?
mlt_properties_get( properties
, "passlogfile" ) : mlt_properties_get( properties
, "target" ) );
637 if ( c
->flags
& CODEC_FLAG_PASS1
)
639 f
= fopen( logfilename
, "w" );
641 perror( logfilename
);
643 mlt_properties_set_data( properties
, "_logfile", f
, 0, ( mlt_destructor
)fclose
, NULL
);
647 /* read the log file */
648 f
= fopen( logfilename
, "r" );
655 fseek( f
, 0, SEEK_END
);
657 fseek( f
, 0, SEEK_SET
);
658 logbuffer
= av_malloc( size
+ 1 );
660 fprintf( stderr
, "%s: Could not allocate log buffer\n", __FILE__
);
663 size
= fread( logbuffer
, 1, size
, f
);
665 logbuffer
[size
] = '\0';
666 c
->stats_in
= logbuffer
;
667 mlt_properties_set_data( properties
, "_logbuffer", logbuffer
, 0, ( mlt_destructor
)av_free
, NULL
);
675 fprintf( stderr
, "%s: Could not allocate a stream for video\n", __FILE__
);
681 static AVFrame
*alloc_picture( int pix_fmt
, int width
, int height
)
684 AVFrame
*picture
= avcodec_alloc_frame();
686 // Determine size of the
687 int size
= avpicture_get_size(pix_fmt
, width
, height
);
689 // Allocate the picture buf
690 uint8_t *picture_buf
= av_malloc(size
);
692 // If we have both, then fill the image
693 if ( picture
!= NULL
&& picture_buf
!= NULL
)
695 // Fill the frame with the allocated buffer
696 avpicture_fill( (AVPicture
*)picture
, picture_buf
, pix_fmt
, width
, height
);
700 // Something failed - clean up what we can
702 av_free( picture_buf
);
709 static int open_video(AVFormatContext
*oc
, AVStream
*st
)
712 AVCodecContext
*video_enc
= st
->codec
;
714 // find the video encoder
715 AVCodec
*codec
= avcodec_find_encoder( video_enc
->codec_id
);
717 if( codec
&& codec
->pix_fmts
)
719 const enum PixelFormat
*p
= codec
->pix_fmts
;
722 if( *p
== video_enc
->pix_fmt
)
726 video_enc
->pix_fmt
= codec
->pix_fmts
[ 0 ];
729 // Open the codec safely
730 return codec
!= NULL
&& avcodec_open( video_enc
, codec
) >= 0;
733 void close_video(AVFormatContext
*oc
, AVStream
*st
)
735 avcodec_close(st
->codec
);
738 static inline long time_difference( struct timeval
*time1
)
740 struct timeval time2
;
741 gettimeofday( &time2
, NULL
);
742 return time2
.tv_sec
* 1000000 + time2
.tv_usec
- time1
->tv_sec
* 1000000 - time1
->tv_usec
;
745 /** The main thread - the argument is simply the consumer.
748 static void *consumer_thread( void *arg
)
750 // Map the argument to the object
751 mlt_consumer
this = arg
;
753 // Get the properties
754 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
756 // Get the terminate on pause property
757 int terminate_on_pause
= mlt_properties_get_int( properties
, "terminate_on_pause" );
760 // Determine if feed is slow (for realtime stuff)
761 int real_time_output
= mlt_properties_get_int( properties
, "real_time" );
766 // Get the frame rate
767 double fps
= mlt_properties_get_double( properties
, "fps" );
769 // Get width and height
770 int width
= mlt_properties_get_int( properties
, "width" );
771 int height
= mlt_properties_get_int( properties
, "height" );
772 int img_width
= width
;
773 int img_height
= height
;
775 // Get default audio properties
776 mlt_audio_format aud_fmt
= mlt_audio_pcm
;
777 int channels
= mlt_properties_get_int( properties
, "channels" );
778 int frequency
= mlt_properties_get_int( properties
, "frequency" );
782 // AVFormat audio buffer and frame size
783 int audio_outbuf_size
= 10000;
784 uint8_t *audio_outbuf
= av_malloc( audio_outbuf_size
);
785 int audio_input_frame_size
= 0;
787 // AVFormat video buffer and frame count
789 int video_outbuf_size
= ( 1024 * 1024 );
790 uint8_t *video_outbuf
= av_malloc( video_outbuf_size
);
792 // Used for the frame properties
793 mlt_frame frame
= NULL
;
794 mlt_properties frame_properties
= NULL
;
797 mlt_deque queue
= mlt_properties_get_data( properties
, "frame_queue", NULL
);
798 sample_fifo fifo
= mlt_properties_get_data( properties
, "sample_fifo", NULL
);
800 // Need two av pictures for converting
801 AVFrame
*output
= NULL
;
802 AVFrame
*input
= alloc_picture( PIX_FMT_YUV422
, width
, height
);
804 // For receiving images from an mlt_frame
806 mlt_image_format img_fmt
= mlt_image_yuv422
;
808 // For receiving audio samples back from the fifo
809 int16_t *buffer
= av_malloc( 48000 * 2 );
812 // Allocate the context
813 AVFormatContext
*oc
= av_alloc_format_context( );
816 AVStream
*audio_st
= NULL
;
817 AVStream
*video_st
= NULL
;
820 double audio_pts
= 0;
821 double video_pts
= 0;
828 long int total_time
= 0;
830 // Determine the format
831 AVOutputFormat
*fmt
= NULL
;
832 char *filename
= mlt_properties_get( properties
, "target" );
833 char *format
= mlt_properties_get( properties
, "f" );
834 char *vcodec
= mlt_properties_get( properties
, "vcodec" );
835 char *acodec
= mlt_properties_get( properties
, "acodec" );
837 // Used to store and override codec ids
841 // Check for user selected format first
842 if ( format
!= NULL
)
843 fmt
= guess_format( format
, NULL
, NULL
);
845 // Otherwise check on the filename
846 if ( fmt
== NULL
&& filename
!= NULL
)
847 fmt
= guess_format( NULL
, filename
, NULL
);
849 // Otherwise default to mpeg
851 fmt
= guess_format( "mpeg", NULL
, NULL
);
853 // We need a filename - default to stdout?
854 if ( filename
== NULL
|| !strcmp( filename
, "" ) )
857 // Get the codec ids selected
858 audio_codec_id
= fmt
->audio_codec
;
859 video_codec_id
= fmt
->video_codec
;
861 // Check for audio codec overides
862 if ( acodec
!= NULL
)
864 AVCodec
*p
= avcodec_find_encoder_by_name( acodec
);
866 audio_codec_id
= p
->id
;
868 fprintf( stderr
, "%s: audio codec %s unrecognised - ignoring\n", __FILE__
, acodec
);
871 // Check for video codec overides
872 if ( vcodec
!= NULL
)
874 AVCodec
*p
= avcodec_find_encoder_by_name( vcodec
);
876 video_codec_id
= p
->id
;
878 fprintf( stderr
, "%s: video codec %s unrecognised - ignoring\n", __FILE__
, vcodec
);
885 tmp
= mlt_properties_get( properties
, "meta.attr.title.markup");
886 if (tmp
!= NULL
) snprintf( oc
->title
, sizeof(oc
->title
), "%s", tmp
);
888 tmp
= mlt_properties_get( properties
, "meta.attr.comment.markup");
889 if (tmp
!= NULL
) snprintf( oc
->comment
, sizeof(oc
->comment
), "%s", tmp
);
891 tmp
= mlt_properties_get( properties
, "meta.attr.author.markup");
892 if (tmp
!= NULL
) snprintf( oc
->author
, sizeof(oc
->author
), "%s", tmp
);
894 tmp
= mlt_properties_get( properties
, "meta.attr.copyright.markup");
895 if (tmp
!= NULL
) snprintf( oc
->copyright
, sizeof(oc
->copyright
), "%s", tmp
);
897 tmp
= mlt_properties_get( properties
, "meta.attr.album.markup");
898 if (tmp
!= NULL
) snprintf( oc
->album
, sizeof(oc
->album
), "%s", tmp
);
900 metavalue
= mlt_properties_get_int( properties
, "meta.attr.year.markup");
901 if (metavalue
!= 0) oc
->year
= metavalue
;
903 metavalue
= mlt_properties_get_int( properties
, "meta.attr.track.markup");
904 if (metavalue
!= 0) oc
->track
= metavalue
;
907 snprintf( oc
->filename
, sizeof(oc
->filename
), "%s", filename
);
909 // Add audio and video streams
910 if ( fmt
->video_codec
!= CODEC_ID_NONE
)
911 video_st
= add_video_stream( this, oc
, video_codec_id
);
912 if ( fmt
->audio_codec
!= CODEC_ID_NONE
)
913 audio_st
= add_audio_stream( this, oc
, audio_codec_id
);
915 // Set the parameters (even though we have none...)
916 if ( av_set_parameters(oc
, NULL
) >= 0 )
918 oc
->preload
= ( int )( mlt_properties_get_double( properties
, "muxpreload" ) * AV_TIME_BASE
);
919 oc
->max_delay
= ( int )( mlt_properties_get_double( properties
, "muxdelay" ) * AV_TIME_BASE
);
921 // Process properties as AVOptions
922 apply_properties( oc
, properties
, AV_OPT_FLAG_ENCODING_PARAM
);
924 if ( video_st
&& !open_video( oc
, video_st
) )
927 audio_input_frame_size
= open_audio( oc
, audio_st
, audio_outbuf_size
);
929 // Open the output file, if needed
930 if ( !( fmt
->flags
& AVFMT_NOFILE
) )
932 if ( url_fopen( &oc
->pb
, filename
, URL_WRONLY
) < 0 )
934 fprintf( stderr
, "%s: Could not open '%s'\n", __FILE__
, filename
);
935 mlt_properties_set_int( properties
, "running", 0 );
939 // Write the stream header, if any
940 if ( mlt_properties_get_int( properties
, "running" ) )
941 av_write_header( oc
);
945 fprintf( stderr
, "%s: Invalid output format parameters\n", __FILE__
);
946 mlt_properties_set_int( properties
, "running", 0 );
951 output
= alloc_picture( video_st
->codec
->pix_fmt
, width
, height
);
953 // Last check - need at least one stream
954 if ( audio_st
== NULL
&& video_st
== NULL
)
955 mlt_properties_set_int( properties
, "running", 0 );
957 // Get the starting time (can ignore the times above)
958 gettimeofday( &ante
, NULL
);
960 // Loop while running
961 while( mlt_properties_get_int( properties
, "running" ) && !terminated
)
964 frame
= mlt_consumer_rt_frame( this );
966 // Check that we have a frame to work with
969 // Increment frames despatched
972 // Default audio args
973 frame_properties
= MLT_FRAME_PROPERTIES( frame
);
975 // Check for the terminated condition
976 terminated
= terminate_on_pause
&& mlt_properties_get_double( frame_properties
, "_speed" ) == 0.0;
978 // Get audio and append to the fifo
979 if ( !terminated
&& audio_st
)
981 samples
= mlt_sample_calculator( fps
, frequency
, count
++ );
982 mlt_frame_get_audio( frame
, &pcm
, &aud_fmt
, &frequency
, &channels
, &samples
);
984 // Create the fifo if we don't have one
987 fifo
= sample_fifo_init( frequency
, channels
);
988 mlt_properties_set_data( properties
, "sample_fifo", fifo
, 0, ( mlt_destructor
)sample_fifo_close
, NULL
);
991 if ( mlt_properties_get_double( frame_properties
, "_speed" ) != 1.0 )
992 memset( pcm
, 0, samples
* channels
* 2 );
994 // Append the samples
995 sample_fifo_append( fifo
, pcm
, samples
* channels
);
996 total_time
+= ( samples
* 1000000 ) / frequency
;
1000 if ( !terminated
&& video_st
)
1001 mlt_deque_push_back( queue
, frame
);
1003 mlt_frame_close( frame
);
1006 // While we have stuff to process, process...
1010 audio_pts
= (double)audio_st
->pts
.val
* audio_st
->time_base
.num
/ audio_st
->time_base
.den
;
1015 video_pts
= (double)video_st
->pts
.val
* video_st
->time_base
.num
/ video_st
->time_base
.den
;
1019 // Write interleaved audio and video frames
1020 if ( !video_st
|| ( video_st
&& audio_st
&& audio_pts
< video_pts
) )
1022 if ( channels
* audio_input_frame_size
< sample_fifo_used( fifo
) )
1026 av_init_packet( &pkt
);
1028 c
= audio_st
->codec
;
1030 sample_fifo_fetch( fifo
, buffer
, channels
* audio_input_frame_size
);
1032 pkt
.size
= avcodec_encode_audio( c
, audio_outbuf
, audio_outbuf_size
, buffer
);
1033 // Write the compressed frame in the media file
1034 if ( c
->coded_frame
&& c
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
1035 pkt
.pts
= av_rescale_q( c
->coded_frame
->pts
, c
->time_base
, audio_st
->time_base
);
1036 pkt
.flags
|= PKT_FLAG_KEY
;
1037 pkt
.stream_index
= audio_st
->index
;
1038 pkt
.data
= audio_outbuf
;
1041 if ( av_interleaved_write_frame( oc
, &pkt
) != 0)
1042 fprintf( stderr
, "%s: Error while writing audio frame\n", __FILE__
);
1044 audio_pts
+= c
->frame_size
;
1051 else if ( video_st
)
1053 if ( mlt_deque_count( queue
) )
1058 frame
= mlt_deque_pop_front( queue
);
1059 frame_properties
= MLT_FRAME_PROPERTIES( frame
);
1061 c
= video_st
->codec
;
1063 if ( mlt_properties_get_int( frame_properties
, "rendered" ) )
1070 mlt_events_fire( properties
, "consumer-frame-show", frame
, NULL
);
1072 mlt_frame_get_image( frame
, &image
, &img_fmt
, &img_width
, &img_height
, 0 );
1076 // Convert the mlt frame to an AVPicture
1077 for ( i
= 0; i
< height
; i
++ )
1079 p
= input
->data
[ 0 ] + i
* input
->linesize
[ 0 ];
1088 // Do the colour space conversion
1090 struct SwsContext
*context
= sws_getContext( width
, height
, PIX_FMT_YUV422
,
1091 width
, height
, video_st
->codec
->pix_fmt
, SWS_FAST_BILINEAR
, NULL
, NULL
, NULL
);
1092 sws_scale( context
, input
->data
, input
->linesize
, 0, height
,
1093 output
->data
, output
->linesize
);
1094 sws_freeContext( context
);
1096 img_convert( ( AVPicture
* )output
, video_st
->codec
->pix_fmt
, ( AVPicture
* )input
, PIX_FMT_YUV422
, width
, height
);
1099 // Apply the alpha if applicable
1100 if ( video_st
->codec
->pix_fmt
== PIX_FMT_RGBA32
)
1102 uint8_t *alpha
= mlt_frame_get_alpha_mask( frame
);
1105 for ( i
= 0; i
< height
; i
++ )
1107 n
= ( width
+ 7 ) / 8;
1108 p
= output
->data
[ 0 ] + i
* output
->linesize
[ 0 ];
1116 case 0: do { *p
= *alpha
++; p
+= 4;
1117 case 7: *p
= *alpha
++; p
+= 4;
1118 case 6: *p
= *alpha
++; p
+= 4;
1119 case 5: *p
= *alpha
++; p
+= 4;
1120 case 4: *p
= *alpha
++; p
+= 4;
1121 case 3: *p
= *alpha
++; p
+= 4;
1122 case 2: *p
= *alpha
++; p
+= 4;
1123 case 1: *p
= *alpha
++; p
+= 4;
1131 if (oc
->oformat
->flags
& AVFMT_RAWPICTURE
)
1133 // raw video case. The API will change slightly in the near future for that
1135 av_init_packet(&pkt
);
1137 pkt
.flags
|= PKT_FLAG_KEY
;
1138 pkt
.stream_index
= video_st
->index
;
1139 pkt
.data
= (uint8_t *)output
;
1140 pkt
.size
= sizeof(AVPicture
);
1142 ret
= av_write_frame(oc
, &pkt
);
1143 video_pts
+= c
->frame_size
;
1148 output
->quality
= video_st
->quality
;
1150 // Set frame interlace hints
1151 output
->interlaced_frame
= !mlt_properties_get_int( frame_properties
, "progressive" );
1152 output
->top_field_first
= mlt_properties_get_int( frame_properties
, "top_field_first" );
1155 out_size
= avcodec_encode_video(c
, video_outbuf
, video_outbuf_size
, output
);
1157 // If zero size, it means the image was buffered
1161 av_init_packet( &pkt
);
1163 if ( c
->coded_frame
&& c
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
1164 pkt
.pts
= av_rescale_q( c
->coded_frame
->pts
, c
->time_base
, video_st
->time_base
);
1165 if( c
->coded_frame
&& c
->coded_frame
->key_frame
)
1166 pkt
.flags
|= PKT_FLAG_KEY
;
1167 pkt
.stream_index
= video_st
->index
;
1168 pkt
.data
= video_outbuf
;
1171 // write the compressed frame in the media file
1172 ret
= av_interleaved_write_frame(oc
, &pkt
);
1173 video_pts
+= c
->frame_size
;
1175 // Dual pass logging
1176 if ( mlt_properties_get_data( properties
, "_logfile", NULL
) && c
->stats_out
)
1177 fprintf( mlt_properties_get_data( properties
, "_logfile", NULL
), "%s", c
->stats_out
);
1181 fprintf( stderr
, "%s: error with video encode\n", __FILE__
);
1185 mlt_frame_close( frame
);
1194 if ( real_time_output
== 1 && frames
% 12 == 0 )
1196 long passed
= time_difference( &ante
);
1199 long pending
= ( ( ( long )sample_fifo_used( fifo
) * 1000 ) / frequency
) * 1000;
1202 if ( passed
< total_time
)
1204 long total
= ( total_time
- passed
);
1205 struct timespec t
= { total
/ 1000000, ( total
% 1000000 ) * 1000 };
1206 nanosleep( &t
, NULL
);
1212 if ( ! real_time_output
)
1215 if ( audio_st
&& audio_st
->codec
->frame_size
> 1 ) for (;;)
1217 AVCodecContext
*c
= audio_st
->codec
;
1219 av_init_packet( &pkt
);
1222 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1223 ( channels
* audio_input_frame_size
< sample_fifo_used( fifo
) ) )
1225 sample_fifo_fetch( fifo
, buffer
, channels
* audio_input_frame_size
);
1226 pkt
.size
= avcodec_encode_audio( c
, audio_outbuf
, audio_outbuf_size
, buffer
);
1228 if ( pkt
.size
<= 0 )
1229 pkt
.size
= avcodec_encode_audio( c
, audio_outbuf
, audio_outbuf_size
, NULL
);
1230 if ( pkt
.size
<= 0 )
1233 // Write the compressed frame in the media file
1234 if ( c
->coded_frame
&& c
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
1235 pkt
.pts
= av_rescale_q( c
->coded_frame
->pts
, c
->time_base
, audio_st
->time_base
);
1236 pkt
.flags
|= PKT_FLAG_KEY
;
1237 pkt
.stream_index
= audio_st
->index
;
1238 pkt
.data
= audio_outbuf
;
1239 if ( av_interleaved_write_frame( oc
, &pkt
) != 0 )
1241 fprintf( stderr
, "%s: Error while writing flushed audio frame\n", __FILE__
);
1247 if ( video_st
&& !( oc
->oformat
->flags
& AVFMT_RAWPICTURE
) ) for (;;)
1249 AVCodecContext
*c
= video_st
->codec
;
1251 av_init_packet( &pkt
);
1254 pkt
.size
= avcodec_encode_video( c
, video_outbuf
, video_outbuf_size
, NULL
);
1255 if ( pkt
.size
<= 0 )
1258 if ( c
->coded_frame
&& c
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
1259 pkt
.pts
= av_rescale_q( c
->coded_frame
->pts
, c
->time_base
, video_st
->time_base
);
1260 if( c
->coded_frame
&& c
->coded_frame
->key_frame
)
1261 pkt
.flags
|= PKT_FLAG_KEY
;
1262 pkt
.stream_index
= video_st
->index
;
1263 pkt
.data
= video_outbuf
;
1265 // write the compressed frame in the media file
1266 if ( av_interleaved_write_frame( oc
, &pkt
) != 0 )
1268 fprintf( stderr
, "%s: Error while writing flushed video frame\n". __FILE__
);
1277 close_video(oc
, video_st
);
1279 close_audio(oc
, audio_st
);
1281 // Write the trailer, if any
1282 av_write_trailer(oc
);
1285 for(i
= 0; i
< oc
->nb_streams
; i
++)
1286 av_freep(&oc
->streams
[i
]);
1288 // Close the output file
1289 if (!(fmt
->flags
& AVFMT_NOFILE
))
1290 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1293 url_fclose(&oc
->pb
);
1296 // Clean up input and output frames
1298 av_free( output
->data
[0] );
1300 av_free( input
->data
[0] );
1302 av_free( video_outbuf
);
1308 // Just in case we terminated on pause
1309 mlt_properties_set_int( properties
, "running", 0 );
1311 mlt_consumer_stopped( this );
1316 /** Close the consumer.
1319 static void consumer_close( mlt_consumer
this )
1321 // Stop the consumer
1322 mlt_consumer_stop( this );
1325 mlt_consumer_close( this );