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 library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library 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 GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, 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
36 // avformat header files
43 // This structure should be extended and made globally available in mlt
55 *sample_fifo, sample_fifo_s;
57 sample_fifo sample_fifo_init( int frequency, int channels )
59 sample_fifo this = calloc( 1, sizeof( sample_fifo_s ) );
60 this->frequency = frequency;
61 this->channels = channels;
65 // sample_fifo_clear and check are temporarily aborted (not working as intended)
67 void sample_fifo_clear( sample_fifo this, double time )
69 int words = ( float )( time - this->time ) * this->frequency * this->channels;
70 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) && this->used > words && words > 0 )
72 memmove( this->buffer, &this->buffer[ words ], ( this->used - words ) * sizeof( int16_t ) );
76 else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )this->time * 100 ) )
83 void sample_fifo_check( sample_fifo this, double time )
85 if ( this->used == 0 )
87 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) )
92 void sample_fifo_append( sample_fifo this, int16_t *samples, int count )
94 if ( ( this->size - this->used ) < count )
96 this->size += count * 5;
97 this->buffer = realloc( this->buffer, this->size * sizeof( int16_t ) );
100 memcpy( &this->buffer[ this->used ], samples, count * sizeof( int16_t ) );
104 int sample_fifo_used( sample_fifo this )
109 int sample_fifo_fetch( sample_fifo this, int16_t *samples, int count )
111 if ( count > this->used )
114 memcpy( samples, this->buffer, count * sizeof( int16_t ) );
116 memmove( this->buffer, &this->buffer[ count ], this->used * sizeof( int16_t ) );
118 this->time += ( double )count / this->channels / this->frequency;
123 void sample_fifo_close( sample_fifo this )
125 free( this->buffer );
129 // Forward references.
130 static int consumer_start( mlt_consumer this );
131 static int consumer_stop( mlt_consumer this );
132 static int consumer_is_stopped( mlt_consumer this );
133 static void *consumer_thread( void *arg );
134 static void consumer_close( mlt_consumer this );
136 /** Initialise the dv consumer.
139 mlt_consumer consumer_avformat_init( char *arg )
141 // Allocate the consumer
142 mlt_consumer this = mlt_consumer_new( );
144 // If memory allocated and initialises without error
147 // Get properties from the consumer
148 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
150 // Assign close callback
151 this->close = consumer_close;
153 // Interpret the argument
155 mlt_properties_set( properties, "target", arg );
157 // sample and frame queue
158 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
160 // Set avformat defaults (all lifted from ffmpeg.c)
161 mlt_properties_set_int( properties, "audio_bit_rate", 128000 );
162 mlt_properties_set_int( properties, "video_bit_rate", 200 * 1000 );
163 mlt_properties_set_int( properties, "video_bit_rate_tolerance", 4000 * 1000 );
164 mlt_properties_set_int( properties, "gop_size", 12 );
165 mlt_properties_set_int( properties, "b_frames", 0 );
166 mlt_properties_set_int( properties, "mb_decision", FF_MB_DECISION_SIMPLE );
167 mlt_properties_set_double( properties, "qscale", 1 );
168 mlt_properties_set_int( properties, "me_method", ME_EPZS );
169 mlt_properties_set_int( properties, "mb_cmp", FF_CMP_SAD );
170 mlt_properties_set_int( properties, "ildct_cmp", FF_CMP_VSAD );
171 mlt_properties_set_int( properties, "sub_cmp", FF_CMP_SAD );
172 mlt_properties_set_int( properties, "cmp", FF_CMP_SAD );
173 mlt_properties_set_int( properties, "pre_cmp", FF_CMP_SAD );
174 mlt_properties_set_int( properties, "pre_me", 0 );
175 mlt_properties_set_double( properties, "lumi_mask", 0 );
176 mlt_properties_set_double( properties, "dark_mask", 0 );
177 mlt_properties_set_double( properties, "scplx_mask", 0 );
178 mlt_properties_set_double( properties, "tcplx_mask", 0 );
179 mlt_properties_set_double( properties, "p_mask", 0 );
180 mlt_properties_set_int( properties, "qns", 0 );
181 mlt_properties_set_int( properties, "video_qmin", 2 );
182 mlt_properties_set_int( properties, "video_qmax", 31 );
183 mlt_properties_set_int( properties, "video_lmin", 2*FF_QP2LAMBDA );
184 mlt_properties_set_int( properties, "video_lmax", 31*FF_QP2LAMBDA );
185 mlt_properties_set_int( properties, "video_mb_qmin", 2 );
186 mlt_properties_set_int( properties, "video_mb_qmax", 31 );
187 mlt_properties_set_int( properties, "video_qdiff", 3 );
188 mlt_properties_set_double( properties, "video_qblur", 0.5 );
189 mlt_properties_set_double( properties, "video_qcomp", 0.5 );
190 mlt_properties_set_int( properties, "video_rc_max_rate", 0 );
191 mlt_properties_set_int( properties, "video_rc_min_rate", 0 );
192 mlt_properties_set_int( properties, "video_rc_buffer_size", 0 );
193 mlt_properties_set_double( properties, "video_rc_buffer_aggressivity", 1.0 );
194 mlt_properties_set_double( properties, "video_rc_initial_cplx", 0 );
195 mlt_properties_set_double( properties, "video_i_qfactor", 1.25 );
196 mlt_properties_set_double( properties, "video_b_qfactor", 1.25 );
197 mlt_properties_set_double( properties, "video_i_qoffset", -0.8 );
198 mlt_properties_set_double( properties, "video_b_qoffset", 0 );
199 mlt_properties_set_int( properties, "video_intra_quant_bias", FF_DEFAULT_QUANT_BIAS );
200 mlt_properties_set_int( properties, "video_inter_quant_bias", FF_DEFAULT_QUANT_BIAS );
201 mlt_properties_set_int( properties, "dct_algo", 0 );
202 mlt_properties_set_int( properties, "idct_algo", 0 );
203 mlt_properties_set_int( properties, "me_threshold", 0 );
204 mlt_properties_set_int( properties, "mb_threshold", 0 );
205 mlt_properties_set_int( properties, "intra_dc_precision", 0 );
206 mlt_properties_set_int( properties, "strict", 0 );
207 mlt_properties_set_int( properties, "error_rate", 0 );
208 mlt_properties_set_int( properties, "noise_reduction", 0 );
209 mlt_properties_set_int( properties, "sc_threshold", 0 );
210 mlt_properties_set_int( properties, "me_range", 0 );
211 mlt_properties_set_int( properties, "coder", 0 );
212 mlt_properties_set_int( properties, "context", 0 );
213 mlt_properties_set_int( properties, "predictor", 0 );
214 mlt_properties_set_int( properties, "ildct", 0 );
215 mlt_properties_set_int( properties, "ilme", 0 );
217 // Ensure termination at end of the stream
218 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
220 // Set up start/stop/terminated callbacks
221 this->start = consumer_start;
222 this->stop = consumer_stop;
223 this->is_stopped = consumer_is_stopped;
230 /** Start the consumer.
233 static int consumer_start( mlt_consumer this )
235 // Get the properties
236 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
238 // Check that we're not already running
239 if ( !mlt_properties_get_int( properties, "running" ) )
242 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
244 // Get the width and height
245 int width = mlt_properties_get_int( properties, "width" );
246 int height = mlt_properties_get_int( properties, "height" );
248 // Obtain the size property
249 char *size = mlt_properties_get( properties, "size" );
255 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
262 fprintf( stderr, "consumer_avformat: Invalid size property %s - ignoring.\n", size );
266 // Now ensure we honour the multiple of two requested by libavformat
267 mlt_properties_set_int( properties, "width", ( width / 2 ) * 2 );
268 mlt_properties_set_int( properties, "height", ( height / 2 ) * 2 );
270 // Assign the thread to properties
271 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
273 // Set the running state
274 mlt_properties_set_int( properties, "running", 1 );
277 pthread_create( thread, NULL, consumer_thread, this );
282 /** Stop the consumer.
285 static int consumer_stop( mlt_consumer this )
287 // Get the properties
288 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
290 // Check that we're running
291 if ( mlt_properties_get_int( properties, "running" ) )
294 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
297 mlt_properties_set_int( properties, "running", 0 );
299 // Wait for termination
300 pthread_join( *thread, NULL );
306 /** Determine if the consumer is stopped.
309 static int consumer_is_stopped( mlt_consumer this )
311 // Get the properties
312 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
313 return !mlt_properties_get_int( properties, "running" );
316 /** Add an audio output stream
319 static AVStream *add_audio_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
321 // Get the properties
322 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
324 // Create a new stream
325 AVStream *st = av_new_stream( oc, 1 );
327 // If created, then initialise from properties
330 AVCodecContext *c = st->codec;
331 c->codec_id = codec_id;
332 c->codec_type = CODEC_TYPE_AUDIO;
334 // Put sample parameters
335 c->bit_rate = mlt_properties_get_int( properties, "audio_bit_rate" );
336 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
337 c->channels = mlt_properties_get_int( properties, "channels" );
339 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
340 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
342 // Allow the user to override the audio fourcc
343 if ( mlt_properties_get( properties, "afourcc" ) )
346 char *arg = mlt_properties_get( properties, "afourcc" );
347 int tag = strtol( arg, &tail, 0);
349 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
355 fprintf( stderr, "Could not allocate a stream for audio\n" );
361 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
363 // We will return the audio input size from here
364 int audio_input_frame_size = 0;
367 AVCodecContext *c = st->codec;
370 AVCodec *codec = avcodec_find_encoder( c->codec_id );
372 // Continue if codec found and we can open it
373 if ( codec != NULL && avcodec_open(c, codec) >= 0 )
375 // ugly hack for PCM codecs (will be removed ASAP with new PCM
376 // support to compute the input frame size in samples
377 if ( c->frame_size <= 1 )
379 audio_input_frame_size = audio_outbuf_size / c->channels;
380 switch(st->codec->codec_id)
382 case CODEC_ID_PCM_S16LE:
383 case CODEC_ID_PCM_S16BE:
384 case CODEC_ID_PCM_U16LE:
385 case CODEC_ID_PCM_U16BE:
386 audio_input_frame_size >>= 1;
394 audio_input_frame_size = c->frame_size;
397 // Some formats want stream headers to be seperate (hmm)
398 if( !strcmp( oc->oformat->name, "mp4" ) ||
399 !strcmp( oc->oformat->name, "mov" ) ||
400 !strcmp( oc->oformat->name, "3gp" ) )
401 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
405 fprintf( stderr, "Unable to encode audio - disabling audio output.\n" );
408 return audio_input_frame_size;
411 static void close_audio( AVFormatContext *oc, AVStream *st )
413 avcodec_close( st->codec );
416 /** Add a video output stream
419 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
421 // Get the properties
422 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
424 // Create a new stream
425 AVStream *st = av_new_stream( oc, 0 );
429 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
430 double ar = mlt_properties_get_double( properties, "display_ratio" );
431 AVCodecContext *c = st->codec;
432 c->codec_id = codec_id;
433 c->codec_type = CODEC_TYPE_VIDEO;
435 // put sample parameters
436 c->bit_rate = mlt_properties_get_int( properties, "video_bit_rate" );
437 c->bit_rate_tolerance = mlt_properties_get_int( properties, "video_bit_rate_tolerance" );
438 c->width = mlt_properties_get_int( properties, "width" );
439 c->height = mlt_properties_get_int( properties, "height" );
440 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
441 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
442 c->gop_size = mlt_properties_get_int( properties, "gop_size" );
443 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
445 if ( mlt_properties_get_int( properties, "b_frames" ) )
447 c->max_b_frames = mlt_properties_get_int( properties, "b_frames" );
448 c->b_frame_strategy = 0;
449 c->b_quant_factor = 2.0;
452 c->mb_decision = mlt_properties_get_int( properties, "mb_decision" );
453 c->sample_aspect_ratio = av_d2q( ar * c->height / c->width , 255);
454 c->mb_cmp = mlt_properties_get_int( properties, "mb_cmp" );
455 c->ildct_cmp = mlt_properties_get_int( properties, "ildct_cmp" );
456 c->me_sub_cmp = mlt_properties_get_int( properties, "sub_cmp" );
457 c->me_cmp = mlt_properties_get_int( properties, "cmp" );
458 c->me_pre_cmp = mlt_properties_get_int( properties, "pre_cmp" );
459 c->pre_me = mlt_properties_get_int( properties, "pre_me" );
460 c->lumi_masking = mlt_properties_get_double( properties, "lumi_mask" );
461 c->dark_masking = mlt_properties_get_double( properties, "dark_mask" );
462 c->spatial_cplx_masking = mlt_properties_get_double( properties, "scplx_mask" );
463 c->temporal_cplx_masking = mlt_properties_get_double( properties, "tcplx_mask" );
464 c->p_masking = mlt_properties_get_double( properties, "p_mask" );
465 c->quantizer_noise_shaping= mlt_properties_get_int( properties, "qns" );
466 c->qmin = mlt_properties_get_int( properties, "video_qmin" );
467 c->qmax = mlt_properties_get_int( properties, "video_qmax" );
468 c->lmin = mlt_properties_get_int( properties, "video_lmin" );
469 c->lmax = mlt_properties_get_int( properties, "video_lmax" );
470 c->mb_qmin = mlt_properties_get_int( properties, "video_mb_qmin" );
471 c->mb_qmax = mlt_properties_get_int( properties, "video_mb_qmax" );
472 c->max_qdiff = mlt_properties_get_int( properties, "video_qdiff" );
473 c->qblur = mlt_properties_get_double( properties, "video_qblur" );
474 c->qcompress = mlt_properties_get_double( properties, "video_qcomp" );
476 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
478 c->flags |= CODEC_FLAG_QSCALE;
479 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
482 // Allow the user to override the video fourcc
483 if ( mlt_properties_get( properties, "vfourcc" ) )
486 const char *arg = mlt_properties_get( properties, "vfourcc" );
487 int tag = strtol( arg, &tail, 0);
489 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
493 // Some formats want stream headers to be seperate
494 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
495 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
497 c->rc_max_rate = mlt_properties_get_int( properties, "video_rc_max_rate" );
498 c->rc_min_rate = mlt_properties_get_int( properties, "video_rc_min_rate" );
499 c->rc_buffer_size = mlt_properties_get_int( properties, "video_rc_buffer_size" );
500 c->rc_buffer_aggressivity= mlt_properties_get_double( properties, "video_rc_buffer_aggressivity" );
501 c->rc_initial_cplx= mlt_properties_get_double( properties, "video_rc_initial_cplx" );
502 c->i_quant_factor = mlt_properties_get_double( properties, "video_i_qfactor" );
503 c->b_quant_factor = mlt_properties_get_double( properties, "video_b_qfactor" );
504 c->i_quant_offset = mlt_properties_get_double( properties, "video_i_qoffset" );
505 c->b_quant_offset = mlt_properties_get_double( properties, "video_b_qoffset" );
506 c->intra_quant_bias = mlt_properties_get_int( properties, "video_intra_quant_bias" );
507 c->inter_quant_bias = mlt_properties_get_int( properties, "video_inter_quant_bias" );
508 c->dct_algo = mlt_properties_get_int( properties, "dct_algo" );
509 c->idct_algo = mlt_properties_get_int( properties, "idct_algo" );
510 c->me_threshold= mlt_properties_get_int( properties, "me_threshold" );
511 c->mb_threshold= mlt_properties_get_int( properties, "mb_threshold" );
512 c->intra_dc_precision= mlt_properties_get_int( properties, "intra_dc_precision" );
513 c->strict_std_compliance = mlt_properties_get_int( properties, "strict" );
514 c->error_rate = mlt_properties_get_int( properties, "error_rate" );
515 c->noise_reduction= mlt_properties_get_int( properties, "noise_reduction" );
516 c->scenechange_threshold= mlt_properties_get_int( properties, "sc_threshold" );
517 c->me_range = mlt_properties_get_int( properties, "me_range" );
518 c->coder_type= mlt_properties_get_int( properties, "coder" );
519 c->context_model= mlt_properties_get_int( properties, "context" );
520 c->prediction_method= mlt_properties_get_int( properties, "predictor" );
521 c->me_method = mlt_properties_get_int( properties, "me_method" );
522 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
523 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
525 if ( mlt_properties_get_int( properties, "ildct" ) )
526 c->flags |= CODEC_FLAG_INTERLACED_DCT;
527 if ( mlt_properties_get_int( properties, "ilme" ) )
528 c->flags |= CODEC_FLAG_INTERLACED_ME;
533 fprintf( stderr, "Could not allocate a stream for video\n" );
539 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
542 AVFrame *picture = avcodec_alloc_frame();
544 // Determine size of the
545 int size = avpicture_get_size(pix_fmt, width, height);
547 // Allocate the picture buf
548 uint8_t *picture_buf = av_malloc(size);
550 // If we have both, then fill the image
551 if ( picture != NULL && picture_buf != NULL )
553 // Fill the frame with the allocated buffer
554 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
558 // Something failed - clean up what we can
560 av_free( picture_buf );
567 static int open_video(AVFormatContext *oc, AVStream *st)
570 AVCodecContext *video_enc = st->codec;
572 // find the video encoder
573 AVCodec *codec = avcodec_find_encoder( video_enc->codec_id );
575 if( codec && codec->pix_fmts )
577 const enum PixelFormat *p = codec->pix_fmts;
580 if( *p == video_enc->pix_fmt )
584 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
587 // Open the codec safely
588 return codec != NULL && avcodec_open( video_enc, codec ) >= 0;
591 void close_video(AVFormatContext *oc, AVStream *st)
593 avcodec_close(st->codec);
596 static inline long time_difference( struct timeval *time1 )
598 struct timeval time2;
599 gettimeofday( &time2, NULL );
600 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
603 /** The main thread - the argument is simply the consumer.
606 static void *consumer_thread( void *arg )
608 // Map the argument to the object
609 mlt_consumer this = arg;
611 // Get the properties
612 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
614 // Get the terminate on pause property
615 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
618 // Determine if feed is slow (for realtime stuff)
619 int real_time_output = mlt_properties_get_int( properties, "real_time" );
624 // Get the frame rate
625 int fps = mlt_properties_get_double( properties, "fps" );
627 // Get width and height
628 int width = mlt_properties_get_int( properties, "width" );
629 int height = mlt_properties_get_int( properties, "height" );
630 int img_width = width;
631 int img_height = height;
633 // Get default audio properties
634 mlt_audio_format aud_fmt = mlt_audio_pcm;
635 int channels = mlt_properties_get_int( properties, "channels" );
636 int frequency = mlt_properties_get_int( properties, "frequency" );
640 // AVFormat audio buffer and frame size
641 int audio_outbuf_size = 10000;
642 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
643 int audio_input_frame_size = 0;
645 // AVFormat video buffer and frame count
647 int video_outbuf_size = ( 1024 * 1024 );
648 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
650 // Used for the frame properties
651 mlt_frame frame = NULL;
652 mlt_properties frame_properties = NULL;
655 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
656 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
658 // Need two av pictures for converting
659 AVFrame *output = NULL;
660 AVFrame *input = alloc_picture( PIX_FMT_YUV422, width, height );
662 // For receiving images from an mlt_frame
664 mlt_image_format img_fmt = mlt_image_yuv422;
666 // For receiving audio samples back from the fifo
667 int16_t *buffer = av_malloc( 48000 * 2 );
670 // Allocate the context
671 AVFormatContext *oc = av_alloc_format_context( );
674 AVStream *audio_st = NULL;
675 AVStream *video_st = NULL;
678 double audio_pts = 0;
679 double video_pts = 0;
686 long int total_time = 0;
688 // Determine the format
689 AVOutputFormat *fmt = NULL;
690 char *filename = mlt_properties_get( properties, "target" );
691 char *format = mlt_properties_get( properties, "format" );
692 char *vcodec = mlt_properties_get( properties, "vcodec" );
693 char *acodec = mlt_properties_get( properties, "acodec" );
695 // Used to store and override codec ids
699 // Check for user selected format first
700 if ( format != NULL )
701 fmt = guess_format( format, NULL, NULL );
703 // Otherwise check on the filename
704 if ( fmt == NULL && filename != NULL )
705 fmt = guess_format( NULL, filename, NULL );
707 // Otherwise default to mpeg
709 fmt = guess_format( "mpeg", NULL, NULL );
711 // We need a filename - default to stdout?
712 if ( filename == NULL || !strcmp( filename, "" ) )
715 // Get the codec ids selected
716 audio_codec_id = fmt->audio_codec;
717 video_codec_id = fmt->video_codec;
719 // Check for audio codec overides
720 if ( acodec != NULL )
722 AVCodec *p = first_avcodec;
725 if ( !strcmp( p->name, acodec ) && p->type == CODEC_TYPE_AUDIO )
730 audio_codec_id = p->id;
732 fprintf( stderr, "consumer_avcodec: audio codec %s unrecognised - ignoring\n", acodec );
735 // Check for video codec overides
736 if ( vcodec != NULL )
738 AVCodec *p = first_avcodec;
741 if ( !strcmp( p->name, vcodec ) && p->type == CODEC_TYPE_VIDEO )
746 video_codec_id = p->id;
748 fprintf( stderr, "consumer_avcodec: video codec %s unrecognised - ignoring\n", vcodec );
751 // Update the output context
757 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
758 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
760 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
761 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
763 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
764 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
766 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
767 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
769 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
770 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
772 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
773 if (metavalue != 0) oc->year = metavalue;
775 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
776 if (metavalue != 0) oc->track = metavalue;
779 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
781 // Add audio and video streams
782 if ( fmt->video_codec != CODEC_ID_NONE )
783 video_st = add_video_stream( this, oc, video_codec_id );
784 if ( fmt->audio_codec != CODEC_ID_NONE )
785 audio_st = add_audio_stream( this, oc, audio_codec_id );
787 // Set the parameters (even though we have none...)
788 if ( av_set_parameters(oc, NULL) >= 0 )
790 if ( video_st && !open_video( oc, video_st ) )
793 audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
795 // Open the output file, if needed
796 if ( !( fmt->flags & AVFMT_NOFILE ) )
798 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0)
800 fprintf(stderr, "Could not open '%s'\n", filename);
801 mlt_properties_set_int( properties, "running", 0 );
805 // Write the stream header, if any
806 if ( mlt_properties_get_int( properties, "running" ) )
807 av_write_header( oc );
811 fprintf(stderr, "Invalid output format parameters\n");
812 mlt_properties_set_int( properties, "running", 0 );
817 output = alloc_picture( video_st->codec->pix_fmt, width, height );
819 // Last check - need at least one stream
820 if ( audio_st == NULL && video_st == NULL )
821 mlt_properties_set_int( properties, "running", 0 );
823 // Get the starting time (can ignore the times above)
824 gettimeofday( &ante, NULL );
826 // Loop while running
827 while( mlt_properties_get_int( properties, "running" ) && !terminated )
830 frame = mlt_consumer_rt_frame( this );
832 // Check that we have a frame to work with
835 // Increment frames despatched
838 // Default audio args
839 frame_properties = MLT_FRAME_PROPERTIES( frame );
841 // Check for the terminated condition
842 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
844 // Get audio and append to the fifo
845 if ( !terminated && audio_st )
847 samples = mlt_sample_calculator( fps, frequency, count ++ );
848 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
850 // Create the fifo if we don't have one
853 fifo = sample_fifo_init( frequency, channels );
854 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
857 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
858 memset( pcm, 0, samples * channels * 2 );
860 // Append the samples
861 sample_fifo_append( fifo, pcm, samples * channels );
862 total_time += ( samples * 1000000 ) / frequency;
866 if ( !terminated && video_st )
867 mlt_deque_push_back( queue, frame );
869 mlt_frame_close( frame );
872 // While we have stuff to process, process...
876 audio_pts = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;
881 video_pts = (double)video_st->pts.val * video_st->time_base.num / video_st->time_base.den;
885 // Write interleaved audio and video frames
886 if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
888 if ( channels * audio_input_frame_size < sample_fifo_used( fifo ) )
892 av_init_packet( &pkt );
896 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
898 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
899 // Write the compressed frame in the media file
900 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
901 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
902 pkt.flags |= PKT_FLAG_KEY;
903 pkt.stream_index= audio_st->index;
904 pkt.data= audio_outbuf;
907 if ( av_interleaved_write_frame( oc, &pkt ) != 0)
908 fprintf(stderr, "Error while writing audio frame\n");
910 audio_pts += c->frame_size;
919 if ( mlt_deque_count( queue ) )
924 frame = mlt_deque_pop_front( queue );
925 frame_properties = MLT_FRAME_PROPERTIES( frame );
929 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
936 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
938 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
942 // Convert the mlt frame to an AVPicture
943 for ( i = 0; i < height; i ++ )
945 p = input->data[ 0 ] + i * input->linesize[ 0 ];
954 // Do the colour space conversion
956 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUV422,
957 width, height, video_st->codec->pix_fmt, SWS_FAST_BILINEAR, NULL, NULL, NULL);
958 sws_scale( context, input->data, input->linesize, 0, height,
959 output->data, output->linesize);
960 sws_freeContext( context );
962 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUV422, width, height );
965 // Apply the alpha if applicable
966 if ( video_st->codec->pix_fmt == PIX_FMT_RGBA32 )
968 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
971 for ( i = 0; i < height; i ++ )
973 n = ( width + 7 ) / 8;
974 p = output->data[ 0 ] + i * output->linesize[ 0 ];
982 case 0: do { *p = *alpha++; p += 4;
983 case 7: *p = *alpha++; p += 4;
984 case 6: *p = *alpha++; p += 4;
985 case 5: *p = *alpha++; p += 4;
986 case 4: *p = *alpha++; p += 4;
987 case 3: *p = *alpha++; p += 4;
988 case 2: *p = *alpha++; p += 4;
989 case 1: *p = *alpha++; p += 4;
997 if (oc->oformat->flags & AVFMT_RAWPICTURE)
999 // raw video case. The API will change slightly in the near future for that
1001 av_init_packet(&pkt);
1003 pkt.flags |= PKT_FLAG_KEY;
1004 pkt.stream_index= video_st->index;
1005 pkt.data= (uint8_t *)output;
1006 pkt.size= sizeof(AVPicture);
1008 ret = av_write_frame(oc, &pkt);
1009 video_pts += c->frame_size;
1014 output->quality = video_st->quality;
1016 // Set frame interlace hints
1017 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1018 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1021 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1023 // If zero size, it means the image was buffered
1027 av_init_packet( &pkt );
1029 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1030 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1031 if( c->coded_frame && c->coded_frame->key_frame )
1032 pkt.flags |= PKT_FLAG_KEY;
1033 pkt.stream_index= video_st->index;
1034 pkt.data= video_outbuf;
1037 // write the compressed frame in the media file
1038 ret = av_interleaved_write_frame(oc, &pkt);
1039 video_pts += c->frame_size;
1043 fprintf( stderr, "Error with video encode\n" );
1047 mlt_frame_close( frame );
1056 if ( real_time_output && frames % 12 == 0 )
1058 long passed = time_difference( &ante );
1061 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1064 if ( passed < total_time )
1066 long total = ( total_time - passed );
1067 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1068 nanosleep( &t, NULL );
1075 close_video(oc, video_st);
1077 close_audio(oc, audio_st);
1079 // Write the trailer, if any
1080 av_write_trailer(oc);
1083 for(i = 0; i < oc->nb_streams; i++)
1084 av_freep(&oc->streams[i]);
1086 // Close the output file
1087 if (!(fmt->flags & AVFMT_NOFILE))
1088 url_fclose(&oc->pb);
1090 // Clean up input and output frames
1092 av_free( output->data[0] );
1094 av_free( input->data[0] );
1096 av_free( video_outbuf );
1102 // Just in case we terminated on pause
1103 mlt_properties_set_int( properties, "running", 0 );
1105 mlt_consumer_stopped( this );
1110 /** Close the consumer.
1113 static void consumer_close( mlt_consumer this )
1115 // Stop the consumer
1116 mlt_consumer_stop( this );
1119 mlt_consumer_close( this );