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", 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;
139 // Clean up in case of init failure
148 /** Start the consumer.
151 static int consumer_start( mlt_consumer this )
153 // Get the properties
154 mlt_properties properties = mlt_consumer_properties( this );
156 // Check that we're not already running
157 if ( !mlt_properties_get_int( properties, "running" ) )
160 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
161 pthread_attr_t thread_attributes;
163 // Get the width and height
164 int width = mlt_properties_get_int( properties, "width" );
165 int height = mlt_properties_get_int( properties, "height" );
167 // Obtain the size property
168 char *size = mlt_properties_get( properties, "size" );
174 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
181 fprintf( stderr, "consumer_avformat: Invalid size property %s - ignoring.\n", size );
185 // Now ensure we honour the multiple of two requested by libavformat
186 mlt_properties_set_int( properties, "width", ( width / 2 ) * 2 );
187 mlt_properties_set_int( properties, "height", ( height / 2 ) * 2 );
189 // Assign the thread to properties
190 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
192 // Set the running state
193 mlt_properties_set_int( properties, "running", 1 );
195 // Inherit the scheduling priority
196 pthread_attr_init( &thread_attributes );
197 pthread_attr_setinheritsched( &thread_attributes, PTHREAD_INHERIT_SCHED );
200 pthread_create( thread, &thread_attributes, consumer_thread, this );
205 /** Stop the consumer.
208 static int consumer_stop( mlt_consumer this )
210 // Get the properties
211 mlt_properties properties = mlt_consumer_properties( this );
213 // Check that we're running
214 if ( mlt_properties_get_int( properties, "running" ) )
217 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
220 mlt_properties_set_int( properties, "running", 0 );
222 // Wait for termination
223 pthread_join( *thread, NULL );
229 /** Determine if the consumer is stopped.
232 static int consumer_is_stopped( mlt_consumer this )
234 // Get the properties
235 mlt_properties properties = mlt_consumer_properties( this );
236 return !mlt_properties_get_int( properties, "running" );
239 /** Add an audio output stream
242 static AVStream *add_audio_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
244 // Get the properties
245 mlt_properties properties = mlt_consumer_properties( this );
247 // Create a new stream
248 AVStream *st = av_new_stream( oc, 1 );
250 // If created, then initialise from properties
253 AVCodecContext *c = &st->codec;
254 c->codec_id = codec_id;
255 c->codec_type = CODEC_TYPE_AUDIO;
257 // Put sample parameters
258 c->bit_rate = mlt_properties_get_int( properties, "audio_bit_rate" );
259 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
260 c->channels = mlt_properties_get_int( properties, "channels" );
264 fprintf( stderr, "Could not allocate a stream for audio\n" );
270 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
272 // We will return the audio input size from here
273 int audio_input_frame_size = 0;
276 AVCodecContext *c = &st->codec;
279 AVCodec *codec = avcodec_find_encoder( c->codec_id );
281 // Continue if codec found and we can open it
282 if ( codec != NULL && avcodec_open(c, codec) >= 0 )
284 // ugly hack for PCM codecs (will be removed ASAP with new PCM
285 // support to compute the input frame size in samples
286 if ( c->frame_size <= 1 )
288 audio_input_frame_size = audio_outbuf_size / c->channels;
289 switch(st->codec.codec_id)
291 case CODEC_ID_PCM_S16LE:
292 case CODEC_ID_PCM_S16BE:
293 case CODEC_ID_PCM_U16LE:
294 case CODEC_ID_PCM_U16BE:
295 audio_input_frame_size >>= 1;
303 audio_input_frame_size = c->frame_size;
306 // Some formats want stream headers to be seperate (hmm)
307 if( !strcmp( oc->oformat->name, "mp4" ) ||
308 !strcmp( oc->oformat->name, "mov" ) ||
309 !strcmp( oc->oformat->name, "3gp" ) )
310 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
314 fprintf( stderr, "Unable to encode audio - disabling audio output.\n" );
317 return audio_input_frame_size;
320 static void close_audio( AVFormatContext *oc, AVStream *st )
322 avcodec_close( &st->codec );
325 /** Add a video output stream
328 static AVStream *add_video_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, 0 );
338 AVCodecContext *c = &st->codec;
339 c->codec_id = codec_id;
340 c->codec_type = CODEC_TYPE_VIDEO;
342 // put sample parameters
343 c->bit_rate = mlt_properties_get_int( properties, "video_bit_rate" );
344 c->bit_rate_tolerance = mlt_properties_get_int( properties, "video_bit_rate_tolerance" );
345 c->width = mlt_properties_get_int( properties, "width" );
346 c->height = mlt_properties_get_int( properties, "height" );
347 c->frame_rate = mlt_properties_get_double( properties, "fps" );
348 c->frame_rate_base = mlt_properties_get_double( properties, "frame_rate_base" );
349 c->frame_rate_base = 1;
350 c->gop_size = mlt_properties_get_int( properties, "gop_size" );
351 c->max_b_frames = mlt_properties_get_int( properties, "max_b_frames" );
352 if ( c->max_b_frames )
354 c->b_frame_strategy = 0;
355 c->b_quant_factor = 2.0;
358 c->mb_decision = mlt_properties_get_int( properties, "mb_decision" );
359 c->sample_aspect_ratio = av_d2q( mlt_properties_get_double( properties, "aspect_ratio" ), 255 );
362 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
364 c->flags |= CODEC_FLAG_QSCALE;
365 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
368 // Some formats want stream headers to be seperate (hmm)
369 if( !strcmp( oc->oformat->name, "mp4" ) ||
370 !strcmp( oc->oformat->name, "mov" ) ||
371 !strcmp( oc->oformat->name, "3gp" ) )
372 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
374 c->me_method = mlt_properties_get_int( properties, "me_method" );
378 fprintf( stderr, "Could not allocate a stream for video\n" );
384 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
387 AVFrame *picture = avcodec_alloc_frame();
389 // Determine size of the
390 int size = avpicture_get_size(pix_fmt, width, height);
392 // Allocate the picture buf
393 uint8_t *picture_buf = av_malloc(size);
395 // If we have both, then fill the image
396 if ( picture != NULL && picture_buf != NULL )
398 // Fill the frame with the allocated buffer
399 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
403 // Something failed - clean up what we can
405 av_free( picture_buf );
412 static int open_video(AVFormatContext *oc, AVStream *st)
415 AVCodecContext *c = &st->codec;
417 // find the video encoder
418 AVCodec *codec = avcodec_find_encoder(c->codec_id);
420 // Open the codec safely
421 return codec != NULL && avcodec_open(c, codec) >= 0;
424 void close_video(AVFormatContext *oc, AVStream *st)
426 avcodec_close(&st->codec);
429 /** The main thread - the argument is simply the consumer.
432 static void *consumer_thread( void *arg )
434 // Map the argument to the object
435 mlt_consumer this = arg;
437 // Get the properties
438 mlt_properties properties = mlt_consumer_properties( this );
440 // Get the terminate on pause property
441 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
443 // Get the frame rate
444 int fps = mlt_properties_get_double( properties, "fps" );
446 // Get width and height
447 int width = mlt_properties_get_int( properties, "width" );
448 int height = mlt_properties_get_int( properties, "height" );
449 int img_width = width;
450 int img_height = height;
452 // Get default audio properties
453 mlt_audio_format aud_fmt = mlt_audio_pcm;
454 int channels = mlt_properties_get_int( properties, "channels" );
455 int frequency = mlt_properties_get_int( properties, "frequency" );
459 // AVFormat audio buffer and frame size
460 int audio_outbuf_size = 2 * 128 * 1024;
461 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
462 int audio_input_frame_size = 0;
464 // AVFormat video buffer and frame count
466 int video_outbuf_size = ( 1024 * 1024 );
467 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
469 // Used for the frame properties
470 mlt_frame frame = NULL;
471 mlt_properties frame_properties = NULL;
474 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
475 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
477 // Need two av pictures for converting
478 AVFrame *output = alloc_picture( PIX_FMT_YUV420P, width, height );
479 AVFrame *input = alloc_picture( PIX_FMT_YUV422, width, height );
481 // For receiving images from an mlt_frame
483 mlt_image_format img_fmt = mlt_image_yuv422;
485 // Fo receiving audio samples back from the fifo
486 int16_t buffer[ 48000 * 2 ];
489 // Allocate the context
490 AVFormatContext *oc = av_alloc_format_context( );
493 AVStream *audio_st = NULL;
494 AVStream *video_st = NULL;
497 double audio_pts, video_pts;
502 // Determine the format
503 AVOutputFormat *fmt = NULL;
504 char *filename = mlt_properties_get( properties, "target" );
505 char *format = mlt_properties_get( properties, "format" );
506 char *vcodec = mlt_properties_get( properties, "vcodec" );
507 char *acodec = mlt_properties_get( properties, "acodec" );
509 // Used to store and override codec ids
513 // Check for user selected format first
514 if ( format != NULL )
515 fmt = guess_format( format, NULL, NULL );
517 // Otherwise check on the filename
518 if ( fmt == NULL && filename != NULL )
519 fmt = guess_format( NULL, filename, NULL );
521 // Otherwise default to mpeg
523 fmt = guess_format( "mpeg", NULL, NULL );
525 // We need a filename - default to stdout?
526 if ( filename == NULL )
529 // Get the codec ids selected
530 audio_codec_id = fmt->audio_codec;
531 video_codec_id = fmt->video_codec;
533 // Check for audio codec overides
534 if ( acodec != NULL )
536 AVCodec *p = first_avcodec;
539 if ( !strcmp( p->name, acodec ) && p->type == CODEC_TYPE_AUDIO )
544 audio_codec_id = p->id;
546 fprintf( stderr, "consumer_avcodec: audio codec %s unrecognised - ignoring\n", acodec );
549 // Check for video codec overides
550 if ( vcodec != NULL )
552 AVCodec *p = first_avcodec;
555 if ( !strcmp( p->name, vcodec ) && p->type == CODEC_TYPE_VIDEO )
560 video_codec_id = p->id;
562 fprintf( stderr, "consumer_avcodec: video codec %s unrecognised - ignoring\n", vcodec );
565 // Update the output context
567 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
569 // Add audio and video streams
570 if ( fmt->video_codec != CODEC_ID_NONE )
571 video_st = add_video_stream( this, oc, video_codec_id );
572 if ( fmt->audio_codec != CODEC_ID_NONE )
573 audio_st = add_audio_stream( this, oc, audio_codec_id );
575 // Set the parameters (even though we have none...)
576 if ( av_set_parameters(oc, NULL) >= 0 )
578 if ( video_st && !open_video( oc, video_st ) )
581 audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
583 // Open the output file, if needed
584 if ( !( fmt->flags & AVFMT_NOFILE ) )
586 if (url_fopen(&oc->pb, filename, URL_RDWR) < 0)
588 fprintf(stderr, "Could not open '%s'\n", filename);
589 mlt_properties_set_int( properties, "running", 0 );
593 if ( url_is_streamed( &oc->pb ) )
594 fprintf( stderr, "FUCK!\n" );
596 // Write the stream header, if any
597 if ( mlt_properties_get_int( properties, "running" ) )
598 av_write_header( oc );
602 fprintf(stderr, "Invalid output format parameters\n");
603 mlt_properties_set_int( properties, "running", 0 );
606 // Last check - need at least one stream
607 if ( audio_st == NULL && video_st == NULL )
608 mlt_properties_set_int( properties, "running", 0 );
610 // Loop while running
611 while( mlt_properties_get_int( properties, "running" ) )
614 frame = mlt_consumer_rt_frame( this );
616 // Check that we have a frame to work with
619 // Default audio args
620 frame_properties = mlt_frame_properties( frame );
622 // Get audio and append to the fifo
625 samples = mlt_sample_calculator( fps, frequency, count );
626 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
627 sample_fifo_append( fifo, pcm, samples * channels );
632 mlt_deque_push_back( queue, frame );
634 mlt_frame_close( frame );
636 // While we have stuff to process, process...
639 // Compute current audio and video time
641 audio_pts = (double)audio_st->pts.val * oc->pts_num / oc->pts_den;
646 video_pts = (double)video_st->pts.val * oc->pts_num / oc->pts_den;
650 // Write interleaved audio and video frames
651 if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
653 if ( channels * audio_input_frame_size < sample_fifo_used( fifo ) )
658 c = &audio_st->codec;
660 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
662 out_size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
664 // Write the compressed frame in the media file
665 if (av_write_frame(oc, audio_st->index, audio_outbuf, out_size) != 0)
666 fprintf(stderr, "Error while writing audio frame\n");
675 if ( mlt_deque_count( queue ) )
680 frame = mlt_deque_pop_front( queue );
681 frame_properties = mlt_frame_properties( frame );
683 if ( terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0 )
685 mlt_properties_set_int( properties, "running", 0 );
689 c = &video_st->codec;
691 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
698 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
702 for ( i = 0; i < height; i ++ )
704 p = input->data[ 0 ] + i * input->linesize[ 0 ];
713 img_convert( ( AVPicture * )output, PIX_FMT_YUV420P, ( AVPicture * )input, PIX_FMT_YUV422, width, height );
716 if (oc->oformat->flags & AVFMT_RAWPICTURE)
718 // raw video case. The API will change slightly in the near future for that
719 ret = av_write_frame(oc, video_st->index, (uint8_t *)output, sizeof(AVPicture));
724 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
726 // If zero size, it means the image was buffered
729 // write the compressed frame in the media file
730 // XXX: in case of B frames, the pts is not yet valid
731 ret = av_write_frame( oc, video_st->index, video_outbuf, out_size );
735 mlt_frame_close( frame );
748 close_video(oc, video_st);
750 close_audio(oc, audio_st);
752 // Write the trailer, if any
753 av_write_trailer(oc);
756 for(i = 0; i < oc->nb_streams; i++)
757 av_freep(&oc->streams[i]);
759 // Close the output file
760 if (!(fmt->flags & AVFMT_NOFILE))
763 // Clean up input and output frames
764 av_free( output->data[0] );
766 av_free( input->data[0] );
768 av_free( video_outbuf );
776 /** Close the consumer.
779 static void consumer_close( mlt_consumer this )
782 mlt_consumer_stop( this );
785 mlt_consumer_close( this );