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>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 #include "consumer_avformat.h"
25 #include <framework/mlt_frame.h>
27 // System header files
35 // avformat header files
44 *sample_fifo
, sample_fifo_s
;
46 sample_fifo
sample_fifo_init( )
48 return calloc( 1, sizeof( sample_fifo_s
) );
51 void sample_fifo_append( sample_fifo
this, int16_t *samples
, int count
)
53 if ( ( this->size
- this->used
) < count
)
55 this->size
+= count
* 5;
56 this->buffer
= realloc( this->buffer
, this->size
* sizeof( int16_t ) );
59 memcpy( &this->buffer
[ this->used
], samples
, count
* sizeof( int16_t ) );
63 int sample_fifo_used( sample_fifo
this )
68 int sample_fifo_fetch( sample_fifo
this, int16_t *samples
, int count
)
70 if ( count
> this->used
)
73 memcpy( samples
, this->buffer
, count
* sizeof( int16_t ) );
75 memmove( this->buffer
, &this->buffer
[ count
], this->used
* sizeof( int16_t ) );
80 void sample_fifo_close( sample_fifo
this )
86 // Forward references.
87 static int consumer_start( mlt_consumer
this );
88 static int consumer_stop( mlt_consumer
this );
89 static int consumer_is_stopped( mlt_consumer
this );
90 static void *consumer_thread( void *arg
);
91 static void consumer_close( mlt_consumer
this );
93 /** Initialise the dv consumer.
96 mlt_consumer
consumer_avformat_init( char *arg
)
98 // Allocate the consumer
99 mlt_consumer
this = mlt_consumer_new( );
101 // If memory allocated and initialises without error
104 // Get properties from the consumer
105 mlt_properties properties
= mlt_consumer_properties( this );
107 // Assign close callback
108 this->close
= consumer_close
;
110 // Interpret the argument
112 mlt_properties_set( properties
, "target", arg
);
114 // sample and frame queue
115 mlt_properties_set_data( properties
, "sample_fifo", sample_fifo_init( ), 0, ( mlt_destructor
)sample_fifo_close
, NULL
);
116 mlt_properties_set_data( properties
, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor
)mlt_deque_close
, NULL
);
118 // Set avformat defaults
119 mlt_properties_set_int( properties
, "audio_bit_rate", 128000 );
120 mlt_properties_set_int( properties
, "video_bit_rate", 200 * 1000 );
121 mlt_properties_set_int( properties
, "video_bit_rate_tolerance", 4000 * 1000 );
122 mlt_properties_set_int( properties
, "frame_rate_base", 1 );
123 mlt_properties_set_int( properties
, "gop_size", 12 );
124 mlt_properties_set_int( properties
, "max_b_frames", 0 );
125 mlt_properties_set_int( properties
, "mb_decision", 0 );
126 mlt_properties_set_double( properties
, "qscale", 0 );
127 mlt_properties_set_int( properties
, "me_method", ME_EPZS
);
129 // Ensure termination at end of the stream
130 mlt_properties_set_int( properties
, "terminate_on_pause", 1 );
132 // Set up start/stop/terminated callbacks
133 this->start
= consumer_start
;
134 this->stop
= consumer_stop
;
135 this->is_stopped
= consumer_is_stopped
;
142 /** Start the consumer.
145 static int consumer_start( mlt_consumer
this )
147 // Get the properties
148 mlt_properties properties
= mlt_consumer_properties( this );
150 // Check that we're not already running
151 if ( !mlt_properties_get_int( properties
, "running" ) )
154 pthread_t
*thread
= calloc( 1, sizeof( pthread_t
) );
155 pthread_attr_t thread_attributes
;
157 // Get the width and height
158 int width
= mlt_properties_get_int( properties
, "width" );
159 int height
= mlt_properties_get_int( properties
, "height" );
161 // Obtain the size property
162 char *size
= mlt_properties_get( properties
, "size" );
168 if ( sscanf( size
, "%dx%d", &tw
, &th
) == 2 && tw
> 0 && th
> 0 )
175 fprintf( stderr
, "consumer_avformat: Invalid size property %s - ignoring.\n", size
);
179 // Now ensure we honour the multiple of two requested by libavformat
180 mlt_properties_set_int( properties
, "width", ( width
/ 2 ) * 2 );
181 mlt_properties_set_int( properties
, "height", ( height
/ 2 ) * 2 );
183 // Assign the thread to properties
184 mlt_properties_set_data( properties
, "thread", thread
, sizeof( pthread_t
), free
, NULL
);
186 // Set the running state
187 mlt_properties_set_int( properties
, "running", 1 );
189 // Inherit the scheduling priority
190 pthread_attr_init( &thread_attributes
);
191 pthread_attr_setinheritsched( &thread_attributes
, PTHREAD_INHERIT_SCHED
);
194 pthread_create( thread
, &thread_attributes
, consumer_thread
, this );
199 /** Stop the consumer.
202 static int consumer_stop( mlt_consumer
this )
204 // Get the properties
205 mlt_properties properties
= mlt_consumer_properties( this );
207 // Check that we're running
208 if ( mlt_properties_get_int( properties
, "running" ) )
211 pthread_t
*thread
= mlt_properties_get_data( properties
, "thread", NULL
);
214 mlt_properties_set_int( properties
, "running", 0 );
216 // Wait for termination
217 pthread_join( *thread
, NULL
);
223 /** Determine if the consumer is stopped.
226 static int consumer_is_stopped( mlt_consumer
this )
228 // Get the properties
229 mlt_properties properties
= mlt_consumer_properties( this );
230 return !mlt_properties_get_int( properties
, "running" );
233 /** Add an audio output stream
236 static AVStream
*add_audio_stream( mlt_consumer
this, AVFormatContext
*oc
, int codec_id
)
238 // Get the properties
239 mlt_properties properties
= mlt_consumer_properties( this );
241 // Create a new stream
242 AVStream
*st
= av_new_stream( oc
, 1 );
244 // If created, then initialise from properties
247 AVCodecContext
*c
= &st
->codec
;
248 c
->codec_id
= codec_id
;
249 c
->codec_type
= CODEC_TYPE_AUDIO
;
251 // Put sample parameters
252 c
->bit_rate
= mlt_properties_get_int( properties
, "audio_bit_rate" );
253 c
->sample_rate
= mlt_properties_get_int( properties
, "frequency" );
254 c
->channels
= mlt_properties_get_int( properties
, "channels" );
258 fprintf( stderr
, "Could not allocate a stream for audio\n" );
264 static int open_audio( AVFormatContext
*oc
, AVStream
*st
, int audio_outbuf_size
)
266 // We will return the audio input size from here
267 int audio_input_frame_size
= 0;
270 AVCodecContext
*c
= &st
->codec
;
273 AVCodec
*codec
= avcodec_find_encoder( c
->codec_id
);
275 // Continue if codec found and we can open it
276 if ( codec
!= NULL
&& avcodec_open(c
, codec
) >= 0 )
278 // ugly hack for PCM codecs (will be removed ASAP with new PCM
279 // support to compute the input frame size in samples
280 if ( c
->frame_size
<= 1 )
282 audio_input_frame_size
= audio_outbuf_size
/ c
->channels
;
283 switch(st
->codec
.codec_id
)
285 case CODEC_ID_PCM_S16LE
:
286 case CODEC_ID_PCM_S16BE
:
287 case CODEC_ID_PCM_U16LE
:
288 case CODEC_ID_PCM_U16BE
:
289 audio_input_frame_size
>>= 1;
297 audio_input_frame_size
= c
->frame_size
;
300 // Some formats want stream headers to be seperate (hmm)
301 if( !strcmp( oc
->oformat
->name
, "mp4" ) ||
302 !strcmp( oc
->oformat
->name
, "mov" ) ||
303 !strcmp( oc
->oformat
->name
, "3gp" ) )
304 c
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
308 fprintf( stderr
, "Unable to encode audio - disabling audio output.\n" );
311 return audio_input_frame_size
;
314 static void close_audio( AVFormatContext
*oc
, AVStream
*st
)
316 avcodec_close( &st
->codec
);
319 /** Add a video output stream
322 static AVStream
*add_video_stream( mlt_consumer
this, AVFormatContext
*oc
, int codec_id
)
324 // Get the properties
325 mlt_properties properties
= mlt_consumer_properties( this );
327 // Create a new stream
328 AVStream
*st
= av_new_stream( oc
, 0 );
332 AVCodecContext
*c
= &st
->codec
;
333 c
->codec_id
= codec_id
;
334 c
->codec_type
= CODEC_TYPE_VIDEO
;
336 // put sample parameters
337 c
->bit_rate
= mlt_properties_get_int( properties
, "video_bit_rate" );
338 c
->bit_rate_tolerance
= mlt_properties_get_int( properties
, "video_bit_rate_tolerance" );
339 c
->width
= mlt_properties_get_int( properties
, "width" );
340 c
->height
= mlt_properties_get_int( properties
, "height" );
341 c
->frame_rate
= mlt_properties_get_double( properties
, "fps" );
342 c
->frame_rate_base
= mlt_properties_get_double( properties
, "frame_rate_base" );
343 c
->frame_rate_base
= 1;
344 c
->gop_size
= mlt_properties_get_int( properties
, "gop_size" );
345 c
->max_b_frames
= mlt_properties_get_int( properties
, "max_b_frames" );
346 if ( c
->max_b_frames
)
348 c
->b_frame_strategy
= 0;
349 c
->b_quant_factor
= 2.0;
352 c
->mb_decision
= mlt_properties_get_int( properties
, "mb_decision" );
353 c
->sample_aspect_ratio
= av_d2q( mlt_properties_get_double( properties
, "aspect_ratio" ), 255 );
356 if ( mlt_properties_get_double( properties
, "qscale" ) > 0 )
358 c
->flags
|= CODEC_FLAG_QSCALE
;
359 st
->quality
= FF_QP2LAMBDA
* mlt_properties_get_double( properties
, "qscale" );
362 // Some formats want stream headers to be seperate (hmm)
363 if( !strcmp( oc
->oformat
->name
, "mp4" ) ||
364 !strcmp( oc
->oformat
->name
, "mov" ) ||
365 !strcmp( oc
->oformat
->name
, "3gp" ) )
366 c
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
368 c
->me_method
= mlt_properties_get_int( properties
, "me_method" );
372 fprintf( stderr
, "Could not allocate a stream for video\n" );
378 static AVFrame
*alloc_picture( int pix_fmt
, int width
, int height
)
381 AVFrame
*picture
= avcodec_alloc_frame();
383 // Determine size of the
384 int size
= avpicture_get_size(pix_fmt
, width
, height
);
386 // Allocate the picture buf
387 uint8_t *picture_buf
= av_malloc(size
);
389 // If we have both, then fill the image
390 if ( picture
!= NULL
&& picture_buf
!= NULL
)
392 // Fill the frame with the allocated buffer
393 avpicture_fill( (AVPicture
*)picture
, picture_buf
, pix_fmt
, width
, height
);
397 // Something failed - clean up what we can
399 av_free( picture_buf
);
406 static int open_video(AVFormatContext
*oc
, AVStream
*st
)
409 AVCodecContext
*c
= &st
->codec
;
411 // find the video encoder
412 AVCodec
*codec
= avcodec_find_encoder(c
->codec_id
);
414 // Open the codec safely
415 return codec
!= NULL
&& avcodec_open(c
, codec
) >= 0;
418 void close_video(AVFormatContext
*oc
, AVStream
*st
)
420 avcodec_close(&st
->codec
);
423 static inline long time_difference( struct timeval
*time1
)
425 struct timeval time2
;
426 gettimeofday( &time2
, NULL
);
427 return time2
.tv_sec
* 1000000 + time2
.tv_usec
- time1
->tv_sec
* 1000000 - time1
->tv_usec
;
430 /** The main thread - the argument is simply the consumer.
433 static void *consumer_thread( void *arg
)
435 // Map the argument to the object
436 mlt_consumer
this = arg
;
438 // Get the properties
439 mlt_properties properties
= mlt_consumer_properties( this );
441 // Get the terminate on pause property
442 int terminate_on_pause
= mlt_properties_get_int( properties
, "terminate_on_pause" );
444 // Determine if feed is slow (for realtime stuff)
445 int real_time_output
= mlt_properties_get_int( properties
, "real_time" );
450 // Get the frame rate
451 int fps
= mlt_properties_get_double( properties
, "fps" );
453 // Get width and height
454 int width
= mlt_properties_get_int( properties
, "width" );
455 int height
= mlt_properties_get_int( properties
, "height" );
456 int img_width
= width
;
457 int img_height
= height
;
459 // Get default audio properties
460 mlt_audio_format aud_fmt
= mlt_audio_pcm
;
461 int channels
= mlt_properties_get_int( properties
, "channels" );
462 int frequency
= mlt_properties_get_int( properties
, "frequency" );
466 // AVFormat audio buffer and frame size
467 int audio_outbuf_size
= 2 * 128 * 1024;
468 uint8_t *audio_outbuf
= av_malloc( audio_outbuf_size
);
469 int audio_input_frame_size
= 0;
471 // AVFormat video buffer and frame count
473 int video_outbuf_size
= ( 1024 * 1024 );
474 uint8_t *video_outbuf
= av_malloc( video_outbuf_size
);
476 // Used for the frame properties
477 mlt_frame frame
= NULL
;
478 mlt_properties frame_properties
= NULL
;
481 mlt_deque queue
= mlt_properties_get_data( properties
, "frame_queue", NULL
);
482 sample_fifo fifo
= mlt_properties_get_data( properties
, "sample_fifo", NULL
);
484 // Need two av pictures for converting
485 AVFrame
*output
= alloc_picture( PIX_FMT_YUV420P
, width
, height
);
486 AVFrame
*input
= alloc_picture( PIX_FMT_YUV422
, width
, height
);
488 // For receiving images from an mlt_frame
490 mlt_image_format img_fmt
= mlt_image_yuv422
;
492 // For receiving audio samples back from the fifo
493 int16_t *buffer
= av_malloc( 48000 * 2 );
496 // Allocate the context
497 AVFormatContext
*oc
= av_alloc_format_context( );
500 AVStream
*audio_st
= NULL
;
501 AVStream
*video_st
= NULL
;
504 double audio_pts
, video_pts
;
511 long int total_time
= 0;
513 // Determine the format
514 AVOutputFormat
*fmt
= NULL
;
515 char *filename
= mlt_properties_get( properties
, "target" );
516 char *format
= mlt_properties_get( properties
, "format" );
517 char *vcodec
= mlt_properties_get( properties
, "vcodec" );
518 char *acodec
= mlt_properties_get( properties
, "acodec" );
520 // Used to store and override codec ids
524 // Check for user selected format first
525 if ( format
!= NULL
)
526 fmt
= guess_format( format
, NULL
, NULL
);
528 // Otherwise check on the filename
529 if ( fmt
== NULL
&& filename
!= NULL
)
530 fmt
= guess_format( NULL
, filename
, NULL
);
532 // Otherwise default to mpeg
534 fmt
= guess_format( "mpeg", NULL
, NULL
);
536 // We need a filename - default to stdout?
537 if ( filename
== NULL
)
540 // Get the codec ids selected
541 audio_codec_id
= fmt
->audio_codec
;
542 video_codec_id
= fmt
->video_codec
;
544 // Check for audio codec overides
545 if ( acodec
!= NULL
)
547 AVCodec
*p
= first_avcodec
;
550 if ( !strcmp( p
->name
, acodec
) && p
->type
== CODEC_TYPE_AUDIO
)
555 audio_codec_id
= p
->id
;
557 fprintf( stderr
, "consumer_avcodec: audio codec %s unrecognised - ignoring\n", acodec
);
560 // Check for video codec overides
561 if ( vcodec
!= NULL
)
563 AVCodec
*p
= first_avcodec
;
566 if ( !strcmp( p
->name
, vcodec
) && p
->type
== CODEC_TYPE_VIDEO
)
571 video_codec_id
= p
->id
;
573 fprintf( stderr
, "consumer_avcodec: video codec %s unrecognised - ignoring\n", vcodec
);
576 // Update the output context
578 snprintf( oc
->filename
, sizeof(oc
->filename
), "%s", filename
);
580 // Add audio and video streams
581 if ( fmt
->video_codec
!= CODEC_ID_NONE
)
582 video_st
= add_video_stream( this, oc
, video_codec_id
);
583 if ( fmt
->audio_codec
!= CODEC_ID_NONE
)
584 audio_st
= add_audio_stream( this, oc
, audio_codec_id
);
586 // Set the parameters (even though we have none...)
587 if ( av_set_parameters(oc
, NULL
) >= 0 )
589 if ( video_st
&& !open_video( oc
, video_st
) )
592 audio_input_frame_size
= open_audio( oc
, audio_st
, audio_outbuf_size
);
594 // Open the output file, if needed
595 if ( !( fmt
->flags
& AVFMT_NOFILE
) )
597 if (url_fopen(&oc
->pb
, filename
, URL_RDWR
) < 0)
599 fprintf(stderr
, "Could not open '%s'\n", filename
);
600 mlt_properties_set_int( properties
, "running", 0 );
604 // Write the stream header, if any
605 if ( mlt_properties_get_int( properties
, "running" ) )
606 av_write_header( oc
);
610 fprintf(stderr
, "Invalid output format parameters\n");
611 mlt_properties_set_int( properties
, "running", 0 );
614 // Last check - need at least one stream
615 if ( audio_st
== NULL
&& video_st
== NULL
)
616 mlt_properties_set_int( properties
, "running", 0 );
618 // Get the starting time (can ignore the times above)
619 gettimeofday( &ante
, NULL
);
621 // Loop while running
622 while( mlt_properties_get_int( properties
, "running" ) )
625 frame
= mlt_consumer_rt_frame( this );
627 // Check that we have a frame to work with
630 // Increment frames despatched
633 // Default audio args
634 frame_properties
= mlt_frame_properties( frame
);
636 // Get audio and append to the fifo
639 samples
= mlt_sample_calculator( fps
, frequency
, count
);
640 mlt_frame_get_audio( frame
, &pcm
, &aud_fmt
, &frequency
, &channels
, &samples
);
641 sample_fifo_append( fifo
, pcm
, samples
* channels
);
642 total_time
+= ( samples
* 1000000 ) / frequency
;
647 mlt_deque_push_back( queue
, frame
);
649 mlt_frame_close( frame
);
651 // While we have stuff to process, process...
654 // Compute current audio and video time
656 audio_pts
= (double)audio_st
->pts
.val
* oc
->pts_num
/ oc
->pts_den
;
661 video_pts
= (double)video_st
->pts
.val
* oc
->pts_num
/ oc
->pts_den
;
665 // Write interleaved audio and video frames
666 if ( !video_st
|| ( video_st
&& audio_st
&& audio_pts
< video_pts
) )
668 if ( channels
* audio_input_frame_size
< sample_fifo_used( fifo
) )
673 c
= &audio_st
->codec
;
675 sample_fifo_fetch( fifo
, buffer
, channels
* audio_input_frame_size
);
677 out_size
= avcodec_encode_audio( c
, audio_outbuf
, audio_outbuf_size
, buffer
);
679 // Write the compressed frame in the media file
680 if (av_write_frame(oc
, audio_st
->index
, audio_outbuf
, out_size
) != 0)
681 fprintf(stderr
, "Error while writing audio frame\n");
690 if ( mlt_deque_count( queue
) )
695 frame
= mlt_deque_pop_front( queue
);
696 frame_properties
= mlt_frame_properties( frame
);
698 if ( terminate_on_pause
&& mlt_properties_get_double( frame_properties
, "_speed" ) == 0.0 )
700 mlt_properties_set_int( properties
, "running", 0 );
704 c
= &video_st
->codec
;
706 if ( mlt_properties_get_int( frame_properties
, "rendered" ) )
713 mlt_frame_get_image( frame
, &image
, &img_fmt
, &img_width
, &img_height
, 0 );
717 for ( i
= 0; i
< height
; i
++ )
719 p
= input
->data
[ 0 ] + i
* input
->linesize
[ 0 ];
728 img_convert( ( AVPicture
* )output
, PIX_FMT_YUV420P
, ( AVPicture
* )input
, PIX_FMT_YUV422
, width
, height
);
731 if (oc
->oformat
->flags
& AVFMT_RAWPICTURE
)
733 // raw video case. The API will change slightly in the near future for that
734 ret
= av_write_frame(oc
, video_st
->index
, (uint8_t *)output
, sizeof(AVPicture
));
739 out_size
= avcodec_encode_video(c
, video_outbuf
, video_outbuf_size
, output
);
741 // If zero size, it means the image was buffered
744 // write the compressed frame in the media file
745 // XXX: in case of B frames, the pts is not yet valid
746 ret
= av_write_frame( oc
, video_st
->index
, video_outbuf
, out_size
);
750 mlt_frame_close( frame
);
760 if ( real_time_output
&& frames
% 25 == 0 )
762 long passed
= time_difference( &ante
);
763 long pending
= ( ( ( long )sample_fifo_used( fifo
) * 1000 ) / frequency
) * 1000;
765 if ( passed
< total_time
)
767 long total
= ( total_time
- passed
);
768 struct timespec t
= { total
/ 1000000, ( total
% 1000000 ) * 1000 };
769 nanosleep( &t
, NULL
);
776 close_video(oc
, video_st
);
778 close_audio(oc
, audio_st
);
780 // Write the trailer, if any
781 av_write_trailer(oc
);
784 for(i
= 0; i
< oc
->nb_streams
; i
++)
785 av_freep(&oc
->streams
[i
]);
787 // Close the output file
788 if (!(fmt
->flags
& AVFMT_NOFILE
))
791 // Clean up input and output frames
792 av_free( output
->data
[0] );
794 av_free( input
->data
[0] );
796 av_free( video_outbuf
);
805 /** Close the consumer.
808 static void consumer_close( mlt_consumer
this )
811 mlt_consumer_stop( this );
814 mlt_consumer_close( this );