FFMPEG revisions to match current CVS (part 1)
[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 <pthread.h>
32 #include <sys/time.h>
33 #include <math.h>
34
35 // avformat header files
36 #include <avformat.h>
37
38 //
39 // This structure should be extended and made globally available in mlt
40 //
41
42 typedef struct
43 {
44 int16_t *buffer;
45 int size;
46 int used;
47 double time;
48 int frequency;
49 int channels;
50 }
51 *sample_fifo, sample_fifo_s;
52
53 sample_fifo sample_fifo_init( int frequency, int channels )
54 {
55 sample_fifo this = calloc( 1, sizeof( sample_fifo_s ) );
56 this->frequency = frequency;
57 this->channels = channels;
58 return this;
59 }
60
61 // sample_fifo_clear and check are temporarily aborted (not working as intended)
62
63 void sample_fifo_clear( sample_fifo this, double time )
64 {
65 int words = ( float )( time - this->time ) * this->frequency * this->channels;
66 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) && this->used > words && words > 0 )
67 {
68 memmove( this->buffer, &this->buffer[ words ], ( this->used - words ) * sizeof( int16_t ) );
69 this->used -= words;
70 this->time = time;
71 }
72 else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )this->time * 100 ) )
73 {
74 this->used = 0;
75 this->time = time;
76 }
77 }
78
79 void sample_fifo_check( sample_fifo this, double time )
80 {
81 if ( this->used == 0 )
82 {
83 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) )
84 this->time = time;
85 }
86 }
87
88 void sample_fifo_append( sample_fifo this, int16_t *samples, int count )
89 {
90 if ( ( this->size - this->used ) < count )
91 {
92 this->size += count * 5;
93 this->buffer = realloc( this->buffer, this->size * sizeof( int16_t ) );
94 }
95
96 memcpy( &this->buffer[ this->used ], samples, count * sizeof( int16_t ) );
97 this->used += count;
98 }
99
100 int sample_fifo_used( sample_fifo this )
101 {
102 return this->used;
103 }
104
105 int sample_fifo_fetch( sample_fifo this, int16_t *samples, int count )
106 {
107 if ( count > this->used )
108 count = this->used;
109
110 memcpy( samples, this->buffer, count * sizeof( int16_t ) );
111 this->used -= count;
112 memmove( this->buffer, &this->buffer[ count ], this->used * sizeof( int16_t ) );
113
114 this->time += ( double )count / this->channels / this->frequency;
115
116 return count;
117 }
118
119 void sample_fifo_close( sample_fifo this )
120 {
121 free( this->buffer );
122 free( this );
123 }
124
125 // Forward references.
126 static int consumer_start( mlt_consumer this );
127 static int consumer_stop( mlt_consumer this );
128 static int consumer_is_stopped( mlt_consumer this );
129 static void *consumer_thread( void *arg );
130 static void consumer_close( mlt_consumer this );
131
132 /** Initialise the dv consumer.
133 */
134
135 mlt_consumer consumer_avformat_init( char *arg )
136 {
137 // Allocate the consumer
138 mlt_consumer this = mlt_consumer_new( );
139
140 // If memory allocated and initialises without error
141 if ( this != NULL )
142 {
143 // Get properties from the consumer
144 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
145
146 // Assign close callback
147 this->close = consumer_close;
148
149 // Interpret the argument
150 if ( arg != NULL )
151 mlt_properties_set( properties, "target", arg );
152
153 // sample and frame queue
154 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
155
156 // Set avformat defaults (all lifted from ffmpeg.c)
157 mlt_properties_set_int( properties, "audio_bit_rate", 128000 );
158 mlt_properties_set_int( properties, "video_bit_rate", 200 * 1000 );
159 mlt_properties_set_int( properties, "video_bit_rate_tolerance", 4000 * 1000 );
160 mlt_properties_set_int( properties, "frame_rate_base", 1 );
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", 0 );
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 else
335 {
336 fprintf( stderr, "Could not allocate a stream for audio\n" );
337 }
338
339 return st;
340 }
341
342 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
343 {
344 // We will return the audio input size from here
345 int audio_input_frame_size = 0;
346
347 // Get the context
348 AVCodecContext *c = &st->codec;
349
350 // Find the encoder
351 AVCodec *codec = avcodec_find_encoder( c->codec_id );
352
353 // Continue if codec found and we can open it
354 if ( codec != NULL && avcodec_open(c, codec) >= 0 )
355 {
356 // ugly hack for PCM codecs (will be removed ASAP with new PCM
357 // support to compute the input frame size in samples
358 if ( c->frame_size <= 1 )
359 {
360 audio_input_frame_size = audio_outbuf_size / c->channels;
361 switch(st->codec.codec_id)
362 {
363 case CODEC_ID_PCM_S16LE:
364 case CODEC_ID_PCM_S16BE:
365 case CODEC_ID_PCM_U16LE:
366 case CODEC_ID_PCM_U16BE:
367 audio_input_frame_size >>= 1;
368 break;
369 default:
370 break;
371 }
372 }
373 else
374 {
375 audio_input_frame_size = c->frame_size;
376 }
377
378 // Some formats want stream headers to be seperate (hmm)
379 if( !strcmp( oc->oformat->name, "mp4" ) ||
380 !strcmp( oc->oformat->name, "mov" ) ||
381 !strcmp( oc->oformat->name, "3gp" ) )
382 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
383 }
384 else
385 {
386 fprintf( stderr, "Unable to encode audio - disabling audio output.\n" );
387 }
388
389 return audio_input_frame_size;
390 }
391
392 static void close_audio( AVFormatContext *oc, AVStream *st )
393 {
394 avcodec_close( &st->codec );
395 }
396
397 /** Add a video output stream
398 */
399
400 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
401 {
402 // Get the properties
403 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
404
405 // Create a new stream
406 AVStream *st = av_new_stream( oc, 0 );
407
408 if ( st != NULL )
409 {
410 AVCodecContext *c = &st->codec;
411 c->codec_id = codec_id;
412 c->codec_type = CODEC_TYPE_VIDEO;
413
414 // put sample parameters
415 c->bit_rate = mlt_properties_get_int( properties, "video_bit_rate" );
416 c->bit_rate_tolerance = mlt_properties_get_int( properties, "video_bit_rate_tolerance" );
417 c->width = mlt_properties_get_int( properties, "width" );
418 c->height = mlt_properties_get_int( properties, "height" );
419 c->time_base.den = mlt_properties_get_double( properties, "fps" );
420 c->time_base.num = mlt_properties_get_double( properties, "frame_rate_base" );
421 c->time_base.num = 1;
422 c->gop_size = mlt_properties_get_int( properties, "gop_size" );
423 c->pix_fmt = PIX_FMT_YUV420P;
424
425 if ( mlt_properties_get_int( properties, "b_frames" ) )
426 {
427 c->max_b_frames = mlt_properties_get_int( properties, "b_frames" );
428 c->b_frame_strategy = 0;
429 c->b_quant_factor = 2.0;
430 }
431
432 c->mb_decision = mlt_properties_get_int( properties, "mb_decision" );
433 c->sample_aspect_ratio = av_d2q( mlt_properties_get_double( properties, "aspect_ratio" ), 255 );
434 c->mb_cmp = mlt_properties_get_int( properties, "mb_cmp" );
435 c->ildct_cmp = mlt_properties_get_int( properties, "ildct_cmp" );
436 c->me_sub_cmp = mlt_properties_get_int( properties, "sub_cmp" );
437 c->me_cmp = mlt_properties_get_int( properties, "cmp" );
438 c->me_pre_cmp = mlt_properties_get_int( properties, "pre_cmp" );
439 c->pre_me = mlt_properties_get_int( properties, "pre_me" );
440 c->lumi_masking = mlt_properties_get_double( properties, "lumi_mask" );
441 c->dark_masking = mlt_properties_get_double( properties, "dark_mask" );
442 c->spatial_cplx_masking = mlt_properties_get_double( properties, "scplx_mask" );
443 c->temporal_cplx_masking = mlt_properties_get_double( properties, "tcplx_mask" );
444 c->p_masking = mlt_properties_get_double( properties, "p_mask" );
445 c->quantizer_noise_shaping= mlt_properties_get_int( properties, "qns" );
446 c->qmin = mlt_properties_get_int( properties, "video_qmin" );
447 c->qmax = mlt_properties_get_int( properties, "video_qmax" );
448 c->lmin = mlt_properties_get_int( properties, "video_lmin" );
449 c->lmax = mlt_properties_get_int( properties, "video_lmax" );
450 c->mb_qmin = mlt_properties_get_int( properties, "video_mb_qmin" );
451 c->mb_qmax = mlt_properties_get_int( properties, "video_mb_qmax" );
452 c->max_qdiff = mlt_properties_get_int( properties, "video_qdiff" );
453 c->qblur = mlt_properties_get_double( properties, "video_qblur" );
454 c->qcompress = mlt_properties_get_double( properties, "video_qcomp" );
455
456 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
457 {
458 c->flags |= CODEC_FLAG_QSCALE;
459 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
460 }
461
462 // Some formats want stream headers to be seperate (hmm)
463 if( !strcmp( oc->oformat->name, "mp4" ) ||
464 !strcmp( oc->oformat->name, "mov" ) ||
465 !strcmp( oc->oformat->name, "3gp" ) )
466 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
467
468 c->rc_max_rate = mlt_properties_get_int( properties, "video_rc_max_rate" );
469 c->rc_min_rate = mlt_properties_get_int( properties, "video_rc_min_rate" );
470 c->rc_buffer_size = mlt_properties_get_int( properties, "video_rc_buffer_size" );
471 c->rc_buffer_aggressivity= mlt_properties_get_double( properties, "video_rc_buffer_aggressivity" );
472 c->rc_initial_cplx= mlt_properties_get_double( properties, "video_rc_initial_cplx" );
473 c->i_quant_factor = mlt_properties_get_double( properties, "video_i_qfactor" );
474 c->b_quant_factor = mlt_properties_get_double( properties, "video_b_qfactor" );
475 c->i_quant_offset = mlt_properties_get_double( properties, "video_i_qoffset" );
476 c->b_quant_offset = mlt_properties_get_double( properties, "video_b_qoffset" );
477 c->intra_quant_bias = mlt_properties_get_int( properties, "video_intra_quant_bias" );
478 c->inter_quant_bias = mlt_properties_get_int( properties, "video_inter_quant_bias" );
479 c->dct_algo = mlt_properties_get_int( properties, "dct_algo" );
480 c->idct_algo = mlt_properties_get_int( properties, "idct_algo" );
481 c->me_threshold= mlt_properties_get_int( properties, "me_threshold" );
482 c->mb_threshold= mlt_properties_get_int( properties, "mb_threshold" );
483 c->intra_dc_precision= mlt_properties_get_int( properties, "intra_dc_precision" );
484 c->strict_std_compliance = mlt_properties_get_int( properties, "strict" );
485 c->error_rate = mlt_properties_get_int( properties, "error_rate" );
486 c->noise_reduction= mlt_properties_get_int( properties, "noise_reduction" );
487 c->scenechange_threshold= mlt_properties_get_int( properties, "sc_threshold" );
488 c->me_range = mlt_properties_get_int( properties, "me_range" );
489 c->coder_type= mlt_properties_get_int( properties, "coder" );
490 c->context_model= mlt_properties_get_int( properties, "context" );
491 c->prediction_method= mlt_properties_get_int( properties, "predictor" );
492 c->me_method = mlt_properties_get_int( properties, "me_method" );
493 }
494 else
495 {
496 fprintf( stderr, "Could not allocate a stream for video\n" );
497 }
498
499 return st;
500 }
501
502 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
503 {
504 // Allocate a frame
505 AVFrame *picture = avcodec_alloc_frame();
506
507 // Determine size of the
508 int size = avpicture_get_size(pix_fmt, width, height);
509
510 // Allocate the picture buf
511 uint8_t *picture_buf = av_malloc(size);
512
513 // If we have both, then fill the image
514 if ( picture != NULL && picture_buf != NULL )
515 {
516 // Fill the frame with the allocated buffer
517 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
518 }
519 else
520 {
521 // Something failed - clean up what we can
522 av_free( picture );
523 av_free( picture_buf );
524 picture = NULL;
525 }
526
527 return picture;
528 }
529
530 static int open_video(AVFormatContext *oc, AVStream *st)
531 {
532 // Get the codec
533 AVCodecContext *c = &st->codec;
534
535 // find the video encoder
536 AVCodec *codec = avcodec_find_encoder(c->codec_id);
537
538 // Open the codec safely
539 return codec != NULL && avcodec_open(c, codec) >= 0;
540 }
541
542 void close_video(AVFormatContext *oc, AVStream *st)
543 {
544 avcodec_close(&st->codec);
545 }
546
547 static inline long time_difference( struct timeval *time1 )
548 {
549 struct timeval time2;
550 gettimeofday( &time2, NULL );
551 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
552 }
553
554 /** The main thread - the argument is simply the consumer.
555 */
556
557 static void *consumer_thread( void *arg )
558 {
559 // Map the argument to the object
560 mlt_consumer this = arg;
561
562 // Get the properties
563 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
564
565 // Get the terminate on pause property
566 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
567 int terminated = 0;
568
569 // Determine if feed is slow (for realtime stuff)
570 int real_time_output = mlt_properties_get_int( properties, "real_time" );
571
572 // Time structures
573 struct timeval ante;
574
575 // Get the frame rate
576 int fps = mlt_properties_get_double( properties, "fps" );
577
578 // Get width and height
579 int width = mlt_properties_get_int( properties, "width" );
580 int height = mlt_properties_get_int( properties, "height" );
581 int img_width = width;
582 int img_height = height;
583
584 // Get default audio properties
585 mlt_audio_format aud_fmt = mlt_audio_pcm;
586 int channels = mlt_properties_get_int( properties, "channels" );
587 int frequency = mlt_properties_get_int( properties, "frequency" );
588 int16_t *pcm = NULL;
589 int samples = 0;
590
591 // AVFormat audio buffer and frame size
592 int audio_outbuf_size = 10000;
593 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
594 int audio_input_frame_size = 0;
595
596 // AVFormat video buffer and frame count
597 int frame_count = 0;
598 int video_outbuf_size = ( 1024 * 1024 );
599 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
600
601 // Used for the frame properties
602 mlt_frame frame = NULL;
603 mlt_properties frame_properties = NULL;
604
605 // Get the queues
606 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
607 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
608
609 // Need two av pictures for converting
610 AVFrame *output = alloc_picture( PIX_FMT_YUV420P, width, height );
611 AVFrame *input = alloc_picture( PIX_FMT_YUV422, width, height );
612
613 // For receiving images from an mlt_frame
614 uint8_t *image;
615 mlt_image_format img_fmt = mlt_image_yuv422;
616
617 // For receiving audio samples back from the fifo
618 int16_t *buffer = av_malloc( 48000 * 2 );
619 int count = 0;
620
621 // Allocate the context
622 AVFormatContext *oc = av_alloc_format_context( );
623
624 // Streams
625 AVStream *audio_st = NULL;
626 AVStream *video_st = NULL;
627
628 // Time stamps
629 double audio_pts = 0;
630 double video_pts = 0;
631
632 // Loop variable
633 int i;
634
635 // Frames despatched
636 long int frames = 0;
637 long int total_time = 0;
638
639 // Determine the format
640 AVOutputFormat *fmt = NULL;
641 char *filename = mlt_properties_get( properties, "target" );
642 char *format = mlt_properties_get( properties, "format" );
643 char *vcodec = mlt_properties_get( properties, "vcodec" );
644 char *acodec = mlt_properties_get( properties, "acodec" );
645
646 // Used to store and override codec ids
647 int audio_codec_id;
648 int video_codec_id;
649
650 // Check for user selected format first
651 if ( format != NULL )
652 fmt = guess_format( format, NULL, NULL );
653
654 // Otherwise check on the filename
655 if ( fmt == NULL && filename != NULL )
656 fmt = guess_format( NULL, filename, NULL );
657
658 // Otherwise default to mpeg
659 if ( fmt == NULL )
660 fmt = guess_format( "mpeg", NULL, NULL );
661
662 // We need a filename - default to stdout?
663 if ( filename == NULL || !strcmp( filename, "" ) )
664 filename = "pipe:";
665
666 // Get the codec ids selected
667 audio_codec_id = fmt->audio_codec;
668 video_codec_id = fmt->video_codec;
669
670 // Check for audio codec overides
671 if ( acodec != NULL )
672 {
673 AVCodec *p = first_avcodec;
674 while( p != NULL )
675 {
676 if ( !strcmp( p->name, acodec ) && p->type == CODEC_TYPE_AUDIO )
677 break;
678 p = p->next;
679 }
680 if ( p != NULL )
681 audio_codec_id = p->id;
682 else
683 fprintf( stderr, "consumer_avcodec: audio codec %s unrecognised - ignoring\n", acodec );
684 }
685
686 // Check for video codec overides
687 if ( vcodec != NULL )
688 {
689 AVCodec *p = first_avcodec;
690 while( p != NULL )
691 {
692 if ( !strcmp( p->name, vcodec ) && p->type == CODEC_TYPE_VIDEO )
693 break;
694 p = p->next;
695 }
696 if ( p != NULL )
697 video_codec_id = p->id;
698 else
699 fprintf( stderr, "consumer_avcodec: video codec %s unrecognised - ignoring\n", vcodec );
700 }
701
702 // Update the output context
703 oc->oformat = fmt;
704 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
705
706 // Add audio and video streams
707 if ( fmt->video_codec != CODEC_ID_NONE )
708 video_st = add_video_stream( this, oc, video_codec_id );
709 if ( fmt->audio_codec != CODEC_ID_NONE )
710 audio_st = add_audio_stream( this, oc, audio_codec_id );
711
712 // Set the parameters (even though we have none...)
713 if ( av_set_parameters(oc, NULL) >= 0 )
714 {
715 if ( video_st && !open_video( oc, video_st ) )
716 video_st = NULL;
717 if ( audio_st )
718 audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
719
720 // Open the output file, if needed
721 if ( !( fmt->flags & AVFMT_NOFILE ) )
722 {
723 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0)
724 {
725 fprintf(stderr, "Could not open '%s'\n", filename);
726 mlt_properties_set_int( properties, "running", 0 );
727 }
728 }
729
730 // Write the stream header, if any
731 if ( mlt_properties_get_int( properties, "running" ) )
732 av_write_header( oc );
733 }
734 else
735 {
736 fprintf(stderr, "Invalid output format parameters\n");
737 mlt_properties_set_int( properties, "running", 0 );
738 }
739
740 // Last check - need at least one stream
741 if ( audio_st == NULL && video_st == NULL )
742 mlt_properties_set_int( properties, "running", 0 );
743
744 // Get the starting time (can ignore the times above)
745 gettimeofday( &ante, NULL );
746
747 // Loop while running
748 while( mlt_properties_get_int( properties, "running" ) && !terminated )
749 {
750 // Get the frame
751 frame = mlt_consumer_rt_frame( this );
752
753 // Check that we have a frame to work with
754 if ( frame != NULL )
755 {
756 // Increment frames despatched
757 frames ++;
758
759 // Default audio args
760 frame_properties = MLT_FRAME_PROPERTIES( frame );
761
762 // Check for the terminated condition
763 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
764
765 // Get audio and append to the fifo
766 if ( audio_st )
767 {
768 samples = mlt_sample_calculator( fps, frequency, count );
769 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
770
771 // Create the fifo if we don't have one
772 if ( fifo == NULL )
773 {
774 fifo = sample_fifo_init( frequency, channels );
775 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
776 }
777
778 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
779 memset( pcm, 0, samples * channels * 2 );
780
781 // Append the samples
782 sample_fifo_append( fifo, pcm, samples * channels );
783 total_time += ( samples * 1000000 ) / frequency;
784 }
785
786 // Encode the image
787 if ( video_st )
788 mlt_deque_push_back( queue, frame );
789 else
790 mlt_frame_close( frame );
791 }
792
793 // While we have stuff to process, process...
794 while ( 1 )
795 {
796 if (audio_st)
797 audio_pts = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;
798 else
799 audio_pts = 0.0;
800
801 if (video_st)
802 video_pts = (double)video_st->pts.val * video_st->time_base.num / video_st->time_base.den;
803 else
804 video_pts = 0.0;
805
806 // Write interleaved audio and video frames
807 if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
808 {
809 if ( channels * audio_input_frame_size < sample_fifo_used( fifo ) )
810 {
811 AVCodecContext *c;
812 AVPacket pkt;
813 av_init_packet( &pkt );
814
815 c = &audio_st->codec;
816
817 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
818
819 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
820 // Write the compressed frame in the media file
821 if ( c->coded_frame )
822 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
823 pkt.flags |= PKT_FLAG_KEY;
824 pkt.stream_index= audio_st->index;
825 pkt.data= audio_outbuf;
826
827 if ( av_interleaved_write_frame( oc, &pkt ) != 0)
828 fprintf(stderr, "Error while writing audio frame\n");
829
830 audio_pts += c->frame_size;
831 }
832 else
833 {
834 break;
835 }
836 }
837 else if ( video_st )
838 {
839 if ( mlt_deque_count( queue ) )
840 {
841 int out_size, ret;
842 AVCodecContext *c;
843
844 frame = mlt_deque_pop_front( queue );
845 frame_properties = MLT_FRAME_PROPERTIES( frame );
846
847 c = &video_st->codec;
848
849 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
850 {
851 int i = 0;
852 int j = 0;
853 uint8_t *p;
854 uint8_t *q;
855
856 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
857
858 // This will cause some fx to go awry....
859 if ( mlt_properties_get_int( properties, "transcode" ) )
860 {
861 mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "normalised_width", img_height * 4.0 / 3.0 );
862 mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "normalised_height", img_height );
863 }
864
865 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
866
867 q = image;
868
869 for ( i = 0; i < height; i ++ )
870 {
871 p = input->data[ 0 ] + i * input->linesize[ 0 ];
872 j = width;
873 while( j -- )
874 {
875 *p ++ = *q ++;
876 *p ++ = *q ++;
877 }
878 }
879
880 img_convert( ( AVPicture * )output, PIX_FMT_YUV420P, ( AVPicture * )input, PIX_FMT_YUV422, width, height );
881 }
882
883 if (oc->oformat->flags & AVFMT_RAWPICTURE)
884 {
885 // raw video case. The API will change slightly in the near future for that
886 AVPacket pkt;
887 av_init_packet(&pkt);
888
889 pkt.flags |= PKT_FLAG_KEY;
890 pkt.stream_index= video_st->index;
891 pkt.data= (uint8_t *)output;
892 pkt.size= sizeof(AVPicture);
893
894 ret = av_write_frame(oc, &pkt);
895 video_pts += c->frame_size;
896 }
897 else
898 {
899 // Set the quality
900 output->quality = video_st->quality;
901
902 // Encode the image
903 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
904
905 // If zero size, it means the image was buffered
906 if (out_size != 0)
907 {
908 AVPacket pkt;
909 av_init_packet( &pkt );
910
911 if ( c->coded_frame )
912 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
913 if(c->coded_frame->key_frame)
914 pkt.flags |= PKT_FLAG_KEY;
915 pkt.stream_index= video_st->index;
916 pkt.data= video_outbuf;
917 pkt.size= out_size;
918
919 // write the compressed frame in the media file
920 ret = av_interleaved_write_frame(oc, &pkt);
921 video_pts += c->frame_size;
922 }
923 }
924 frame_count++;
925 mlt_frame_close( frame );
926 }
927 else
928 {
929 break;
930 }
931 }
932 }
933
934 if ( real_time_output && frames % 12 == 0 )
935 {
936 long passed = time_difference( &ante );
937 if ( fifo != NULL )
938 {
939 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
940 passed -= pending;
941 }
942 if ( passed < total_time )
943 {
944 long total = ( total_time - passed );
945 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
946 nanosleep( &t, NULL );
947 }
948 }
949 }
950
951 // close each codec
952 if (video_st)
953 close_video(oc, video_st);
954 if (audio_st)
955 close_audio(oc, audio_st);
956
957 // Write the trailer, if any
958 av_write_trailer(oc);
959
960 // Free the streams
961 for(i = 0; i < oc->nb_streams; i++)
962 av_freep(&oc->streams[i]);
963
964 // Close the output file
965 if (!(fmt->flags & AVFMT_NOFILE))
966 url_fclose(&oc->pb);
967
968 // Clean up input and output frames
969 av_free( output->data[0] );
970 av_free( output );
971 av_free( input->data[0] );
972 av_free( input );
973 av_free( video_outbuf );
974 av_free( buffer );
975
976 // Free the stream
977 av_free(oc);
978
979 // Just in case we terminated on pause
980 mlt_properties_set_int( properties, "running", 0 );
981
982 mlt_consumer_stopped( this );
983
984 return NULL;
985 }
986
987 /** Close the consumer.
988 */
989
990 static void consumer_close( mlt_consumer this )
991 {
992 // Stop the consumer
993 mlt_consumer_stop( this );
994
995 // Close the parent
996 mlt_consumer_close( this );
997
998 // Free the memory
999 free( this );
1000 }