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 ) );
158 // Get the width and height
159 int width = mlt_properties_get_int( properties, "width" );
160 int height = mlt_properties_get_int( properties, "height" );
162 // Obtain the size property
163 char *size = mlt_properties_get( properties, "size" );
169 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
176 fprintf( stderr, "consumer_avformat: Invalid size property %s - ignoring.\n", size );
180 // Now ensure we honour the multiple of two requested by libavformat
181 mlt_properties_set_int( properties, "width", ( width / 2 ) * 2 );
182 mlt_properties_set_int( properties, "height", ( height / 2 ) * 2 );
184 // Assign the thread to properties
185 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
187 // Set the running state
188 mlt_properties_set_int( properties, "running", 1 );
191 pthread_create( thread, NULL, consumer_thread, this );
196 /** Stop the consumer.
199 static int consumer_stop( mlt_consumer this )
201 // Get the properties
202 mlt_properties properties = mlt_consumer_properties( this );
204 // Check that we're running
205 if ( mlt_properties_get_int( properties, "running" ) )
208 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
211 mlt_properties_set_int( properties, "running", 0 );
213 // Wait for termination
214 pthread_join( *thread, NULL );
220 /** Determine if the consumer is stopped.
223 static int consumer_is_stopped( mlt_consumer this )
225 // Get the properties
226 mlt_properties properties = mlt_consumer_properties( this );
227 return !mlt_properties_get_int( properties, "running" );
230 /** Add an audio output stream
233 static AVStream *add_audio_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
235 // Get the properties
236 mlt_properties properties = mlt_consumer_properties( this );
238 // Create a new stream
239 AVStream *st = av_new_stream( oc, 1 );
241 // If created, then initialise from properties
244 AVCodecContext *c = &st->codec;
245 c->codec_id = codec_id;
246 c->codec_type = CODEC_TYPE_AUDIO;
248 // Put sample parameters
249 c->bit_rate = mlt_properties_get_int( properties, "audio_bit_rate" );
250 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
251 c->channels = mlt_properties_get_int( properties, "channels" );
255 fprintf( stderr, "Could not allocate a stream for audio\n" );
261 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
263 // We will return the audio input size from here
264 int audio_input_frame_size = 0;
267 AVCodecContext *c = &st->codec;
270 AVCodec *codec = avcodec_find_encoder( c->codec_id );
272 // Continue if codec found and we can open it
273 if ( codec != NULL && avcodec_open(c, codec) >= 0 )
275 // ugly hack for PCM codecs (will be removed ASAP with new PCM
276 // support to compute the input frame size in samples
277 if ( c->frame_size <= 1 )
279 audio_input_frame_size = audio_outbuf_size / c->channels;
280 switch(st->codec.codec_id)
282 case CODEC_ID_PCM_S16LE:
283 case CODEC_ID_PCM_S16BE:
284 case CODEC_ID_PCM_U16LE:
285 case CODEC_ID_PCM_U16BE:
286 audio_input_frame_size >>= 1;
294 audio_input_frame_size = c->frame_size;
299 fprintf( stderr, "Unable to encode audio - disabling audio output.\n" );
302 return audio_input_frame_size;
305 static void close_audio( AVFormatContext *oc, AVStream *st )
307 avcodec_close( &st->codec );
310 /** Add a video output stream
313 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
315 // Get the properties
316 mlt_properties properties = mlt_consumer_properties( this );
318 // Create a new stream
319 AVStream *st = av_new_stream( oc, 0 );
323 AVCodecContext *c = &st->codec;
324 c->codec_id = codec_id;
325 c->codec_type = CODEC_TYPE_VIDEO;
327 // put sample parameters
328 c->bit_rate = mlt_properties_get_int( properties, "video_bit_rate" );
329 c->width = mlt_properties_get_int( properties, "width" );
330 c->height = mlt_properties_get_int( properties, "height" );
331 c->frame_rate = mlt_properties_get_double( properties, "fps" );
332 c->frame_rate_base = 1;
333 c->gop_size = mlt_properties_get_int( properties, "gop_size" );
334 c->max_b_frames = mlt_properties_get_int( properties, "max_b_frames" );
335 c->mb_decision = mlt_properties_get_int( properties, "mb_decision" );
337 // Some formats want stream headers to be seperate (hmm)
338 if( !strcmp( oc->oformat->name, "mp4" ) ||
339 !strcmp( oc->oformat->name, "mov" ) ||
340 !strcmp( oc->oformat->name, "3gp" ) )
341 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
345 fprintf( stderr, "Could not allocate a stream for video\n" );
351 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
354 AVFrame *picture = avcodec_alloc_frame();
356 // Determine size of the
357 int size = avpicture_get_size(pix_fmt, width, height);
359 // Allocate the picture buf
360 uint8_t *picture_buf = av_malloc(size);
362 // If we have both, then fill the image
363 if ( picture != NULL && picture_buf != NULL )
365 // Fill the frame with the allocated buffer
366 avpicture_fill((AVPicture *)picture, picture_buf, pix_fmt, width, height);
370 // Something failed - clean up what we can
372 av_free(picture_buf);
379 static int open_video(AVFormatContext *oc, AVStream *st)
382 AVCodecContext *c = &st->codec;
384 // find the video encoder
385 AVCodec *codec = avcodec_find_encoder(c->codec_id);
387 // Open the codec safely
388 return codec != NULL && avcodec_open(c, codec) >= 0;
391 void close_video(AVFormatContext *oc, AVStream *st)
393 avcodec_close(&st->codec);
396 /** The main thread - the argument is simply the consumer.
399 static void *consumer_thread( void *arg )
401 // Map the argument to the object
402 mlt_consumer this = arg;
404 // Get the properties
405 mlt_properties properties = mlt_consumer_properties( this );
407 // Get the terminate on pause property
408 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
410 // Get the frame rate
411 int fps = mlt_properties_get_double( properties, "fps" );
413 // Get width and height
414 int width = mlt_properties_get_int( properties, "width" );
415 int height = mlt_properties_get_int( properties, "height" );
416 int img_width = width;
417 int img_height = height;
419 // Get default audio properties
420 mlt_audio_format aud_fmt = mlt_audio_pcm;
421 int channels = mlt_properties_get_int( properties, "channels" );
422 int frequency = mlt_properties_get_int( properties, "frequency" );
426 // AVFormat audio buffer and frame size
427 int audio_outbuf_size = 10000;
428 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
429 int audio_input_frame_size = 0;
431 // AVFormat video buffer and frame count
433 int video_outbuf_size = 200000;
434 uint8_t *video_outbuf = av_malloc(video_outbuf_size);
436 // Used for the frame properties
437 mlt_frame frame = NULL;
438 mlt_properties frame_properties = NULL;
441 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
442 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
444 // Need two av pictures for converting
445 AVFrame *output = alloc_picture( PIX_FMT_YUV420P, width, height );
446 AVFrame *input = alloc_picture( PIX_FMT_YUV422, width, height );
448 // For receiving images from an mlt_frame
450 mlt_image_format img_fmt = mlt_image_yuv422;
452 // Fo receiving audio samples back from the fifo
453 int16_t buffer[ 48000 * 2 ];
456 // Allocate the context
457 AVFormatContext *oc = av_alloc_format_context();
460 AVStream *audio_st = NULL;
461 AVStream *video_st = NULL;
464 double audio_pts, video_pts;
469 // Determine the format
470 AVOutputFormat *fmt = NULL;
471 char *filename = mlt_properties_get( properties, "target" );
472 char *format = mlt_properties_get( properties, "format" );
473 //char *vcodec = mlt_properties_get( properties, "vcodec" );
474 //char *acodec = mlt_properties_get( properties, "acodec" );
476 // Check for user selected format first
477 if ( format != NULL )
478 fmt = guess_format( format, NULL, NULL );
480 // Otherwise check on the filename
481 if ( fmt == NULL && filename != NULL )
482 fmt = guess_format( NULL, filename, NULL );
484 // Otherwise default to mpeg
486 fmt = guess_format( "mpeg", NULL, NULL );
488 // We need a filename - default to stdout?
489 if ( filename == NULL )
492 // Update the output context
494 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
496 // Add audio and video streams
497 if ( fmt->video_codec != CODEC_ID_NONE )
498 video_st = add_video_stream( this, oc, fmt->video_codec );
499 if ( fmt->audio_codec != CODEC_ID_NONE )
500 audio_st = add_audio_stream( this, oc, fmt->audio_codec );
502 // Set the parameters (even though we have none...)
503 if ( av_set_parameters(oc, NULL) >= 0 )
505 if ( video_st && !open_video( oc, video_st ) )
508 audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
510 // Open the output file, if needed
511 if ( !( fmt->flags & AVFMT_NOFILE ) )
513 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0)
515 fprintf(stderr, "Could not open '%s'\n", filename);
516 mlt_properties_set_int( properties, "running", 0 );
520 // Write the stream header, if any
521 if ( mlt_properties_get_int( properties, "running" ) )
522 av_write_header( oc );
526 fprintf(stderr, "Invalid output format parameters\n");
527 mlt_properties_set_int( properties, "running", 0 );
530 // Last check - need at least one stream
531 if ( audio_st == NULL && video_st == NULL )
532 mlt_properties_set_int( properties, "running", 0 );
534 // Loop while running
535 while( mlt_properties_get_int( properties, "running" ) )
538 frame = mlt_consumer_rt_frame( this );
540 // Check that we have a frame to work with
543 // Default audio args
544 frame_properties = mlt_frame_properties( frame );
546 // Get audio and append to the fifo
549 samples = mlt_sample_calculator( fps, frequency, count );
550 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
551 sample_fifo_append( fifo, pcm, samples * channels );
556 mlt_deque_push_back( queue, frame );
558 mlt_frame_close( frame );
560 // While we have stuff to process, process...
563 // Compute current audio and video time
565 audio_pts = (double)audio_st->pts.val * oc->pts_num / oc->pts_den;
570 video_pts = (double)video_st->pts.val * oc->pts_num / oc->pts_den;
574 // Write interleaved audio and video frames
575 if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
577 if ( channels * audio_input_frame_size < sample_fifo_used( fifo ) )
582 c = &audio_st->codec;
584 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
586 out_size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
588 // Write the compressed frame in the media file
589 if (av_write_frame(oc, audio_st->index, audio_outbuf, out_size) != 0)
590 fprintf(stderr, "Error while writing audio frame\n");
599 if ( mlt_deque_count( queue ) )
604 frame = mlt_deque_pop_front( queue );
605 frame_properties = mlt_frame_properties( frame );
607 if ( terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0 )
609 mlt_properties_set_int( properties, "running", 0 );
613 c = &video_st->codec;
615 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
622 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
626 for ( i = 0; i < height; i ++ )
628 p = input->data[ 0 ] + i * input->linesize[ 0 ];
637 img_convert( ( AVPicture * )output, PIX_FMT_YUV420P, ( AVPicture * )input, PIX_FMT_YUV422, width, height );
640 if (oc->oformat->flags & AVFMT_RAWPICTURE)
642 // raw video case. The API will change slightly in the near future for that
643 ret = av_write_frame(oc, video_st->index, (uint8_t *)output, sizeof(AVPicture));
648 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
650 // If zero size, it means the image was buffered
653 // write the compressed frame in the media file
654 // XXX: in case of B frames, the pts is not yet valid
655 ret = av_write_frame( oc, video_st->index, video_outbuf, out_size );
659 mlt_frame_close( frame );
672 close_video(oc, video_st);
674 close_audio(oc, audio_st);
676 // Write the trailer, if any
677 av_write_trailer(oc);
680 for(i = 0; i < oc->nb_streams; i++)
681 av_freep(&oc->streams[i]);
683 // Close the output file
684 if (!(fmt->flags & AVFMT_NOFILE))
687 // Clean up input and output frames
688 av_free( output->data[0] );
690 av_free( input->data[0] );
692 av_free( video_outbuf );
700 /** Close the consumer.
703 static void consumer_close( mlt_consumer this )
706 mlt_consumer_stop( this );
709 mlt_consumer_close( this );