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
36 #include <ffmpeg/avformat.h>
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 = calloc( 1, sizeof( struct mlt_consumer_s
) );
101 // If memory allocated and initialises without error
102 if ( this != NULL
&& mlt_consumer_init( this, NULL
) == 0 )
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", 400000 );
121 mlt_properties_set_int( properties
, "gop_size", 12 );
122 mlt_properties_set_int( properties
, "max_b_frames", 0 );
123 mlt_properties_set_int( properties
, "mb_decision", 0 );
125 // Ensure termination at end of the stream
126 mlt_properties_set_int( properties
, "terminate_on_pause", 1 );
128 // Set up start/stop/terminated callbacks
129 this->start
= consumer_start
;
130 this->stop
= consumer_stop
;
131 this->is_stopped
= consumer_is_stopped
;
135 // Clean up in case of init failure
144 /** Start the consumer.
147 static int consumer_start( mlt_consumer
this )
149 // Get the properties
150 mlt_properties properties
= mlt_consumer_properties( this );
152 // Check that we're not already running
153 if ( !mlt_properties_get_int( properties
, "running" ) )
156 pthread_t
*thread
= calloc( 1, sizeof( pthread_t
) );
157 pthread_attr_t thread_attributes
;
159 // Get the width and height
160 int width
= mlt_properties_get_int( properties
, "width" );
161 int height
= mlt_properties_get_int( properties
, "height" );
163 // Obtain the size property
164 char *size
= mlt_properties_get( properties
, "size" );
170 if ( sscanf( size
, "%dx%d", &tw
, &th
) == 2 && tw
> 0 && th
> 0 )
177 fprintf( stderr
, "consumer_avformat: Invalid size property %s - ignoring.\n", size
);
181 // Now ensure we honour the multiple of two requested by libavformat
182 mlt_properties_set_int( properties
, "width", ( width
/ 2 ) * 2 );
183 mlt_properties_set_int( properties
, "height", ( height
/ 2 ) * 2 );
185 // Assign the thread to properties
186 mlt_properties_set_data( properties
, "thread", thread
, sizeof( pthread_t
), free
, NULL
);
188 // Set the running state
189 mlt_properties_set_int( properties
, "running", 1 );
191 // Inherit the scheduling priority
192 pthread_attr_init( &thread_attributes
);
193 pthread_attr_setinheritsched( &thread_attributes
, PTHREAD_INHERIT_SCHED
);
196 pthread_create( thread
, &thread_attributes
, consumer_thread
, this );
201 /** Stop the consumer.
204 static int consumer_stop( mlt_consumer
this )
206 // Get the properties
207 mlt_properties properties
= mlt_consumer_properties( this );
209 // Check that we're running
210 if ( mlt_properties_get_int( properties
, "running" ) )
213 pthread_t
*thread
= mlt_properties_get_data( properties
, "thread", NULL
);
216 mlt_properties_set_int( properties
, "running", 0 );
218 // Wait for termination
219 pthread_join( *thread
, NULL
);
225 /** Determine if the consumer is stopped.
228 static int consumer_is_stopped( mlt_consumer
this )
230 // Get the properties
231 mlt_properties properties
= mlt_consumer_properties( this );
232 return !mlt_properties_get_int( properties
, "running" );
235 /** Add an audio output stream
238 static AVStream
*add_audio_stream( mlt_consumer
this, AVFormatContext
*oc
, int codec_id
)
240 // Get the properties
241 mlt_properties properties
= mlt_consumer_properties( this );
243 // Create a new stream
244 AVStream
*st
= av_new_stream( oc
, 1 );
246 // If created, then initialise from properties
249 AVCodecContext
*c
= &st
->codec
;
250 c
->codec_id
= codec_id
;
251 c
->codec_type
= CODEC_TYPE_AUDIO
;
253 // Put sample parameters
254 c
->bit_rate
= mlt_properties_get_int( properties
, "audio_bit_rate" );
255 c
->sample_rate
= mlt_properties_get_int( properties
, "frequency" );
256 c
->channels
= mlt_properties_get_int( properties
, "channels" );
260 fprintf( stderr
, "Could not allocate a stream for audio\n" );
266 static int open_audio( AVFormatContext
*oc
, AVStream
*st
, int audio_outbuf_size
)
268 // We will return the audio input size from here
269 int audio_input_frame_size
= 0;
272 AVCodecContext
*c
= &st
->codec
;
275 AVCodec
*codec
= avcodec_find_encoder( c
->codec_id
);
277 // Continue if codec found and we can open it
278 if ( codec
!= NULL
&& avcodec_open(c
, codec
) >= 0 )
280 // ugly hack for PCM codecs (will be removed ASAP with new PCM
281 // support to compute the input frame size in samples
282 if ( c
->frame_size
<= 1 )
284 audio_input_frame_size
= audio_outbuf_size
/ c
->channels
;
285 switch(st
->codec
.codec_id
)
287 case CODEC_ID_PCM_S16LE
:
288 case CODEC_ID_PCM_S16BE
:
289 case CODEC_ID_PCM_U16LE
:
290 case CODEC_ID_PCM_U16BE
:
291 audio_input_frame_size
>>= 1;
299 audio_input_frame_size
= c
->frame_size
;
304 fprintf( stderr
, "Unable to encode audio - disabling audio output.\n" );
307 return audio_input_frame_size
;
310 static void close_audio( AVFormatContext
*oc
, AVStream
*st
)
312 avcodec_close( &st
->codec
);
315 /** Add a video output stream
318 static AVStream
*add_video_stream( mlt_consumer
this, AVFormatContext
*oc
, int codec_id
)
320 // Get the properties
321 mlt_properties properties
= mlt_consumer_properties( this );
323 // Create a new stream
324 AVStream
*st
= av_new_stream( oc
, 0 );
328 AVCodecContext
*c
= &st
->codec
;
329 c
->codec_id
= codec_id
;
330 c
->codec_type
= CODEC_TYPE_VIDEO
;
332 // put sample parameters
333 c
->bit_rate
= mlt_properties_get_int( properties
, "video_bit_rate" );
334 c
->width
= mlt_properties_get_int( properties
, "width" );
335 c
->height
= mlt_properties_get_int( properties
, "height" );
336 c
->frame_rate
= mlt_properties_get_double( properties
, "fps" );
337 c
->frame_rate_base
= 1;
338 c
->gop_size
= mlt_properties_get_int( properties
, "gop_size" );
339 c
->max_b_frames
= mlt_properties_get_int( properties
, "max_b_frames" );
340 c
->mb_decision
= mlt_properties_get_int( properties
, "mb_decision" );
342 // Some formats want stream headers to be seperate (hmm)
343 if( !strcmp( oc
->oformat
->name
, "mp4" ) ||
344 !strcmp( oc
->oformat
->name
, "mov" ) ||
345 !strcmp( oc
->oformat
->name
, "3gp" ) )
346 c
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
350 fprintf( stderr
, "Could not allocate a stream for video\n" );
356 static AVFrame
*alloc_picture( int pix_fmt
, int width
, int height
)
359 AVFrame
*picture
= avcodec_alloc_frame();
361 // Determine size of the
362 int size
= avpicture_get_size(pix_fmt
, width
, height
);
364 // Allocate the picture buf
365 uint8_t *picture_buf
= av_malloc(size
);
367 // If we have both, then fill the image
368 if ( picture
!= NULL
&& picture_buf
!= NULL
)
370 // Fill the frame with the allocated buffer
371 avpicture_fill((AVPicture
*)picture
, picture_buf
, pix_fmt
, width
, height
);
375 // Something failed - clean up what we can
377 av_free(picture_buf
);
384 static int open_video(AVFormatContext
*oc
, AVStream
*st
)
387 AVCodecContext
*c
= &st
->codec
;
389 // find the video encoder
390 AVCodec
*codec
= avcodec_find_encoder(c
->codec_id
);
392 // Open the codec safely
393 return codec
!= NULL
&& avcodec_open(c
, codec
) >= 0;
396 void close_video(AVFormatContext
*oc
, AVStream
*st
)
398 avcodec_close(&st
->codec
);
401 /** The main thread - the argument is simply the consumer.
404 static void *consumer_thread( void *arg
)
406 // Map the argument to the object
407 mlt_consumer
this = arg
;
409 // Get the properties
410 mlt_properties properties
= mlt_consumer_properties( this );
412 // Get the terminate on pause property
413 int terminate_on_pause
= mlt_properties_get_int( properties
, "terminate_on_pause" );
415 // Get the frame rate
416 int fps
= mlt_properties_get_double( properties
, "fps" );
418 // Get width and height
419 int width
= mlt_properties_get_int( properties
, "width" );
420 int height
= mlt_properties_get_int( properties
, "height" );
421 int img_width
= width
;
422 int img_height
= height
;
424 // Get default audio properties
425 mlt_audio_format aud_fmt
= mlt_audio_pcm
;
426 int channels
= mlt_properties_get_int( properties
, "channels" );
427 int frequency
= mlt_properties_get_int( properties
, "frequency" );
431 // AVFormat audio buffer and frame size
432 int audio_outbuf_size
= 10000;
433 uint8_t *audio_outbuf
= av_malloc( audio_outbuf_size
);
434 int audio_input_frame_size
= 0;
436 // AVFormat video buffer and frame count
438 int video_outbuf_size
= 200000;
439 uint8_t *video_outbuf
= av_malloc(video_outbuf_size
);
441 // Used for the frame properties
442 mlt_frame frame
= NULL
;
443 mlt_properties frame_properties
= NULL
;
446 mlt_deque queue
= mlt_properties_get_data( properties
, "frame_queue", NULL
);
447 sample_fifo fifo
= mlt_properties_get_data( properties
, "sample_fifo", NULL
);
449 // Need two av pictures for converting
450 AVFrame
*output
= alloc_picture( PIX_FMT_YUV420P
, width
, height
);
451 AVFrame
*input
= alloc_picture( PIX_FMT_YUV422
, width
, height
);
453 // For receiving images from an mlt_frame
455 mlt_image_format img_fmt
= mlt_image_yuv422
;
457 // Fo receiving audio samples back from the fifo
458 int16_t buffer
[ 48000 * 2 ];
461 // Allocate the context
462 AVFormatContext
*oc
= av_alloc_format_context();
465 AVStream
*audio_st
= NULL
;
466 AVStream
*video_st
= NULL
;
469 double audio_pts
, video_pts
;
474 // Determine the format
475 AVOutputFormat
*fmt
= NULL
;
476 char *filename
= mlt_properties_get( properties
, "target" );
477 char *format
= mlt_properties_get( properties
, "format" );
478 //char *vcodec = mlt_properties_get( properties, "vcodec" );
479 //char *acodec = mlt_properties_get( properties, "acodec" );
481 // Check for user selected format first
482 if ( format
!= NULL
)
483 fmt
= guess_format( format
, NULL
, NULL
);
485 // Otherwise check on the filename
486 if ( fmt
== NULL
&& filename
!= NULL
)
487 fmt
= guess_format( NULL
, filename
, NULL
);
489 // Otherwise default to mpeg
491 fmt
= guess_format( "mpeg", NULL
, NULL
);
493 // We need a filename - default to stdout?
494 if ( filename
== NULL
)
497 // Update the output context
499 snprintf( oc
->filename
, sizeof(oc
->filename
), "%s", filename
);
501 // Add audio and video streams
502 if ( fmt
->video_codec
!= CODEC_ID_NONE
)
503 video_st
= add_video_stream( this, oc
, fmt
->video_codec
);
504 if ( fmt
->audio_codec
!= CODEC_ID_NONE
)
505 audio_st
= add_audio_stream( this, oc
, fmt
->audio_codec
);
507 // Set the parameters (even though we have none...)
508 if ( av_set_parameters(oc
, NULL
) >= 0 )
510 if ( video_st
&& !open_video( oc
, video_st
) )
513 audio_input_frame_size
= open_audio( oc
, audio_st
, audio_outbuf_size
);
515 // Open the output file, if needed
516 if ( !( fmt
->flags
& AVFMT_NOFILE
) )
518 if (url_fopen(&oc
->pb
, filename
, URL_WRONLY
) < 0)
520 fprintf(stderr
, "Could not open '%s'\n", filename
);
521 mlt_properties_set_int( properties
, "running", 0 );
525 // Write the stream header, if any
526 if ( mlt_properties_get_int( properties
, "running" ) )
527 av_write_header( oc
);
531 fprintf(stderr
, "Invalid output format parameters\n");
532 mlt_properties_set_int( properties
, "running", 0 );
535 // Last check - need at least one stream
536 if ( audio_st
== NULL
&& video_st
== NULL
)
537 mlt_properties_set_int( properties
, "running", 0 );
539 // Loop while running
540 while( mlt_properties_get_int( properties
, "running" ) )
543 frame
= mlt_consumer_rt_frame( this );
545 // Check that we have a frame to work with
548 // Default audio args
549 frame_properties
= mlt_frame_properties( frame
);
551 // Get audio and append to the fifo
554 samples
= mlt_sample_calculator( fps
, frequency
, count
);
555 mlt_frame_get_audio( frame
, &pcm
, &aud_fmt
, &frequency
, &channels
, &samples
);
556 sample_fifo_append( fifo
, pcm
, samples
* channels
);
561 mlt_deque_push_back( queue
, frame
);
563 mlt_frame_close( frame
);
565 // While we have stuff to process, process...
568 // Compute current audio and video time
570 audio_pts
= (double)audio_st
->pts
.val
* oc
->pts_num
/ oc
->pts_den
;
575 video_pts
= (double)video_st
->pts
.val
* oc
->pts_num
/ oc
->pts_den
;
579 // Write interleaved audio and video frames
580 if ( !video_st
|| ( video_st
&& audio_st
&& audio_pts
< video_pts
) )
582 if ( channels
* audio_input_frame_size
< sample_fifo_used( fifo
) )
587 c
= &audio_st
->codec
;
589 sample_fifo_fetch( fifo
, buffer
, channels
* audio_input_frame_size
);
591 out_size
= avcodec_encode_audio( c
, audio_outbuf
, audio_outbuf_size
, buffer
);
593 // Write the compressed frame in the media file
594 if (av_write_frame(oc
, audio_st
->index
, audio_outbuf
, out_size
) != 0)
595 fprintf(stderr
, "Error while writing audio frame\n");
604 if ( mlt_deque_count( queue
) )
609 frame
= mlt_deque_pop_front( queue
);
610 frame_properties
= mlt_frame_properties( frame
);
612 if ( terminate_on_pause
&& mlt_properties_get_double( frame_properties
, "_speed" ) == 0.0 )
614 mlt_properties_set_int( properties
, "running", 0 );
618 c
= &video_st
->codec
;
620 if ( mlt_properties_get_int( frame_properties
, "rendered" ) )
627 mlt_frame_get_image( frame
, &image
, &img_fmt
, &img_width
, &img_height
, 0 );
631 for ( i
= 0; i
< height
; i
++ )
633 p
= input
->data
[ 0 ] + i
* input
->linesize
[ 0 ];
642 img_convert( ( AVPicture
* )output
, PIX_FMT_YUV420P
, ( AVPicture
* )input
, PIX_FMT_YUV422
, width
, height
);
645 if (oc
->oformat
->flags
& AVFMT_RAWPICTURE
)
647 // raw video case. The API will change slightly in the near future for that
648 ret
= av_write_frame(oc
, video_st
->index
, (uint8_t *)output
, sizeof(AVPicture
));
653 out_size
= avcodec_encode_video(c
, video_outbuf
, video_outbuf_size
, output
);
655 // If zero size, it means the image was buffered
658 // write the compressed frame in the media file
659 // XXX: in case of B frames, the pts is not yet valid
660 ret
= av_write_frame( oc
, video_st
->index
, video_outbuf
, out_size
);
664 mlt_frame_close( frame
);
677 close_video(oc
, video_st
);
679 close_audio(oc
, audio_st
);
681 // Write the trailer, if any
682 av_write_trailer(oc
);
685 for(i
= 0; i
< oc
->nb_streams
; i
++)
686 av_freep(&oc
->streams
[i
]);
688 // Close the output file
689 if (!(fmt
->flags
& AVFMT_NOFILE
))
692 // Clean up input and output frames
693 av_free( output
->data
[0] );
695 av_free( input
->data
[0] );
697 av_free( video_outbuf
);
705 /** Close the consumer.
708 static void consumer_close( mlt_consumer
this )
711 mlt_consumer_stop( this );
714 mlt_consumer_close( this );