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