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 = 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 /** The main thread - the argument is simply the consumer.
426 static void *consumer_thread( void *arg )
428 // Map the argument to the object
429 mlt_consumer this = arg;
431 // Get the properties
432 mlt_properties properties = mlt_consumer_properties( this );
434 // Get the terminate on pause property
435 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
437 // Get the frame rate
438 int fps = mlt_properties_get_double( properties, "fps" );
440 // Get width and height
441 int width = mlt_properties_get_int( properties, "width" );
442 int height = mlt_properties_get_int( properties, "height" );
443 int img_width = width;
444 int img_height = height;
446 // Get default audio properties
447 mlt_audio_format aud_fmt = mlt_audio_pcm;
448 int channels = mlt_properties_get_int( properties, "channels" );
449 int frequency = mlt_properties_get_int( properties, "frequency" );
453 // AVFormat audio buffer and frame size
454 int audio_outbuf_size = 2 * 128 * 1024;
455 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
456 int audio_input_frame_size = 0;
458 // AVFormat video buffer and frame count
460 int video_outbuf_size = ( 1024 * 1024 );
461 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
463 // Used for the frame properties
464 mlt_frame frame = NULL;
465 mlt_properties frame_properties = NULL;
468 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
469 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
471 // Need two av pictures for converting
472 AVFrame *output = alloc_picture( PIX_FMT_YUV420P, width, height );
473 AVFrame *input = alloc_picture( PIX_FMT_YUV422, width, height );
475 // For receiving images from an mlt_frame
477 mlt_image_format img_fmt = mlt_image_yuv422;
479 // Fo receiving audio samples back from the fifo
480 int16_t buffer[ 48000 * 2 ];
483 // Allocate the context
484 AVFormatContext *oc = av_alloc_format_context( );
487 AVStream *audio_st = NULL;
488 AVStream *video_st = NULL;
491 double audio_pts, video_pts;
496 // Determine the format
497 AVOutputFormat *fmt = NULL;
498 char *filename = mlt_properties_get( properties, "target" );
499 char *format = mlt_properties_get( properties, "format" );
500 char *vcodec = mlt_properties_get( properties, "vcodec" );
501 char *acodec = mlt_properties_get( properties, "acodec" );
503 // Used to store and override codec ids
507 // Check for user selected format first
508 if ( format != NULL )
509 fmt = guess_format( format, NULL, NULL );
511 // Otherwise check on the filename
512 if ( fmt == NULL && filename != NULL )
513 fmt = guess_format( NULL, filename, NULL );
515 // Otherwise default to mpeg
517 fmt = guess_format( "mpeg", NULL, NULL );
519 // We need a filename - default to stdout?
520 if ( filename == NULL )
523 // Get the codec ids selected
524 audio_codec_id = fmt->audio_codec;
525 video_codec_id = fmt->video_codec;
527 // Check for audio codec overides
528 if ( acodec != NULL )
530 AVCodec *p = first_avcodec;
533 if ( !strcmp( p->name, acodec ) && p->type == CODEC_TYPE_AUDIO )
538 audio_codec_id = p->id;
540 fprintf( stderr, "consumer_avcodec: audio codec %s unrecognised - ignoring\n", acodec );
543 // Check for video codec overides
544 if ( vcodec != NULL )
546 AVCodec *p = first_avcodec;
549 if ( !strcmp( p->name, vcodec ) && p->type == CODEC_TYPE_VIDEO )
554 video_codec_id = p->id;
556 fprintf( stderr, "consumer_avcodec: video codec %s unrecognised - ignoring\n", vcodec );
559 // Update the output context
561 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
563 // Add audio and video streams
564 if ( fmt->video_codec != CODEC_ID_NONE )
565 video_st = add_video_stream( this, oc, video_codec_id );
566 if ( fmt->audio_codec != CODEC_ID_NONE )
567 audio_st = add_audio_stream( this, oc, audio_codec_id );
569 // Set the parameters (even though we have none...)
570 if ( av_set_parameters(oc, NULL) >= 0 )
572 if ( video_st && !open_video( oc, video_st ) )
575 audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
577 // Open the output file, if needed
578 if ( !( fmt->flags & AVFMT_NOFILE ) )
580 if (url_fopen(&oc->pb, filename, URL_RDWR) < 0)
582 fprintf(stderr, "Could not open '%s'\n", filename);
583 mlt_properties_set_int( properties, "running", 0 );
587 if ( url_is_streamed( &oc->pb ) )
588 fprintf( stderr, "FUCK!\n" );
590 // Write the stream header, if any
591 if ( mlt_properties_get_int( properties, "running" ) )
592 av_write_header( oc );
596 fprintf(stderr, "Invalid output format parameters\n");
597 mlt_properties_set_int( properties, "running", 0 );
600 // Last check - need at least one stream
601 if ( audio_st == NULL && video_st == NULL )
602 mlt_properties_set_int( properties, "running", 0 );
604 // Loop while running
605 while( mlt_properties_get_int( properties, "running" ) )
608 frame = mlt_consumer_rt_frame( this );
610 // Check that we have a frame to work with
613 // Default audio args
614 frame_properties = mlt_frame_properties( frame );
616 // Get audio and append to the fifo
619 samples = mlt_sample_calculator( fps, frequency, count );
620 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
621 sample_fifo_append( fifo, pcm, samples * channels );
626 mlt_deque_push_back( queue, frame );
628 mlt_frame_close( frame );
630 // While we have stuff to process, process...
633 // Compute current audio and video time
635 audio_pts = (double)audio_st->pts.val * oc->pts_num / oc->pts_den;
640 video_pts = (double)video_st->pts.val * oc->pts_num / oc->pts_den;
644 // Write interleaved audio and video frames
645 if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
647 if ( channels * audio_input_frame_size < sample_fifo_used( fifo ) )
652 c = &audio_st->codec;
654 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
656 out_size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
658 // Write the compressed frame in the media file
659 if (av_write_frame(oc, audio_st->index, audio_outbuf, out_size) != 0)
660 fprintf(stderr, "Error while writing audio frame\n");
669 if ( mlt_deque_count( queue ) )
674 frame = mlt_deque_pop_front( queue );
675 frame_properties = mlt_frame_properties( frame );
677 if ( terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0 )
679 mlt_properties_set_int( properties, "running", 0 );
683 c = &video_st->codec;
685 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
692 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
696 for ( i = 0; i < height; i ++ )
698 p = input->data[ 0 ] + i * input->linesize[ 0 ];
707 img_convert( ( AVPicture * )output, PIX_FMT_YUV420P, ( AVPicture * )input, PIX_FMT_YUV422, width, height );
710 if (oc->oformat->flags & AVFMT_RAWPICTURE)
712 // raw video case. The API will change slightly in the near future for that
713 ret = av_write_frame(oc, video_st->index, (uint8_t *)output, sizeof(AVPicture));
718 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
720 // If zero size, it means the image was buffered
723 // write the compressed frame in the media file
724 // XXX: in case of B frames, the pts is not yet valid
725 ret = av_write_frame( oc, video_st->index, video_outbuf, out_size );
729 mlt_frame_close( frame );
742 close_video(oc, video_st);
744 close_audio(oc, audio_st);
746 // Write the trailer, if any
747 av_write_trailer(oc);
750 for(i = 0; i < oc->nb_streams; i++)
751 av_freep(&oc->streams[i]);
753 // Close the output file
754 if (!(fmt->flags & AVFMT_NOFILE))
757 // Clean up input and output frames
758 av_free( output->data[0] );
760 av_free( input->data[0] );
762 av_free( video_outbuf );
770 /** Close the consumer.
773 static void consumer_close( mlt_consumer this )
776 mlt_consumer_stop( this );
779 mlt_consumer_close( this );