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>
5 * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #include <framework/mlt_consumer.h>
24 #include <framework/mlt_frame.h>
26 // System header files
35 // 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( mlt_profile profile
, char *arg
)
141 // Allocate the consumer
142 mlt_consumer
this = mlt_consumer_new( profile
);
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 // Audio options not fully handled by AVOptions
161 #define QSCALE_NONE (-99999)
162 mlt_properties_set_int( properties
, "aq", QSCALE_NONE
);
164 // Video options not fully handled by AVOptions
165 mlt_properties_set_int( properties
, "dc", 8 );
167 // Muxer options not fully handled by AVOptions
168 mlt_properties_set_double( properties
, "muxdelay", 0.7 );
169 mlt_properties_set_double( properties
, "muxpreload", 0.5 );
171 // Ensure termination at end of the stream
172 mlt_properties_set_int( properties
, "terminate_on_pause", 1 );
174 // Default to separate processing threads for producer and consumer with no frame dropping!
175 mlt_properties_set_int( properties
, "real_time", -1 );
177 // Set up start/stop/terminated callbacks
178 this->start
= consumer_start
;
179 this->stop
= consumer_stop
;
180 this->is_stopped
= consumer_is_stopped
;
187 /** Start the consumer.
190 static int consumer_start( mlt_consumer
this )
192 // Get the properties
193 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
195 // Check that we're not already running
196 if ( !mlt_properties_get_int( properties
, "running" ) )
199 pthread_t
*thread
= calloc( 1, sizeof( pthread_t
) );
201 // Get the width and height
202 int width
= mlt_properties_get_int( properties
, "width" );
203 int height
= mlt_properties_get_int( properties
, "height" );
205 // Obtain the size property
206 char *size
= mlt_properties_get( properties
, "s" );
212 if ( sscanf( size
, "%dx%d", &tw
, &th
) == 2 && tw
> 0 && th
> 0 )
219 fprintf( stderr
, "%s: Invalid size property %s - ignoring.\n", __FILE__
, size
);
223 // Now ensure we honour the multiple of two requested by libavformat
224 mlt_properties_set_int( properties
, "width", ( width
/ 2 ) * 2 );
225 mlt_properties_set_int( properties
, "height", ( height
/ 2 ) * 2 );
227 // Apply AVOptions that are synonyms for standard mlt_consumer options
228 if ( mlt_properties_get( properties
, "ac" ) )
229 mlt_properties_set_int( properties
, "channels", mlt_properties_get_int( properties
, "ac" ) );
230 if ( mlt_properties_get( properties
, "ar" ) )
231 mlt_properties_set_int( properties
, "frequency", mlt_properties_get_int( properties
, "ar" ) );
233 // Assign the thread to properties
234 mlt_properties_set_data( properties
, "thread", thread
, sizeof( pthread_t
), free
, NULL
);
236 // Set the running state
237 mlt_properties_set_int( properties
, "running", 1 );
240 pthread_create( thread
, NULL
, consumer_thread
, this );
245 /** Stop the consumer.
248 static int consumer_stop( mlt_consumer
this )
250 // Get the properties
251 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
253 // Check that we're running
254 if ( mlt_properties_get_int( properties
, "running" ) )
257 pthread_t
*thread
= mlt_properties_get_data( properties
, "thread", NULL
);
260 mlt_properties_set_int( properties
, "running", 0 );
262 // Wait for termination
263 pthread_join( *thread
, NULL
);
269 /** Determine if the consumer is stopped.
272 static int consumer_is_stopped( mlt_consumer
this )
274 // Get the properties
275 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
276 return !mlt_properties_get_int( properties
, "running" );
279 /** Process properties as AVOptions and apply to AV context obj
282 static void apply_properties( void *obj
, mlt_properties properties
, int flags
)
285 int count
= mlt_properties_count( properties
);
286 for ( i
= 0; i
< count
; i
++ )
288 const char *opt_name
= mlt_properties_get_name( properties
, i
);
289 const AVOption
*opt
= av_find_opt( obj
, opt_name
, NULL
, flags
, flags
);
291 av_set_string( obj
, opt_name
, mlt_properties_get( properties
, opt_name
) );
295 /** Add an audio output stream
298 static AVStream
*add_audio_stream( mlt_consumer
this, AVFormatContext
*oc
, int codec_id
)
300 // Get the properties
301 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
303 // Create a new stream
304 AVStream
*st
= av_new_stream( oc
, 1 );
306 // If created, then initialise from properties
309 AVCodecContext
*c
= st
->codec
;
311 // Establish defaults from AVOptions
312 avcodec_get_context_defaults2( c
, CODEC_TYPE_AUDIO
);
314 c
->codec_id
= codec_id
;
315 c
->codec_type
= CODEC_TYPE_AUDIO
;
317 // Setup multi-threading
318 int thread_count
= mlt_properties_get_int( properties
, "threads" );
319 if ( thread_count
== 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
320 thread_count
= atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
321 if ( thread_count
> 1 )
322 avcodec_thread_init( c
, thread_count
);
324 if (oc
->oformat
->flags
& AVFMT_GLOBALHEADER
)
325 c
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
327 // Allow the user to override the audio fourcc
328 if ( mlt_properties_get( properties
, "atag" ) )
331 char *arg
= mlt_properties_get( properties
, "atag" );
332 int tag
= strtol( arg
, &tail
, 0);
334 tag
= arg
[ 0 ] + ( arg
[ 1 ] << 8 ) + ( arg
[ 2 ] << 16 ) + ( arg
[ 3 ] << 24 );
338 // Process properties as AVOptions
339 apply_properties( c
, properties
, AV_OPT_FLAG_AUDIO_PARAM
| AV_OPT_FLAG_ENCODING_PARAM
);
341 int audio_qscale
= mlt_properties_get_int( properties
, "aq" );
342 if ( audio_qscale
> QSCALE_NONE
)
344 c
->flags
|= CODEC_FLAG_QSCALE
;
345 c
->global_quality
= st
->quality
= FF_QP2LAMBDA
* audio_qscale
;
348 // Set parameters controlled by MLT
349 c
->sample_rate
= mlt_properties_get_int( properties
, "frequency" );
350 c
->channels
= mlt_properties_get_int( properties
, "channels" );
352 if ( mlt_properties_get( properties
, "alang" ) != NULL
)
353 strncpy( st
->language
, mlt_properties_get( properties
, "alang" ), sizeof( st
->language
) );
357 fprintf( stderr
, "%s: Could not allocate a stream for audio\n", __FILE__
);
363 static int open_audio( AVFormatContext
*oc
, AVStream
*st
, int audio_outbuf_size
)
365 // We will return the audio input size from here
366 int audio_input_frame_size
= 0;
369 AVCodecContext
*c
= st
->codec
;
372 AVCodec
*codec
= avcodec_find_encoder( c
->codec_id
);
374 // Continue if codec found and we can open it
375 if ( codec
!= NULL
&& avcodec_open( c
, codec
) >= 0 )
377 // ugly hack for PCM codecs (will be removed ASAP with new PCM
378 // support to compute the input frame size in samples
379 if ( c
->frame_size
<= 1 )
381 audio_input_frame_size
= audio_outbuf_size
/ c
->channels
;
382 switch(st
->codec
->codec_id
)
384 case CODEC_ID_PCM_S16LE
:
385 case CODEC_ID_PCM_S16BE
:
386 case CODEC_ID_PCM_U16LE
:
387 case CODEC_ID_PCM_U16BE
:
388 audio_input_frame_size
>>= 1;
396 audio_input_frame_size
= c
->frame_size
;
399 // Some formats want stream headers to be seperate (hmm)
400 if( !strcmp( oc
->oformat
->name
, "mp4" ) ||
401 !strcmp( oc
->oformat
->name
, "mov" ) ||
402 !strcmp( oc
->oformat
->name
, "3gp" ) )
403 c
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
407 fprintf( stderr
, "%s: Unable to encode audio - disabling audio output.\n", __FILE__
);
410 return audio_input_frame_size
;
413 static void close_audio( AVFormatContext
*oc
, AVStream
*st
)
415 avcodec_close( st
->codec
);
418 /** Add a video output stream
421 static AVStream
*add_video_stream( mlt_consumer
this, AVFormatContext
*oc
, int codec_id
)
423 // Get the properties
424 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
426 // Create a new stream
427 AVStream
*st
= av_new_stream( oc
, 0 );
431 char *pix_fmt
= mlt_properties_get( properties
, "pix_fmt" );
432 AVCodecContext
*c
= st
->codec
;
434 // Establish defaults from AVOptions
435 avcodec_get_context_defaults2( c
, CODEC_TYPE_VIDEO
);
437 c
->codec_id
= codec_id
;
438 c
->codec_type
= CODEC_TYPE_VIDEO
;
440 // Setup multi-threading
441 int thread_count
= mlt_properties_get_int( properties
, "threads" );
442 if ( thread_count
== 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
443 thread_count
= atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
444 if ( thread_count
> 1 )
445 avcodec_thread_init( c
, thread_count
);
447 // Process properties as AVOptions
448 apply_properties( c
, properties
, AV_OPT_FLAG_VIDEO_PARAM
| AV_OPT_FLAG_ENCODING_PARAM
);
450 // Set options controlled by MLT
451 c
->width
= mlt_properties_get_int( properties
, "width" );
452 c
->height
= mlt_properties_get_int( properties
, "height" );
453 c
->time_base
.num
= mlt_properties_get_int( properties
, "frame_rate_den" );
454 c
->time_base
.den
= mlt_properties_get_int( properties
, "frame_rate_num" );
455 c
->pix_fmt
= pix_fmt ?
avcodec_get_pix_fmt( pix_fmt
) : PIX_FMT_YUV420P
;
457 if ( codec_id
== CODEC_ID_DVVIDEO
)
459 // Compensate for FFmpeg's notion of DV aspect ratios, which are
460 // based upon a width of 704. Since we do not have a normaliser
461 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
462 // we just coerce the values to facilitate a passive behaviour through
463 // the rescale normaliser when using equivalent producers and consumers.
464 // = display_aspect / (width * height)
465 double ar
= mlt_properties_get_double( properties
, "aspect_ratio" );
466 if ( ar
== 8.0/9.0 ) // 4:3 NTSC
468 c
->sample_aspect_ratio
.num
= 10;
469 c
->sample_aspect_ratio
.den
= 11;
471 else if ( ar
== 16.0/15.0 ) // 4:3 PAL
473 c
->sample_aspect_ratio
.num
= 159;
474 c
->sample_aspect_ratio
.den
= 54;
476 else if ( ar
== 32.0/27.0 ) // 16:9 NTSC
478 c
->sample_aspect_ratio
.num
= 40;
479 c
->sample_aspect_ratio
.den
= 33;
483 c
->sample_aspect_ratio
.num
= 118;
484 c
->sample_aspect_ratio
.den
= 81;
487 else if ( mlt_properties_get( properties
, "aspect" ) )
489 double ar
= mlt_properties_get_double( properties
, "aspect" );
490 c
->sample_aspect_ratio
= av_d2q( ar
* c
->height
/ c
->width
, 255);
494 c
->sample_aspect_ratio
.num
= mlt_properties_get_int( properties
, "sample_aspect_num" );
495 c
->sample_aspect_ratio
.den
= mlt_properties_get_int( properties
, "sample_aspect_den" );
498 if ( mlt_properties_get_double( properties
, "qscale" ) > 0 )
500 c
->flags
|= CODEC_FLAG_QSCALE
;
501 st
->quality
= FF_QP2LAMBDA
* mlt_properties_get_double( properties
, "qscale" );
504 // Allow the user to override the video fourcc
505 if ( mlt_properties_get( properties
, "vtag" ) )
508 const char *arg
= mlt_properties_get( properties
, "vtag" );
509 int tag
= strtol( arg
, &tail
, 0);
511 tag
= arg
[ 0 ] + ( arg
[ 1 ] << 8 ) + ( arg
[ 2 ] << 16 ) + ( arg
[ 3 ] << 24 );
515 // Some formats want stream headers to be seperate
516 if ( oc
->oformat
->flags
& AVFMT_GLOBALHEADER
)
517 c
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
519 // Translate these standard mlt consumer properties to ffmpeg
520 if ( mlt_properties_get_int( properties
, "progressive" ) == 0 &&
521 mlt_properties_get_int( properties
, "deinterlace" ) == 0 )
523 if ( mlt_properties_get_int( properties
, "ildct" ) )
524 c
->flags
|= CODEC_FLAG_INTERLACED_DCT
;
525 if ( mlt_properties_get_int( properties
, "ilme" ) )
526 c
->flags
|= CODEC_FLAG_INTERLACED_ME
;
529 // parse the ratecontrol override string
531 char *rc_override
= mlt_properties_get( properties
, "rc_override" );
532 for ( i
= 0; rc_override
; i
++ )
535 int e
= sscanf( rc_override
, "%d,%d,%d", &start
, &end
, &q
);
537 fprintf( stderr
, "%s: Error parsing rc_override\n", __FILE__
);
538 c
->rc_override
= av_realloc( c
->rc_override
, sizeof( RcOverride
) * ( i
+ 1 ) );
539 c
->rc_override
[i
].start_frame
= start
;
540 c
->rc_override
[i
].end_frame
= end
;
543 c
->rc_override
[i
].qscale
= q
;
544 c
->rc_override
[i
].quality_factor
= 1.0;
548 c
->rc_override
[i
].qscale
= 0;
549 c
->rc_override
[i
].quality_factor
= -q
/ 100.0;
551 rc_override
= strchr( rc_override
, '/' );
555 c
->rc_override_count
= i
;
556 if ( !c
->rc_initial_buffer_occupancy
)
557 c
->rc_initial_buffer_occupancy
= c
->rc_buffer_size
* 3/4;
558 c
->intra_dc_precision
= mlt_properties_get_int( properties
, "dc" ) - 8;
561 i
= mlt_properties_get_int( properties
, "pass" );
563 c
->flags
|= CODEC_FLAG_PASS1
;
565 c
->flags
|= CODEC_FLAG_PASS2
;
566 if ( c
->flags
& ( CODEC_FLAG_PASS1
| CODEC_FLAG_PASS2
) )
568 char logfilename
[1024];
573 snprintf( logfilename
, sizeof(logfilename
), "%s_2pass.log",
574 mlt_properties_get( properties
, "passlogfile" ) ?
mlt_properties_get( properties
, "passlogfile" ) : mlt_properties_get( properties
, "target" ) );
575 if ( c
->flags
& CODEC_FLAG_PASS1
)
577 f
= fopen( logfilename
, "w" );
579 perror( logfilename
);
581 mlt_properties_set_data( properties
, "_logfile", f
, 0, ( mlt_destructor
)fclose
, NULL
);
585 /* read the log file */
586 f
= fopen( logfilename
, "r" );
593 fseek( f
, 0, SEEK_END
);
595 fseek( f
, 0, SEEK_SET
);
596 logbuffer
= av_malloc( size
+ 1 );
598 fprintf( stderr
, "%s: Could not allocate log buffer\n", __FILE__
);
601 size
= fread( logbuffer
, 1, size
, f
);
603 logbuffer
[size
] = '\0';
604 c
->stats_in
= logbuffer
;
605 mlt_properties_set_data( properties
, "_logbuffer", logbuffer
, 0, ( mlt_destructor
)av_free
, NULL
);
613 fprintf( stderr
, "%s: Could not allocate a stream for video\n", __FILE__
);
619 static AVFrame
*alloc_picture( int pix_fmt
, int width
, int height
)
622 AVFrame
*picture
= avcodec_alloc_frame();
624 // Determine size of the
625 int size
= avpicture_get_size(pix_fmt
, width
, height
);
627 // Allocate the picture buf
628 uint8_t *picture_buf
= av_malloc(size
);
630 // If we have both, then fill the image
631 if ( picture
!= NULL
&& picture_buf
!= NULL
)
633 // Fill the frame with the allocated buffer
634 avpicture_fill( (AVPicture
*)picture
, picture_buf
, pix_fmt
, width
, height
);
638 // Something failed - clean up what we can
640 av_free( picture_buf
);
647 static int open_video(AVFormatContext
*oc
, AVStream
*st
)
650 AVCodecContext
*video_enc
= st
->codec
;
652 // find the video encoder
653 AVCodec
*codec
= avcodec_find_encoder( video_enc
->codec_id
);
655 if( codec
&& codec
->pix_fmts
)
657 const enum PixelFormat
*p
= codec
->pix_fmts
;
660 if( *p
== video_enc
->pix_fmt
)
664 video_enc
->pix_fmt
= codec
->pix_fmts
[ 0 ];
667 // Open the codec safely
668 return codec
!= NULL
&& avcodec_open( video_enc
, codec
) >= 0;
671 void close_video(AVFormatContext
*oc
, AVStream
*st
)
673 avcodec_close(st
->codec
);
676 static inline long time_difference( struct timeval
*time1
)
678 struct timeval time2
;
679 gettimeofday( &time2
, NULL
);
680 return time2
.tv_sec
* 1000000 + time2
.tv_usec
- time1
->tv_sec
* 1000000 - time1
->tv_usec
;
683 /** The main thread - the argument is simply the consumer.
686 static void *consumer_thread( void *arg
)
688 // Map the argument to the object
689 mlt_consumer
this = arg
;
691 // Get the properties
692 mlt_properties properties
= MLT_CONSUMER_PROPERTIES( this );
694 // Get the terminate on pause property
695 int terminate_on_pause
= mlt_properties_get_int( properties
, "terminate_on_pause" );
698 // Determine if feed is slow (for realtime stuff)
699 int real_time_output
= mlt_properties_get_int( properties
, "real_time" );
704 // Get the frame rate
705 double fps
= mlt_properties_get_double( properties
, "fps" );
707 // Get width and height
708 int width
= mlt_properties_get_int( properties
, "width" );
709 int height
= mlt_properties_get_int( properties
, "height" );
710 int img_width
= width
;
711 int img_height
= height
;
713 // Get default audio properties
714 mlt_audio_format aud_fmt
= mlt_audio_pcm
;
715 int channels
= mlt_properties_get_int( properties
, "channels" );
716 int frequency
= mlt_properties_get_int( properties
, "frequency" );
720 // AVFormat audio buffer and frame size
721 int audio_outbuf_size
= 10000;
722 uint8_t *audio_outbuf
= av_malloc( audio_outbuf_size
);
723 int audio_input_frame_size
= 0;
725 // AVFormat video buffer and frame count
727 int video_outbuf_size
= ( 1024 * 1024 );
728 uint8_t *video_outbuf
= av_malloc( video_outbuf_size
);
730 // Used for the frame properties
731 mlt_frame frame
= NULL
;
732 mlt_properties frame_properties
= NULL
;
735 mlt_deque queue
= mlt_properties_get_data( properties
, "frame_queue", NULL
);
736 sample_fifo fifo
= mlt_properties_get_data( properties
, "sample_fifo", NULL
);
738 // Need two av pictures for converting
739 AVFrame
*output
= NULL
;
740 AVFrame
*input
= alloc_picture( PIX_FMT_YUV422
, width
, height
);
742 // For receiving images from an mlt_frame
744 mlt_image_format img_fmt
= mlt_image_yuv422
;
746 // For receiving audio samples back from the fifo
747 int16_t *buffer
= av_malloc( 48000 * 2 );
750 // Allocate the context
751 AVFormatContext
*oc
= av_alloc_format_context( );
754 AVStream
*audio_st
= NULL
;
755 AVStream
*video_st
= NULL
;
758 double audio_pts
= 0;
759 double video_pts
= 0;
766 long int total_time
= 0;
768 // Determine the format
769 AVOutputFormat
*fmt
= NULL
;
770 char *filename
= mlt_properties_get( properties
, "target" );
771 char *format
= mlt_properties_get( properties
, "f" );
772 char *vcodec
= mlt_properties_get( properties
, "vcodec" );
773 char *acodec
= mlt_properties_get( properties
, "acodec" );
775 // Used to store and override codec ids
779 // Check for user selected format first
780 if ( format
!= NULL
)
781 fmt
= guess_format( format
, NULL
, NULL
);
783 // Otherwise check on the filename
784 if ( fmt
== NULL
&& filename
!= NULL
)
785 fmt
= guess_format( NULL
, filename
, NULL
);
787 // Otherwise default to mpeg
789 fmt
= guess_format( "mpeg", NULL
, NULL
);
791 // We need a filename - default to stdout?
792 if ( filename
== NULL
|| !strcmp( filename
, "" ) )
795 // Get the codec ids selected
796 audio_codec_id
= fmt
->audio_codec
;
797 video_codec_id
= fmt
->video_codec
;
799 // Check for audio codec overides
800 if ( acodec
!= NULL
)
802 AVCodec
*p
= first_avcodec
;
805 if ( !strcmp( p
->name
, acodec
) && p
->type
== CODEC_TYPE_AUDIO
)
810 audio_codec_id
= p
->id
;
812 fprintf( stderr
, "%s: audio codec %s unrecognised - ignoring\n", __FILE__
, acodec
);
815 // Check for video codec overides
816 if ( vcodec
!= NULL
)
818 AVCodec
*p
= first_avcodec
;
821 if ( !strcmp( p
->name
, vcodec
) && p
->type
== CODEC_TYPE_VIDEO
)
826 video_codec_id
= p
->id
;
828 fprintf( stderr
, "%s: video codec %s unrecognised - ignoring\n", __FILE__
, vcodec
);
835 tmp
= mlt_properties_get( properties
, "meta.attr.title.markup");
836 if (tmp
!= NULL
) snprintf( oc
->title
, sizeof(oc
->title
), "%s", tmp
);
838 tmp
= mlt_properties_get( properties
, "meta.attr.comment.markup");
839 if (tmp
!= NULL
) snprintf( oc
->comment
, sizeof(oc
->comment
), "%s", tmp
);
841 tmp
= mlt_properties_get( properties
, "meta.attr.author.markup");
842 if (tmp
!= NULL
) snprintf( oc
->author
, sizeof(oc
->author
), "%s", tmp
);
844 tmp
= mlt_properties_get( properties
, "meta.attr.copyright.markup");
845 if (tmp
!= NULL
) snprintf( oc
->copyright
, sizeof(oc
->copyright
), "%s", tmp
);
847 tmp
= mlt_properties_get( properties
, "meta.attr.album.markup");
848 if (tmp
!= NULL
) snprintf( oc
->album
, sizeof(oc
->album
), "%s", tmp
);
850 metavalue
= mlt_properties_get_int( properties
, "meta.attr.year.markup");
851 if (metavalue
!= 0) oc
->year
= metavalue
;
853 metavalue
= mlt_properties_get_int( properties
, "meta.attr.track.markup");
854 if (metavalue
!= 0) oc
->track
= metavalue
;
857 snprintf( oc
->filename
, sizeof(oc
->filename
), "%s", filename
);
859 // Add audio and video streams
860 if ( fmt
->video_codec
!= CODEC_ID_NONE
)
861 video_st
= add_video_stream( this, oc
, video_codec_id
);
862 if ( fmt
->audio_codec
!= CODEC_ID_NONE
)
863 audio_st
= add_audio_stream( this, oc
, audio_codec_id
);
865 // Set the parameters (even though we have none...)
866 if ( av_set_parameters(oc
, NULL
) >= 0 )
868 oc
->preload
= ( int )( mlt_properties_get_double( properties
, "muxpreload" ) * AV_TIME_BASE
);
869 oc
->max_delay
= ( int )( mlt_properties_get_double( properties
, "muxdelay" ) * AV_TIME_BASE
);
871 // Process properties as AVOptions
872 apply_properties( oc
, properties
, AV_OPT_FLAG_ENCODING_PARAM
);
874 if ( video_st
&& !open_video( oc
, video_st
) )
877 audio_input_frame_size
= open_audio( oc
, audio_st
, audio_outbuf_size
);
879 // Open the output file, if needed
880 if ( !( fmt
->flags
& AVFMT_NOFILE
) )
882 if ( url_fopen( &oc
->pb
, filename
, URL_WRONLY
) < 0 )
884 fprintf( stderr
, "%s: Could not open '%s'\n", __FILE__
, filename
);
885 mlt_properties_set_int( properties
, "running", 0 );
889 // Write the stream header, if any
890 if ( mlt_properties_get_int( properties
, "running" ) )
891 av_write_header( oc
);
895 fprintf( stderr
, "%s: Invalid output format parameters\n", __FILE__
);
896 mlt_properties_set_int( properties
, "running", 0 );
901 output
= alloc_picture( video_st
->codec
->pix_fmt
, width
, height
);
903 // Last check - need at least one stream
904 if ( audio_st
== NULL
&& video_st
== NULL
)
905 mlt_properties_set_int( properties
, "running", 0 );
907 // Get the starting time (can ignore the times above)
908 gettimeofday( &ante
, NULL
);
910 // Loop while running
911 while( mlt_properties_get_int( properties
, "running" ) && !terminated
)
914 frame
= mlt_consumer_rt_frame( this );
916 // Check that we have a frame to work with
919 // Increment frames despatched
922 // Default audio args
923 frame_properties
= MLT_FRAME_PROPERTIES( frame
);
925 // Check for the terminated condition
926 terminated
= terminate_on_pause
&& mlt_properties_get_double( frame_properties
, "_speed" ) == 0.0;
928 // Get audio and append to the fifo
929 if ( !terminated
&& audio_st
)
931 samples
= mlt_sample_calculator( fps
, frequency
, count
++ );
932 mlt_frame_get_audio( frame
, &pcm
, &aud_fmt
, &frequency
, &channels
, &samples
);
934 // Create the fifo if we don't have one
937 fifo
= sample_fifo_init( frequency
, channels
);
938 mlt_properties_set_data( properties
, "sample_fifo", fifo
, 0, ( mlt_destructor
)sample_fifo_close
, NULL
);
941 if ( mlt_properties_get_double( frame_properties
, "_speed" ) != 1.0 )
942 memset( pcm
, 0, samples
* channels
* 2 );
944 // Append the samples
945 sample_fifo_append( fifo
, pcm
, samples
* channels
);
946 total_time
+= ( samples
* 1000000 ) / frequency
;
950 if ( !terminated
&& video_st
)
951 mlt_deque_push_back( queue
, frame
);
953 mlt_frame_close( frame
);
956 // While we have stuff to process, process...
960 audio_pts
= (double)audio_st
->pts
.val
* audio_st
->time_base
.num
/ audio_st
->time_base
.den
;
965 video_pts
= (double)video_st
->pts
.val
* video_st
->time_base
.num
/ video_st
->time_base
.den
;
969 // Write interleaved audio and video frames
970 if ( !video_st
|| ( video_st
&& audio_st
&& audio_pts
< video_pts
) )
972 if ( channels
* audio_input_frame_size
< sample_fifo_used( fifo
) )
976 av_init_packet( &pkt
);
980 sample_fifo_fetch( fifo
, buffer
, channels
* audio_input_frame_size
);
982 pkt
.size
= avcodec_encode_audio( c
, audio_outbuf
, audio_outbuf_size
, buffer
);
983 // Write the compressed frame in the media file
984 if ( c
->coded_frame
&& c
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
985 pkt
.pts
= av_rescale_q( c
->coded_frame
->pts
, c
->time_base
, audio_st
->time_base
);
986 pkt
.flags
|= PKT_FLAG_KEY
;
987 pkt
.stream_index
= audio_st
->index
;
988 pkt
.data
= audio_outbuf
;
991 if ( av_interleaved_write_frame( oc
, &pkt
) != 0)
992 fprintf( stderr
, "%s: Error while writing audio frame\n", __FILE__
);
994 audio_pts
+= c
->frame_size
;
1001 else if ( video_st
)
1003 if ( mlt_deque_count( queue
) )
1008 frame
= mlt_deque_pop_front( queue
);
1009 frame_properties
= MLT_FRAME_PROPERTIES( frame
);
1011 c
= video_st
->codec
;
1013 if ( mlt_properties_get_int( frame_properties
, "rendered" ) )
1020 mlt_events_fire( properties
, "consumer-frame-show", frame
, NULL
);
1022 mlt_frame_get_image( frame
, &image
, &img_fmt
, &img_width
, &img_height
, 0 );
1026 // Convert the mlt frame to an AVPicture
1027 for ( i
= 0; i
< height
; i
++ )
1029 p
= input
->data
[ 0 ] + i
* input
->linesize
[ 0 ];
1038 // Do the colour space conversion
1040 struct SwsContext
*context
= sws_getContext( width
, height
, PIX_FMT_YUV422
,
1041 width
, height
, video_st
->codec
->pix_fmt
, SWS_FAST_BILINEAR
, NULL
, NULL
, NULL
);
1042 sws_scale( context
, input
->data
, input
->linesize
, 0, height
,
1043 output
->data
, output
->linesize
);
1044 sws_freeContext( context
);
1046 img_convert( ( AVPicture
* )output
, video_st
->codec
->pix_fmt
, ( AVPicture
* )input
, PIX_FMT_YUV422
, width
, height
);
1049 // Apply the alpha if applicable
1050 if ( video_st
->codec
->pix_fmt
== PIX_FMT_RGBA32
)
1052 uint8_t *alpha
= mlt_frame_get_alpha_mask( frame
);
1055 for ( i
= 0; i
< height
; i
++ )
1057 n
= ( width
+ 7 ) / 8;
1058 p
= output
->data
[ 0 ] + i
* output
->linesize
[ 0 ];
1066 case 0: do { *p
= *alpha
++; p
+= 4;
1067 case 7: *p
= *alpha
++; p
+= 4;
1068 case 6: *p
= *alpha
++; p
+= 4;
1069 case 5: *p
= *alpha
++; p
+= 4;
1070 case 4: *p
= *alpha
++; p
+= 4;
1071 case 3: *p
= *alpha
++; p
+= 4;
1072 case 2: *p
= *alpha
++; p
+= 4;
1073 case 1: *p
= *alpha
++; p
+= 4;
1081 if (oc
->oformat
->flags
& AVFMT_RAWPICTURE
)
1083 // raw video case. The API will change slightly in the near future for that
1085 av_init_packet(&pkt
);
1087 pkt
.flags
|= PKT_FLAG_KEY
;
1088 pkt
.stream_index
= video_st
->index
;
1089 pkt
.data
= (uint8_t *)output
;
1090 pkt
.size
= sizeof(AVPicture
);
1092 ret
= av_write_frame(oc
, &pkt
);
1093 video_pts
+= c
->frame_size
;
1098 output
->quality
= video_st
->quality
;
1100 // Set frame interlace hints
1101 output
->interlaced_frame
= !mlt_properties_get_int( frame_properties
, "progressive" );
1102 output
->top_field_first
= mlt_properties_get_int( frame_properties
, "top_field_first" );
1105 out_size
= avcodec_encode_video(c
, video_outbuf
, video_outbuf_size
, output
);
1107 // If zero size, it means the image was buffered
1111 av_init_packet( &pkt
);
1113 if ( c
->coded_frame
&& c
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
1114 pkt
.pts
= av_rescale_q( c
->coded_frame
->pts
, c
->time_base
, video_st
->time_base
);
1115 if( c
->coded_frame
&& c
->coded_frame
->key_frame
)
1116 pkt
.flags
|= PKT_FLAG_KEY
;
1117 pkt
.stream_index
= video_st
->index
;
1118 pkt
.data
= video_outbuf
;
1121 // write the compressed frame in the media file
1122 ret
= av_interleaved_write_frame(oc
, &pkt
);
1123 video_pts
+= c
->frame_size
;
1125 // Dual pass logging
1126 if ( mlt_properties_get_data( properties
, "_logfile", NULL
) && c
->stats_out
)
1127 fprintf( mlt_properties_get_data( properties
, "_logfile", NULL
), "%s", c
->stats_out
);
1131 fprintf( stderr
, "%s: error with video encode\n", __FILE__
);
1135 mlt_frame_close( frame
);
1144 if ( real_time_output
== 1 && frames
% 12 == 0 )
1146 long passed
= time_difference( &ante
);
1149 long pending
= ( ( ( long )sample_fifo_used( fifo
) * 1000 ) / frequency
) * 1000;
1152 if ( passed
< total_time
)
1154 long total
= ( total_time
- passed
);
1155 struct timespec t
= { total
/ 1000000, ( total
% 1000000 ) * 1000 };
1156 nanosleep( &t
, NULL
);
1162 if ( ! real_time_output
)
1165 if ( audio_st
&& audio_st
->codec
->frame_size
> 1 ) for (;;)
1167 AVCodecContext
*c
= audio_st
->codec
;
1169 av_init_packet( &pkt
);
1172 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1173 ( channels
* audio_input_frame_size
< sample_fifo_used( fifo
) ) )
1175 sample_fifo_fetch( fifo
, buffer
, channels
* audio_input_frame_size
);
1176 pkt
.size
= avcodec_encode_audio( c
, audio_outbuf
, audio_outbuf_size
, buffer
);
1178 if ( pkt
.size
<= 0 )
1179 pkt
.size
= avcodec_encode_audio( c
, audio_outbuf
, audio_outbuf_size
, NULL
);
1180 if ( pkt
.size
<= 0 )
1183 // Write the compressed frame in the media file
1184 if ( c
->coded_frame
&& c
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
1185 pkt
.pts
= av_rescale_q( c
->coded_frame
->pts
, c
->time_base
, audio_st
->time_base
);
1186 pkt
.flags
|= PKT_FLAG_KEY
;
1187 pkt
.stream_index
= audio_st
->index
;
1188 pkt
.data
= audio_outbuf
;
1189 if ( av_interleaved_write_frame( oc
, &pkt
) != 0 )
1191 fprintf( stderr
, "%s: Error while writing flushed audio frame\n", __FILE__
);
1197 if ( video_st
&& !( oc
->oformat
->flags
& AVFMT_RAWPICTURE
) ) for (;;)
1199 AVCodecContext
*c
= video_st
->codec
;
1201 av_init_packet( &pkt
);
1204 pkt
.size
= avcodec_encode_video( c
, video_outbuf
, video_outbuf_size
, NULL
);
1205 if ( pkt
.size
<= 0 )
1208 if ( c
->coded_frame
&& c
->coded_frame
->pts
!= AV_NOPTS_VALUE
)
1209 pkt
.pts
= av_rescale_q( c
->coded_frame
->pts
, c
->time_base
, video_st
->time_base
);
1210 if( c
->coded_frame
&& c
->coded_frame
->key_frame
)
1211 pkt
.flags
|= PKT_FLAG_KEY
;
1212 pkt
.stream_index
= video_st
->index
;
1213 pkt
.data
= video_outbuf
;
1215 // write the compressed frame in the media file
1216 if ( av_interleaved_write_frame( oc
, &pkt
) != 0 )
1218 fprintf( stderr
, "%s: Error while writing flushed video frame\n". __FILE__
);
1227 close_video(oc
, video_st
);
1229 close_audio(oc
, audio_st
);
1231 // Write the trailer, if any
1232 av_write_trailer(oc
);
1235 for(i
= 0; i
< oc
->nb_streams
; i
++)
1236 av_freep(&oc
->streams
[i
]);
1238 // Close the output file
1239 if (!(fmt
->flags
& AVFMT_NOFILE
))
1240 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1243 url_fclose(&oc
->pb
);
1246 // Clean up input and output frames
1248 av_free( output
->data
[0] );
1250 av_free( input
->data
[0] );
1252 av_free( video_outbuf
);
1258 // Just in case we terminated on pause
1259 mlt_properties_set_int( properties
, "running", 0 );
1261 mlt_consumer_stopped( this );
1266 /** Close the consumer.
1269 static void consumer_close( mlt_consumer
this )
1271 // Stop the consumer
1272 mlt_consumer_stop( this );
1275 mlt_consumer_close( this );