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