Write metadata if there is any
[melted] / src / modules / avformat / consumer_avformat.c
1 /*
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 *
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.
10 *
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.
15 *
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.
19 */
20
21 // Local header files
22 #include "consumer_avformat.h"
23
24 // mlt Header files
25 #include <framework/mlt_frame.h>
26
27 // System header files
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <limits.h>
32 #include <pthread.h>
33 #include <sys/time.h>
34 #include <math.h>
35
36 // avformat header files
37 #include <avformat.h>
38
39 //
40 // This structure should be extended and made globally available in mlt
41 //
42
43 typedef struct
44 {
45 int16_t *buffer;
46 int size;
47 int used;
48 double time;
49 int frequency;
50 int channels;
51 }
52 *sample_fifo, sample_fifo_s;
53
54 sample_fifo sample_fifo_init( int frequency, int channels )
55 {
56 sample_fifo this = calloc( 1, sizeof( sample_fifo_s ) );
57 this->frequency = frequency;
58 this->channels = channels;
59 return this;
60 }
61
62 // sample_fifo_clear and check are temporarily aborted (not working as intended)
63
64 void sample_fifo_clear( sample_fifo this, double time )
65 {
66 int words = ( float )( time - this->time ) * this->frequency * this->channels;
67 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) && this->used > words && words > 0 )
68 {
69 memmove( this->buffer, &this->buffer[ words ], ( this->used - words ) * sizeof( int16_t ) );
70 this->used -= words;
71 this->time = time;
72 }
73 else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )this->time * 100 ) )
74 {
75 this->used = 0;
76 this->time = time;
77 }
78 }
79
80 void sample_fifo_check( sample_fifo this, double time )
81 {
82 if ( this->used == 0 )
83 {
84 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) )
85 this->time = time;
86 }
87 }
88
89 void sample_fifo_append( sample_fifo this, int16_t *samples, int count )
90 {
91 if ( ( this->size - this->used ) < count )
92 {
93 this->size += count * 5;
94 this->buffer = realloc( this->buffer, this->size * sizeof( int16_t ) );
95 }
96
97 memcpy( &this->buffer[ this->used ], samples, count * sizeof( int16_t ) );
98 this->used += count;
99 }
100
101 int sample_fifo_used( sample_fifo this )
102 {
103 return this->used;
104 }
105
106 int sample_fifo_fetch( sample_fifo this, int16_t *samples, int count )
107 {
108 if ( count > this->used )
109 count = this->used;
110
111 memcpy( samples, this->buffer, count * sizeof( int16_t ) );
112 this->used -= count;
113 memmove( this->buffer, &this->buffer[ count ], this->used * sizeof( int16_t ) );
114
115 this->time += ( double )count / this->channels / this->frequency;
116
117 return count;
118 }
119
120 void sample_fifo_close( sample_fifo this )
121 {
122 free( this->buffer );
123 free( this );
124 }
125
126 // Forward references.
127 static int consumer_start( mlt_consumer this );
128 static int consumer_stop( mlt_consumer this );
129 static int consumer_is_stopped( mlt_consumer this );
130 static void *consumer_thread( void *arg );
131 static void consumer_close( mlt_consumer this );
132
133 /** Initialise the dv consumer.
134 */
135
136 mlt_consumer consumer_avformat_init( char *arg )
137 {
138 // Allocate the consumer
139 mlt_consumer this = mlt_consumer_new( );
140
141 // If memory allocated and initialises without error
142 if ( this != NULL )
143 {
144 // Get properties from the consumer
145 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
146
147 // Assign close callback
148 this->close = consumer_close;
149
150 // Interpret the argument
151 if ( arg != NULL )
152 mlt_properties_set( properties, "target", arg );
153
154 // sample and frame queue
155 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
156
157 // Set avformat defaults (all lifted from ffmpeg.c)
158 mlt_properties_set_int( properties, "audio_bit_rate", 128000 );
159 mlt_properties_set_int( properties, "video_bit_rate", 200 * 1000 );
160 mlt_properties_set_int( properties, "video_bit_rate_tolerance", 4000 * 1000 );
161 mlt_properties_set_int( properties, "gop_size", 12 );
162 mlt_properties_set_int( properties, "b_frames", 0 );
163 mlt_properties_set_int( properties, "mb_decision", FF_MB_DECISION_SIMPLE );
164 mlt_properties_set_double( properties, "qscale", 1 );
165 mlt_properties_set_int( properties, "me_method", ME_EPZS );
166 mlt_properties_set_int( properties, "mb_cmp", FF_CMP_SAD );
167 mlt_properties_set_int( properties, "ildct_cmp", FF_CMP_VSAD );
168 mlt_properties_set_int( properties, "sub_cmp", FF_CMP_SAD );
169 mlt_properties_set_int( properties, "cmp", FF_CMP_SAD );
170 mlt_properties_set_int( properties, "pre_cmp", FF_CMP_SAD );
171 mlt_properties_set_int( properties, "pre_me", 0 );
172 mlt_properties_set_double( properties, "lumi_mask", 0 );
173 mlt_properties_set_double( properties, "dark_mask", 0 );
174 mlt_properties_set_double( properties, "scplx_mask", 0 );
175 mlt_properties_set_double( properties, "tcplx_mask", 0 );
176 mlt_properties_set_double( properties, "p_mask", 0 );
177 mlt_properties_set_int( properties, "qns", 0 );
178 mlt_properties_set_int( properties, "video_qmin", 2 );
179 mlt_properties_set_int( properties, "video_qmax", 31 );
180 mlt_properties_set_int( properties, "video_lmin", 2*FF_QP2LAMBDA );
181 mlt_properties_set_int( properties, "video_lmax", 31*FF_QP2LAMBDA );
182 mlt_properties_set_int( properties, "video_mb_qmin", 2 );
183 mlt_properties_set_int( properties, "video_mb_qmax", 31 );
184 mlt_properties_set_int( properties, "video_qdiff", 3 );
185 mlt_properties_set_double( properties, "video_qblur", 0.5 );
186 mlt_properties_set_double( properties, "video_qcomp", 0.5 );
187 mlt_properties_set_int( properties, "video_rc_max_rate", 0 );
188 mlt_properties_set_int( properties, "video_rc_min_rate", 0 );
189 mlt_properties_set_int( properties, "video_rc_buffer_size", 0 );
190 mlt_properties_set_double( properties, "video_rc_buffer_aggressivity", 1.0 );
191 mlt_properties_set_double( properties, "video_rc_initial_cplx", 0 );
192 mlt_properties_set_double( properties, "video_i_qfactor", 1.25 );
193 mlt_properties_set_double( properties, "video_b_qfactor", 1.25 );
194 mlt_properties_set_double( properties, "video_i_qoffset", -0.8 );
195 mlt_properties_set_double( properties, "video_b_qoffset", 0 );
196 mlt_properties_set_int( properties, "video_intra_quant_bias", FF_DEFAULT_QUANT_BIAS );
197 mlt_properties_set_int( properties, "video_inter_quant_bias", FF_DEFAULT_QUANT_BIAS );
198 mlt_properties_set_int( properties, "dct_algo", 0 );
199 mlt_properties_set_int( properties, "idct_algo", 0 );
200 mlt_properties_set_int( properties, "me_threshold", 0 );
201 mlt_properties_set_int( properties, "mb_threshold", 0 );
202 mlt_properties_set_int( properties, "intra_dc_precision", 0 );
203 mlt_properties_set_int( properties, "strict", 0 );
204 mlt_properties_set_int( properties, "error_rate", 0 );
205 mlt_properties_set_int( properties, "noise_reduction", 0 );
206 mlt_properties_set_int( properties, "sc_threshold", 0 );
207 mlt_properties_set_int( properties, "me_range", 0 );
208 mlt_properties_set_int( properties, "coder", 0 );
209 mlt_properties_set_int( properties, "context", 0 );
210 mlt_properties_set_int( properties, "predictor", 0 );
211
212 // Ensure termination at end of the stream
213 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
214
215 // Set up start/stop/terminated callbacks
216 this->start = consumer_start;
217 this->stop = consumer_stop;
218 this->is_stopped = consumer_is_stopped;
219 }
220
221 // Return this
222 return this;
223 }
224
225 /** Start the consumer.
226 */
227
228 static int consumer_start( mlt_consumer this )
229 {
230 // Get the properties
231 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
232
233 // Check that we're not already running
234 if ( !mlt_properties_get_int( properties, "running" ) )
235 {
236 // Allocate a thread
237 pthread_t *thread = calloc( 1, sizeof( pthread_t ) );
238
239 // Get the width and height
240 int width = mlt_properties_get_int( properties, "width" );
241 int height = mlt_properties_get_int( properties, "height" );
242
243 // Obtain the size property
244 char *size = mlt_properties_get( properties, "size" );
245
246 // Interpret it
247 if ( size != NULL )
248 {
249 int tw, th;
250 if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
251 {
252 width = tw;
253 height = th;
254 }
255 else
256 {
257 fprintf( stderr, "consumer_avformat: Invalid size property %s - ignoring.\n", size );
258 }
259 }
260
261 // Now ensure we honour the multiple of two requested by libavformat
262 mlt_properties_set_int( properties, "width", ( width / 2 ) * 2 );
263 mlt_properties_set_int( properties, "height", ( height / 2 ) * 2 );
264
265 // Assign the thread to properties
266 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
267
268 // Set the running state
269 mlt_properties_set_int( properties, "running", 1 );
270
271 // Create the thread
272 pthread_create( thread, NULL, consumer_thread, this );
273 }
274 return 0;
275 }
276
277 /** Stop the consumer.
278 */
279
280 static int consumer_stop( mlt_consumer this )
281 {
282 // Get the properties
283 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
284
285 // Check that we're running
286 if ( mlt_properties_get_int( properties, "running" ) )
287 {
288 // Get the thread
289 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
290
291 // Stop the thread
292 mlt_properties_set_int( properties, "running", 0 );
293
294 // Wait for termination
295 pthread_join( *thread, NULL );
296 }
297
298 return 0;
299 }
300
301 /** Determine if the consumer is stopped.
302 */
303
304 static int consumer_is_stopped( mlt_consumer this )
305 {
306 // Get the properties
307 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
308 return !mlt_properties_get_int( properties, "running" );
309 }
310
311 /** Add an audio output stream
312 */
313
314 static AVStream *add_audio_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
315 {
316 // Get the properties
317 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
318
319 // Create a new stream
320 AVStream *st = av_new_stream( oc, 1 );
321
322 // If created, then initialise from properties
323 if ( st != NULL )
324 {
325 AVCodecContext *c = st->codec;
326 c->codec_id = codec_id;
327 c->codec_type = CODEC_TYPE_AUDIO;
328
329 // Put sample parameters
330 c->bit_rate = mlt_properties_get_int( properties, "audio_bit_rate" );
331 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
332 c->channels = mlt_properties_get_int( properties, "channels" );
333
334 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
335 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
336
337 // Allow the user to override the audio fourcc
338 if ( mlt_properties_get( properties, "afourcc" ) )
339 {
340 char *tail = NULL;
341 char *arg = mlt_properties_get( properties, "afourcc" );
342 int tag = strtol( arg, &tail, 0);
343 if( !tail || *tail )
344 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
345 c->codec_tag = tag;
346 }
347 }
348 else
349 {
350 fprintf( stderr, "Could not allocate a stream for audio\n" );
351 }
352
353 return st;
354 }
355
356 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
357 {
358 // We will return the audio input size from here
359 int audio_input_frame_size = 0;
360
361 // Get the context
362 AVCodecContext *c = st->codec;
363
364 // Find the encoder
365 AVCodec *codec = avcodec_find_encoder( c->codec_id );
366
367 // Continue if codec found and we can open it
368 if ( codec != NULL && avcodec_open(c, codec) >= 0 )
369 {
370 // ugly hack for PCM codecs (will be removed ASAP with new PCM
371 // support to compute the input frame size in samples
372 if ( c->frame_size <= 1 )
373 {
374 audio_input_frame_size = audio_outbuf_size / c->channels;
375 switch(st->codec->codec_id)
376 {
377 case CODEC_ID_PCM_S16LE:
378 case CODEC_ID_PCM_S16BE:
379 case CODEC_ID_PCM_U16LE:
380 case CODEC_ID_PCM_U16BE:
381 audio_input_frame_size >>= 1;
382 break;
383 default:
384 break;
385 }
386 }
387 else
388 {
389 audio_input_frame_size = c->frame_size;
390 }
391
392 // Some formats want stream headers to be seperate (hmm)
393 if( !strcmp( oc->oformat->name, "mp4" ) ||
394 !strcmp( oc->oformat->name, "mov" ) ||
395 !strcmp( oc->oformat->name, "3gp" ) )
396 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
397 }
398 else
399 {
400 fprintf( stderr, "Unable to encode audio - disabling audio output.\n" );
401 }
402
403 return audio_input_frame_size;
404 }
405
406 static void close_audio( AVFormatContext *oc, AVStream *st )
407 {
408 avcodec_close( st->codec );
409 }
410
411 /** Add a video output stream
412 */
413
414 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
415 {
416 // Get the properties
417 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
418
419 // Create a new stream
420 AVStream *st = av_new_stream( oc, 0 );
421
422 if ( st != NULL )
423 {
424 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
425 double ar = mlt_properties_get_double( properties, "display_ratio" );
426 AVCodecContext *c = st->codec;
427 c->codec_id = codec_id;
428 c->codec_type = CODEC_TYPE_VIDEO;
429
430 // put sample parameters
431 c->bit_rate = mlt_properties_get_int( properties, "video_bit_rate" );
432 c->bit_rate_tolerance = mlt_properties_get_int( properties, "video_bit_rate_tolerance" );
433 c->width = mlt_properties_get_int( properties, "width" );
434 c->height = mlt_properties_get_int( properties, "height" );
435 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
436 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
437 c->gop_size = mlt_properties_get_int( properties, "gop_size" );
438 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
439
440 if ( mlt_properties_get_int( properties, "b_frames" ) )
441 {
442 c->max_b_frames = mlt_properties_get_int( properties, "b_frames" );
443 c->b_frame_strategy = 0;
444 c->b_quant_factor = 2.0;
445 }
446
447 c->mb_decision = mlt_properties_get_int( properties, "mb_decision" );
448 c->sample_aspect_ratio = av_d2q( ar * c->height / c->width , 255);
449 c->mb_cmp = mlt_properties_get_int( properties, "mb_cmp" );
450 c->ildct_cmp = mlt_properties_get_int( properties, "ildct_cmp" );
451 c->me_sub_cmp = mlt_properties_get_int( properties, "sub_cmp" );
452 c->me_cmp = mlt_properties_get_int( properties, "cmp" );
453 c->me_pre_cmp = mlt_properties_get_int( properties, "pre_cmp" );
454 c->pre_me = mlt_properties_get_int( properties, "pre_me" );
455 c->lumi_masking = mlt_properties_get_double( properties, "lumi_mask" );
456 c->dark_masking = mlt_properties_get_double( properties, "dark_mask" );
457 c->spatial_cplx_masking = mlt_properties_get_double( properties, "scplx_mask" );
458 c->temporal_cplx_masking = mlt_properties_get_double( properties, "tcplx_mask" );
459 c->p_masking = mlt_properties_get_double( properties, "p_mask" );
460 c->quantizer_noise_shaping= mlt_properties_get_int( properties, "qns" );
461 c->qmin = mlt_properties_get_int( properties, "video_qmin" );
462 c->qmax = mlt_properties_get_int( properties, "video_qmax" );
463 c->lmin = mlt_properties_get_int( properties, "video_lmin" );
464 c->lmax = mlt_properties_get_int( properties, "video_lmax" );
465 c->mb_qmin = mlt_properties_get_int( properties, "video_mb_qmin" );
466 c->mb_qmax = mlt_properties_get_int( properties, "video_mb_qmax" );
467 c->max_qdiff = mlt_properties_get_int( properties, "video_qdiff" );
468 c->qblur = mlt_properties_get_double( properties, "video_qblur" );
469 c->qcompress = mlt_properties_get_double( properties, "video_qcomp" );
470
471 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
472 {
473 c->flags |= CODEC_FLAG_QSCALE;
474 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
475 }
476
477 // Allow the user to override the video fourcc
478 if ( mlt_properties_get( properties, "vfourcc" ) )
479 {
480 char *tail = NULL;
481 const char *arg = mlt_properties_get( properties, "vfourcc" );
482 int tag = strtol( arg, &tail, 0);
483 if( !tail || *tail )
484 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
485 c->codec_tag = tag;
486 }
487
488 // Some formats want stream headers to be seperate
489 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
490 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
491
492 c->rc_max_rate = mlt_properties_get_int( properties, "video_rc_max_rate" );
493 c->rc_min_rate = mlt_properties_get_int( properties, "video_rc_min_rate" );
494 c->rc_buffer_size = mlt_properties_get_int( properties, "video_rc_buffer_size" );
495 c->rc_buffer_aggressivity= mlt_properties_get_double( properties, "video_rc_buffer_aggressivity" );
496 c->rc_initial_cplx= mlt_properties_get_double( properties, "video_rc_initial_cplx" );
497 c->i_quant_factor = mlt_properties_get_double( properties, "video_i_qfactor" );
498 c->b_quant_factor = mlt_properties_get_double( properties, "video_b_qfactor" );
499 c->i_quant_offset = mlt_properties_get_double( properties, "video_i_qoffset" );
500 c->b_quant_offset = mlt_properties_get_double( properties, "video_b_qoffset" );
501 c->intra_quant_bias = mlt_properties_get_int( properties, "video_intra_quant_bias" );
502 c->inter_quant_bias = mlt_properties_get_int( properties, "video_inter_quant_bias" );
503 c->dct_algo = mlt_properties_get_int( properties, "dct_algo" );
504 c->idct_algo = mlt_properties_get_int( properties, "idct_algo" );
505 c->me_threshold= mlt_properties_get_int( properties, "me_threshold" );
506 c->mb_threshold= mlt_properties_get_int( properties, "mb_threshold" );
507 c->intra_dc_precision= mlt_properties_get_int( properties, "intra_dc_precision" );
508 c->strict_std_compliance = mlt_properties_get_int( properties, "strict" );
509 c->error_rate = mlt_properties_get_int( properties, "error_rate" );
510 c->noise_reduction= mlt_properties_get_int( properties, "noise_reduction" );
511 c->scenechange_threshold= mlt_properties_get_int( properties, "sc_threshold" );
512 c->me_range = mlt_properties_get_int( properties, "me_range" );
513 c->coder_type= mlt_properties_get_int( properties, "coder" );
514 c->context_model= mlt_properties_get_int( properties, "context" );
515 c->prediction_method= mlt_properties_get_int( properties, "predictor" );
516 c->me_method = mlt_properties_get_int( properties, "me_method" );
517 }
518 else
519 {
520 fprintf( stderr, "Could not allocate a stream for video\n" );
521 }
522
523 return st;
524 }
525
526 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
527 {
528 // Allocate a frame
529 AVFrame *picture = avcodec_alloc_frame();
530
531 // Determine size of the
532 int size = avpicture_get_size(pix_fmt, width, height);
533
534 // Allocate the picture buf
535 uint8_t *picture_buf = av_malloc(size);
536
537 // If we have both, then fill the image
538 if ( picture != NULL && picture_buf != NULL )
539 {
540 // Fill the frame with the allocated buffer
541 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
542 }
543 else
544 {
545 // Something failed - clean up what we can
546 av_free( picture );
547 av_free( picture_buf );
548 picture = NULL;
549 }
550
551 return picture;
552 }
553
554 static int open_video(AVFormatContext *oc, AVStream *st)
555 {
556 // Get the codec
557 AVCodecContext *video_enc = st->codec;
558
559 // find the video encoder
560 AVCodec *codec = avcodec_find_encoder( video_enc->codec_id );
561
562 if( codec && codec->pix_fmts )
563 {
564 const enum PixelFormat *p = codec->pix_fmts;
565 for( ; *p!=-1; p++ )
566 {
567 if( *p == video_enc->pix_fmt )
568 break;
569 }
570 if( *p == -1 )
571 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
572 }
573
574 // Open the codec safely
575 return codec != NULL && avcodec_open( video_enc, codec ) >= 0;
576 }
577
578 void close_video(AVFormatContext *oc, AVStream *st)
579 {
580 avcodec_close(st->codec);
581 }
582
583 static inline long time_difference( struct timeval *time1 )
584 {
585 struct timeval time2;
586 gettimeofday( &time2, NULL );
587 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
588 }
589
590 /** The main thread - the argument is simply the consumer.
591 */
592
593 static void *consumer_thread( void *arg )
594 {
595 // Map the argument to the object
596 mlt_consumer this = arg;
597
598 // Get the properties
599 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
600
601 // Get the terminate on pause property
602 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
603 int terminated = 0;
604
605 // Determine if feed is slow (for realtime stuff)
606 int real_time_output = mlt_properties_get_int( properties, "real_time" );
607
608 // Time structures
609 struct timeval ante;
610
611 // Get the frame rate
612 int fps = mlt_properties_get_double( properties, "fps" );
613
614 // Get width and height
615 int width = mlt_properties_get_int( properties, "width" );
616 int height = mlt_properties_get_int( properties, "height" );
617 int img_width = width;
618 int img_height = height;
619
620 // Get default audio properties
621 mlt_audio_format aud_fmt = mlt_audio_pcm;
622 int channels = mlt_properties_get_int( properties, "channels" );
623 int frequency = mlt_properties_get_int( properties, "frequency" );
624 int16_t *pcm = NULL;
625 int samples = 0;
626
627 // AVFormat audio buffer and frame size
628 int audio_outbuf_size = 10000;
629 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
630 int audio_input_frame_size = 0;
631
632 // AVFormat video buffer and frame count
633 int frame_count = 0;
634 int video_outbuf_size = ( 1024 * 1024 );
635 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
636
637 // Used for the frame properties
638 mlt_frame frame = NULL;
639 mlt_properties frame_properties = NULL;
640
641 // Get the queues
642 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
643 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
644
645 // Need two av pictures for converting
646 AVFrame *output = NULL;
647 AVFrame *input = alloc_picture( PIX_FMT_YUV422, width, height );
648
649 // For receiving images from an mlt_frame
650 uint8_t *image;
651 mlt_image_format img_fmt = mlt_image_yuv422;
652
653 // For receiving audio samples back from the fifo
654 int16_t *buffer = av_malloc( 48000 * 2 );
655 int count = 0;
656
657 // Allocate the context
658 AVFormatContext *oc = av_alloc_format_context( );
659
660 // Streams
661 AVStream *audio_st = NULL;
662 AVStream *video_st = NULL;
663
664 // Time stamps
665 double audio_pts = 0;
666 double video_pts = 0;
667
668 // Loop variable
669 int i;
670
671 // Frames despatched
672 long int frames = 0;
673 long int total_time = 0;
674
675 // Determine the format
676 AVOutputFormat *fmt = NULL;
677 char *filename = mlt_properties_get( properties, "target" );
678 char *format = mlt_properties_get( properties, "format" );
679 char *vcodec = mlt_properties_get( properties, "vcodec" );
680 char *acodec = mlt_properties_get( properties, "acodec" );
681
682 // Used to store and override codec ids
683 int audio_codec_id;
684 int video_codec_id;
685
686 // Check for user selected format first
687 if ( format != NULL )
688 fmt = guess_format( format, NULL, NULL );
689
690 // Otherwise check on the filename
691 if ( fmt == NULL && filename != NULL )
692 fmt = guess_format( NULL, filename, NULL );
693
694 // Otherwise default to mpeg
695 if ( fmt == NULL )
696 fmt = guess_format( "mpeg", NULL, NULL );
697
698 // We need a filename - default to stdout?
699 if ( filename == NULL || !strcmp( filename, "" ) )
700 filename = "pipe:";
701
702 // Get the codec ids selected
703 audio_codec_id = fmt->audio_codec;
704 video_codec_id = fmt->video_codec;
705
706 // Check for audio codec overides
707 if ( acodec != NULL )
708 {
709 AVCodec *p = first_avcodec;
710 while( p != NULL )
711 {
712 if ( !strcmp( p->name, acodec ) && p->type == CODEC_TYPE_AUDIO )
713 break;
714 p = p->next;
715 }
716 if ( p != NULL )
717 audio_codec_id = p->id;
718 else
719 fprintf( stderr, "consumer_avcodec: audio codec %s unrecognised - ignoring\n", acodec );
720 }
721
722 // Check for video codec overides
723 if ( vcodec != NULL )
724 {
725 AVCodec *p = first_avcodec;
726 while( p != NULL )
727 {
728 if ( !strcmp( p->name, vcodec ) && p->type == CODEC_TYPE_VIDEO )
729 break;
730 p = p->next;
731 }
732 if ( p != NULL )
733 video_codec_id = p->id;
734 else
735 fprintf( stderr, "consumer_avcodec: video codec %s unrecognised - ignoring\n", vcodec );
736 }
737
738 // Update the output context
739
740 // Write metadata
741 char *tmp = NULL;
742 int metavalue;
743
744 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
745 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
746
747 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
748 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
749
750 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
751 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
752
753 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
754 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
755
756 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
757 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
758
759 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
760 if (metavalue != 0) oc->year = metavalue;
761
762 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
763 if (metavalue != 0) oc->track = metavalue;
764
765 oc->oformat = fmt;
766 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
767
768 // Add audio and video streams
769 if ( fmt->video_codec != CODEC_ID_NONE )
770 video_st = add_video_stream( this, oc, video_codec_id );
771 if ( fmt->audio_codec != CODEC_ID_NONE )
772 audio_st = add_audio_stream( this, oc, audio_codec_id );
773
774 // Set the parameters (even though we have none...)
775 if ( av_set_parameters(oc, NULL) >= 0 )
776 {
777 if ( video_st && !open_video( oc, video_st ) )
778 video_st = NULL;
779 if ( audio_st )
780 audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
781
782 // Open the output file, if needed
783 if ( !( fmt->flags & AVFMT_NOFILE ) )
784 {
785 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0)
786 {
787 fprintf(stderr, "Could not open '%s'\n", filename);
788 mlt_properties_set_int( properties, "running", 0 );
789 }
790 }
791
792 // Write the stream header, if any
793 if ( mlt_properties_get_int( properties, "running" ) )
794 av_write_header( oc );
795 }
796 else
797 {
798 fprintf(stderr, "Invalid output format parameters\n");
799 mlt_properties_set_int( properties, "running", 0 );
800 }
801
802 // Allocate picture
803 if ( video_st )
804 output = alloc_picture( video_st->codec->pix_fmt, width, height );
805
806 // Last check - need at least one stream
807 if ( audio_st == NULL && video_st == NULL )
808 mlt_properties_set_int( properties, "running", 0 );
809
810 // Get the starting time (can ignore the times above)
811 gettimeofday( &ante, NULL );
812
813 // Loop while running
814 while( mlt_properties_get_int( properties, "running" ) && !terminated )
815 {
816 // Get the frame
817 frame = mlt_consumer_rt_frame( this );
818
819 // Check that we have a frame to work with
820 if ( frame != NULL )
821 {
822 // Increment frames despatched
823 frames ++;
824
825 // Default audio args
826 frame_properties = MLT_FRAME_PROPERTIES( frame );
827
828 // Check for the terminated condition
829 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
830
831 // Get audio and append to the fifo
832 if ( !terminated && audio_st )
833 {
834 samples = mlt_sample_calculator( fps, frequency, count ++ );
835 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
836
837 // Create the fifo if we don't have one
838 if ( fifo == NULL )
839 {
840 fifo = sample_fifo_init( frequency, channels );
841 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
842 }
843
844 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
845 memset( pcm, 0, samples * channels * 2 );
846
847 // Append the samples
848 sample_fifo_append( fifo, pcm, samples * channels );
849 total_time += ( samples * 1000000 ) / frequency;
850 }
851
852 // Encode the image
853 if ( !terminated && video_st )
854 mlt_deque_push_back( queue, frame );
855 else
856 mlt_frame_close( frame );
857 }
858
859 // While we have stuff to process, process...
860 while ( 1 )
861 {
862 if (audio_st)
863 audio_pts = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;
864 else
865 audio_pts = 0.0;
866
867 if (video_st)
868 video_pts = (double)video_st->pts.val * video_st->time_base.num / video_st->time_base.den;
869 else
870 video_pts = 0.0;
871
872 // Write interleaved audio and video frames
873 if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
874 {
875 if ( channels * audio_input_frame_size < sample_fifo_used( fifo ) )
876 {
877 AVCodecContext *c;
878 AVPacket pkt;
879 av_init_packet( &pkt );
880
881 c = audio_st->codec;
882
883 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
884
885 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
886 // Write the compressed frame in the media file
887 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
888 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
889 pkt.flags |= PKT_FLAG_KEY;
890 pkt.stream_index= audio_st->index;
891 pkt.data= audio_outbuf;
892
893 if ( pkt.size )
894 if ( av_interleaved_write_frame( oc, &pkt ) != 0)
895 fprintf(stderr, "Error while writing audio frame\n");
896
897 audio_pts += c->frame_size;
898 }
899 else
900 {
901 break;
902 }
903 }
904 else if ( video_st )
905 {
906 if ( mlt_deque_count( queue ) )
907 {
908 int out_size, ret;
909 AVCodecContext *c;
910
911 frame = mlt_deque_pop_front( queue );
912 frame_properties = MLT_FRAME_PROPERTIES( frame );
913
914 c = video_st->codec;
915
916 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
917 {
918 int i = 0;
919 int j = 0;
920 uint8_t *p;
921 uint8_t *q;
922
923 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
924
925 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
926
927 q = image;
928
929 // Convert the mlt frame to an AVPicture
930 for ( i = 0; i < height; i ++ )
931 {
932 p = input->data[ 0 ] + i * input->linesize[ 0 ];
933 j = width;
934 while( j -- )
935 {
936 *p ++ = *q ++;
937 *p ++ = *q ++;
938 }
939 }
940
941 // Do the colour space conversion
942 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUV422, width, height );
943
944 // Apply the alpha if applicable
945 if ( video_st->codec->pix_fmt == PIX_FMT_RGBA32 )
946 {
947 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
948 register int n;
949
950 for ( i = 0; i < height; i ++ )
951 {
952 n = ( width + 7 ) / 8;
953 p = output->data[ 0 ] + i * output->linesize[ 0 ];
954
955 #ifndef __DARWIN__
956 p += 3;
957 #endif
958
959 switch( width % 8 )
960 {
961 case 0: do { *p = *alpha++; p += 4;
962 case 7: *p = *alpha++; p += 4;
963 case 6: *p = *alpha++; p += 4;
964 case 5: *p = *alpha++; p += 4;
965 case 4: *p = *alpha++; p += 4;
966 case 3: *p = *alpha++; p += 4;
967 case 2: *p = *alpha++; p += 4;
968 case 1: *p = *alpha++; p += 4;
969 }
970 while( --n );
971 }
972 }
973 }
974 }
975
976 if (oc->oformat->flags & AVFMT_RAWPICTURE)
977 {
978 // raw video case. The API will change slightly in the near future for that
979 AVPacket pkt;
980 av_init_packet(&pkt);
981
982 pkt.flags |= PKT_FLAG_KEY;
983 pkt.stream_index= video_st->index;
984 pkt.data= (uint8_t *)output;
985 pkt.size= sizeof(AVPicture);
986
987 ret = av_write_frame(oc, &pkt);
988 video_pts += c->frame_size;
989 }
990 else
991 {
992 // Set the quality
993 output->quality = video_st->quality;
994
995 // Encode the image
996 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
997
998 // If zero size, it means the image was buffered
999 if (out_size > 0)
1000 {
1001 AVPacket pkt;
1002 av_init_packet( &pkt );
1003
1004 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1005 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1006 if( c->coded_frame && c->coded_frame->key_frame )
1007 pkt.flags |= PKT_FLAG_KEY;
1008 pkt.stream_index= video_st->index;
1009 pkt.data= video_outbuf;
1010 pkt.size= out_size;
1011
1012 // write the compressed frame in the media file
1013 ret = av_interleaved_write_frame(oc, &pkt);
1014 video_pts += c->frame_size;
1015 }
1016 else
1017 {
1018 fprintf( stderr, "Error with video encode\n" );
1019 }
1020 }
1021 frame_count++;
1022 mlt_frame_close( frame );
1023 }
1024 else
1025 {
1026 break;
1027 }
1028 }
1029 }
1030
1031 if ( real_time_output && frames % 12 == 0 )
1032 {
1033 long passed = time_difference( &ante );
1034 if ( fifo != NULL )
1035 {
1036 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1037 passed -= pending;
1038 }
1039 if ( passed < total_time )
1040 {
1041 long total = ( total_time - passed );
1042 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1043 nanosleep( &t, NULL );
1044 }
1045 }
1046 }
1047
1048 // close each codec
1049 if (video_st)
1050 close_video(oc, video_st);
1051 if (audio_st)
1052 close_audio(oc, audio_st);
1053
1054 // Write the trailer, if any
1055 av_write_trailer(oc);
1056
1057 // Free the streams
1058 for(i = 0; i < oc->nb_streams; i++)
1059 av_freep(&oc->streams[i]);
1060
1061 // Close the output file
1062 if (!(fmt->flags & AVFMT_NOFILE))
1063 url_fclose(&oc->pb);
1064
1065 // Clean up input and output frames
1066 if ( output )
1067 av_free( output->data[0] );
1068 av_free( output );
1069 av_free( input->data[0] );
1070 av_free( input );
1071 av_free( video_outbuf );
1072 av_free( buffer );
1073
1074 // Free the stream
1075 av_free(oc);
1076
1077 // Just in case we terminated on pause
1078 mlt_properties_set_int( properties, "running", 0 );
1079
1080 mlt_consumer_stopped( this );
1081
1082 return NULL;
1083 }
1084
1085 /** Close the consumer.
1086 */
1087
1088 static void consumer_close( mlt_consumer this )
1089 {
1090 // Stop the consumer
1091 mlt_consumer_stop( this );
1092
1093 // Close the parent
1094 mlt_consumer_close( this );
1095
1096 // Free the memory
1097 free( this );
1098 }