]> git.sesse.net Git - mlt/blob - src/modules/avformat/consumer_avformat.c
fbe91e89e020c8d354fca84e961e0fccac14e85a
[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  * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 // mlt Header files
23 #include <framework/mlt_consumer.h>
24 #include <framework/mlt_frame.h>
25
26 // System header files
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <limits.h>
31 #include <pthread.h>
32 #include <sys/time.h>
33 #include <math.h>
34
35 // avformat header files
36 #include <avformat.h>
37 #ifdef SWSCALE
38 #include <swscale.h>
39 #endif
40 #include <opt.h>
41
42 //
43 // This structure should be extended and made globally available in mlt
44 //
45
46 typedef struct
47 {
48         int16_t *buffer;
49         int size;
50         int used;
51         double time;
52         int frequency;
53         int channels;
54 }
55 *sample_fifo, sample_fifo_s;
56
57 sample_fifo sample_fifo_init( int frequency, int channels )
58 {
59         sample_fifo this = calloc( 1, sizeof( sample_fifo_s ) );
60         this->frequency = frequency;
61         this->channels = channels;
62         return this;
63 }
64
65 // sample_fifo_clear and check are temporarily aborted (not working as intended)
66
67 void sample_fifo_clear( sample_fifo this, double time )
68 {
69         int words = ( float )( time - this->time ) * this->frequency * this->channels;
70         if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) && this->used > words && words > 0 )
71         {
72                 memmove( this->buffer, &this->buffer[ words ], ( this->used - words ) * sizeof( int16_t ) );
73                 this->used -= words;
74                 this->time = time;
75         }
76         else if ( ( int )( ( float )time * 100 ) != ( int )( ( float )this->time * 100 ) )
77         {
78                 this->used = 0;
79                 this->time = time;
80         }
81 }
82
83 void sample_fifo_check( sample_fifo this, double time )
84 {
85         if ( this->used == 0 )
86         {
87                 if ( ( int )( ( float )time * 100 ) < ( int )( ( float )this->time * 100 ) )
88                         this->time = time;
89         }
90 }
91
92 void sample_fifo_append( sample_fifo this, int16_t *samples, int count )
93 {
94         if ( ( this->size - this->used ) < count )
95         {
96                 this->size += count * 5;
97                 this->buffer = realloc( this->buffer, this->size * sizeof( int16_t ) );
98         }
99
100         memcpy( &this->buffer[ this->used ], samples, count * sizeof( int16_t ) );
101         this->used += count;
102 }
103
104 int sample_fifo_used( sample_fifo this )
105 {
106         return this->used;
107 }
108
109 int sample_fifo_fetch( sample_fifo this, int16_t *samples, int count )
110 {
111         if ( count > this->used )
112                 count = this->used;
113
114         memcpy( samples, this->buffer, count * sizeof( int16_t ) );
115         this->used -= count;
116         memmove( this->buffer, &this->buffer[ count ], this->used * sizeof( int16_t ) );
117
118         this->time += ( double )count / this->channels / this->frequency;
119
120         return count;
121 }
122
123 void sample_fifo_close( sample_fifo this )
124 {
125         free( this->buffer );
126         free( this );
127 }
128
129 // Forward references.
130 static int consumer_start( mlt_consumer this );
131 static int consumer_stop( mlt_consumer this );
132 static int consumer_is_stopped( mlt_consumer this );
133 static void *consumer_thread( void *arg );
134 static void consumer_close( mlt_consumer this );
135
136 /** Initialise the dv consumer.
137 */
138
139 mlt_consumer consumer_avformat_init( mlt_profile profile, char *arg )
140 {
141         // Allocate the consumer
142         mlt_consumer this = mlt_consumer_new( profile );
143
144         // If memory allocated and initialises without error
145         if ( this != NULL )
146         {
147                 // Get properties from the consumer
148                 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
149
150                 // Assign close callback
151                 this->close = consumer_close;
152
153                 // Interpret the argument
154                 if ( arg != NULL )
155                         mlt_properties_set( properties, "target", arg );
156
157                 // sample and frame queue
158                 mlt_properties_set_data( properties, "frame_queue", mlt_deque_init( ), 0, ( mlt_destructor )mlt_deque_close, NULL );
159
160                 // Audio options not fully handled by AVOptions
161 #define QSCALE_NONE (-99999)
162                 mlt_properties_set_int( properties, "aq", QSCALE_NONE );
163                 
164                 // Video options not fully handled by AVOptions
165                 mlt_properties_set_int( properties, "dc", 8 );
166                 
167                 // Muxer options not fully handled by AVOptions
168                 mlt_properties_set_double( properties, "muxdelay", 0.7 );
169                 mlt_properties_set_double( properties, "muxpreload", 0.5 );
170
171                 // Ensure termination at end of the stream
172                 mlt_properties_set_int( properties, "terminate_on_pause", 1 );
173                 
174                 // Default to separate processing threads for producer and consumer with no frame dropping!
175                 mlt_properties_set_int( properties, "real_time", -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
201                 // Get the width and height
202                 int width = mlt_properties_get_int( properties, "width" );
203                 int height = mlt_properties_get_int( properties, "height" );
204
205                 // Obtain the size property
206                 char *size = mlt_properties_get( properties, "s" );
207
208                 // Interpret it
209                 if ( size != NULL )
210                 {
211                         int tw, th;
212                         if ( sscanf( size, "%dx%d", &tw, &th ) == 2 && tw > 0 && th > 0 )
213                         {
214                                 width = tw;
215                                 height = th;
216                         }
217                         else
218                         {
219                                 fprintf( stderr, "%s: Invalid size property %s - ignoring.\n", __FILE__, size );
220                         }
221                 }
222                 
223                 // Now ensure we honour the multiple of two requested by libavformat
224                 mlt_properties_set_int( properties, "width", ( width / 2 ) * 2 );
225                 mlt_properties_set_int( properties, "height", ( height / 2 ) * 2 );
226                 
227                 // Apply AVOptions that are synonyms for standard mlt_consumer options
228                 if ( mlt_properties_get( properties, "ac" ) )
229                         mlt_properties_set_int( properties, "channels", mlt_properties_get_int( properties, "ac" ) );
230                 if ( mlt_properties_get( properties, "ar" ) )
231                         mlt_properties_set_int( properties, "frequency", mlt_properties_get_int( properties, "ar" ) );
232
233                 // Assign the thread to properties
234                 mlt_properties_set_data( properties, "thread", thread, sizeof( pthread_t ), free, NULL );
235
236                 // Set the running state
237                 mlt_properties_set_int( properties, "running", 1 );
238
239                 // Create the thread
240                 pthread_create( thread, NULL, consumer_thread, this );
241         }
242         return 0;
243 }
244
245 /** Stop the consumer.
246 */
247
248 static int consumer_stop( mlt_consumer this )
249 {
250         // Get the properties
251         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
252
253         // Check that we're running
254         if ( mlt_properties_get_int( properties, "running" ) )
255         {
256                 // Get the thread
257                 pthread_t *thread = mlt_properties_get_data( properties, "thread", NULL );
258
259                 // Stop the thread
260                 mlt_properties_set_int( properties, "running", 0 );
261
262                 // Wait for termination
263                 pthread_join( *thread, NULL );
264         }
265
266         return 0;
267 }
268
269 /** Determine if the consumer is stopped.
270 */
271
272 static int consumer_is_stopped( mlt_consumer this )
273 {
274         // Get the properties
275         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
276         return !mlt_properties_get_int( properties, "running" );
277 }
278
279 /** Process properties as AVOptions and apply to AV context obj
280 */
281
282 static void apply_properties( void *obj, mlt_properties properties, int flags )
283 {
284         int i;
285         int count = mlt_properties_count( properties ); 
286         for ( i = 0; i < count; i++ )
287         {
288                 const char *opt_name = mlt_properties_get_name( properties, i );
289                 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
290                 if ( opt != NULL )
291                         av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
292         }
293 }
294
295 /** Add an audio output stream
296 */
297
298 static AVStream *add_audio_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
299 {
300         // Get the properties
301         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
302
303         // Create a new stream
304         AVStream *st = av_new_stream( oc, 1 );
305
306         // If created, then initialise from properties
307         if ( st != NULL ) 
308         {
309                 AVCodecContext *c = st->codec;
310
311                 // Establish defaults from AVOptions
312                 avcodec_get_context_defaults2( c, CODEC_TYPE_AUDIO );
313
314                 c->codec_id = codec_id;
315                 c->codec_type = CODEC_TYPE_AUDIO;
316
317                 // Setup multi-threading
318                 int thread_count = mlt_properties_get_int( properties, "threads" );
319                 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
320                         thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
321                 if ( thread_count > 1 )
322                         avcodec_thread_init( c, thread_count );         
323         
324                 if (oc->oformat->flags & AVFMT_GLOBALHEADER) 
325                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
326                 
327                 // Allow the user to override the audio fourcc
328                 if ( mlt_properties_get( properties, "atag" ) )
329                 {
330                         char *tail = NULL;
331                         char *arg = mlt_properties_get( properties, "atag" );
332                         int tag = strtol( arg, &tail, 0);
333                         if( !tail || *tail )
334                                 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
335                         c->codec_tag = tag;
336                 }
337
338                 // Process properties as AVOptions
339                 apply_properties( c, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
340
341                 int audio_qscale = mlt_properties_get_int( properties, "aq" );
342         if ( audio_qscale > QSCALE_NONE )
343                 {
344                         c->flags |= CODEC_FLAG_QSCALE;
345                         c->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
346                 }
347
348                 // Set parameters controlled by MLT
349                 c->sample_rate = mlt_properties_get_int( properties, "frequency" );
350                 c->channels = mlt_properties_get_int( properties, "channels" );
351
352                 if ( mlt_properties_get( properties, "alang" ) != NULL )
353                         strncpy( st->language, mlt_properties_get( properties, "alang" ), sizeof( st->language ) );
354         }
355         else
356         {
357                 fprintf( stderr, "%s: Could not allocate a stream for audio\n", __FILE__ );
358         }
359
360         return st;
361 }
362
363 static int open_audio( AVFormatContext *oc, AVStream *st, int audio_outbuf_size )
364 {
365         // We will return the audio input size from here
366         int audio_input_frame_size = 0;
367
368         // Get the context
369         AVCodecContext *c = st->codec;
370
371         // Find the encoder
372         AVCodec *codec = avcodec_find_encoder( c->codec_id );
373
374         // Continue if codec found and we can open it
375         if ( codec != NULL && avcodec_open( c, codec ) >= 0 )
376         {
377                 // ugly hack for PCM codecs (will be removed ASAP with new PCM
378                 // support to compute the input frame size in samples
379                 if ( c->frame_size <= 1 ) 
380                 {
381                         audio_input_frame_size = audio_outbuf_size / c->channels;
382                         switch(st->codec->codec_id) 
383                         {
384                                 case CODEC_ID_PCM_S16LE:
385                                 case CODEC_ID_PCM_S16BE:
386                                 case CODEC_ID_PCM_U16LE:
387                                 case CODEC_ID_PCM_U16BE:
388                                         audio_input_frame_size >>= 1;
389                                         break;
390                                 default:
391                                         break;
392                         }
393                 } 
394                 else 
395                 {
396                         audio_input_frame_size = c->frame_size;
397                 }
398
399                 // Some formats want stream headers to be seperate (hmm)
400                 if( !strcmp( oc->oformat->name, "mp4" ) || 
401                         !strcmp( oc->oformat->name, "mov" ) || 
402                         !strcmp( oc->oformat->name, "3gp" ) )
403                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
404         }
405         else
406         {
407                 fprintf( stderr, "%s: Unable to encode audio - disabling audio output.\n", __FILE__ );
408         }
409
410         return audio_input_frame_size;
411 }
412
413 static void close_audio( AVFormatContext *oc, AVStream *st )
414 {
415         avcodec_close( st->codec );
416 }
417
418 /** Add a video output stream 
419 */
420
421 static AVStream *add_video_stream( mlt_consumer this, AVFormatContext *oc, int codec_id )
422 {
423         // Get the properties
424         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
425
426         // Create a new stream
427         AVStream *st = av_new_stream( oc, 0 );
428
429         if ( st != NULL ) 
430         {
431                 char *pix_fmt = mlt_properties_get( properties, "pix_fmt" );
432                 AVCodecContext *c = st->codec;
433
434                 // Establish defaults from AVOptions
435                 avcodec_get_context_defaults2( c, CODEC_TYPE_VIDEO );
436
437                 c->codec_id = codec_id;
438                 c->codec_type = CODEC_TYPE_VIDEO;
439                 
440                 // Setup multi-threading
441                 int thread_count = mlt_properties_get_int( properties, "threads" );
442                 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
443                         thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
444                 if ( thread_count > 1 )
445                         avcodec_thread_init( c, thread_count );         
446         
447                 // Process properties as AVOptions
448                 apply_properties( c, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM );
449
450                 // Set options controlled by MLT
451                 c->width = mlt_properties_get_int( properties, "width" );
452                 c->height = mlt_properties_get_int( properties, "height" );
453                 c->time_base.num = mlt_properties_get_int( properties, "frame_rate_den" );
454                 c->time_base.den = mlt_properties_get_int( properties, "frame_rate_num" );
455                 c->pix_fmt = pix_fmt ? avcodec_get_pix_fmt( pix_fmt ) : PIX_FMT_YUV420P;
456
457                 if ( codec_id == CODEC_ID_DVVIDEO )
458                 {
459                         // Compensate for FFmpeg's notion of DV aspect ratios, which are
460                         // based upon a width of 704. Since we do not have a normaliser
461                         // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
462                         // we just coerce the values to facilitate a passive behaviour through
463                         // the rescale normaliser when using equivalent producers and consumers.
464                         // = display_aspect / (width * height)
465                         double ar = mlt_properties_get_double( properties, "aspect_ratio" );
466                         if ( ar == 8.0/9.0 )  // 4:3 NTSC
467                         {
468                                 c->sample_aspect_ratio.num = 10;
469                                 c->sample_aspect_ratio.den = 11;
470                         }
471                         else if ( ar == 16.0/15.0 ) // 4:3 PAL
472                         {
473                                 c->sample_aspect_ratio.num = 159;
474                                 c->sample_aspect_ratio.den = 54;
475                         }
476                         else if ( ar == 32.0/27.0 ) // 16:9 NTSC
477                         {
478                                 c->sample_aspect_ratio.num = 40;
479                                 c->sample_aspect_ratio.den = 33;
480                         }
481                         else // 16:9 PAL
482                         {
483                                 c->sample_aspect_ratio.num = 118;
484                                 c->sample_aspect_ratio.den = 81;
485                         }
486                 }
487                 else if ( mlt_properties_get( properties, "aspect" ) )
488                 {
489                         double ar = mlt_properties_get_double( properties, "aspect" );
490                         c->sample_aspect_ratio = av_d2q( ar * c->height / c->width , 255);
491                 }
492                 else
493                 {
494                         c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
495                         c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
496                 }
497
498                 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
499                 {
500                         c->flags |= CODEC_FLAG_QSCALE;
501                         st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
502                 }
503
504                 // Allow the user to override the video fourcc
505                 if ( mlt_properties_get( properties, "vtag" ) )
506                 {
507                         char *tail = NULL;
508                         const char *arg = mlt_properties_get( properties, "vtag" );
509                         int tag = strtol( arg, &tail, 0);
510                         if( !tail || *tail )
511                                 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
512                         c->codec_tag = tag;
513                 }
514
515                 // Some formats want stream headers to be seperate
516                 if ( oc->oformat->flags & AVFMT_GLOBALHEADER ) 
517                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;
518
519                 // Translate these standard mlt consumer properties to ffmpeg
520                 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
521                      mlt_properties_get_int( properties, "deinterlace" ) == 0 )
522                 {
523                         if ( mlt_properties_get_int( properties, "ildct" ) )
524                                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
525                         if ( mlt_properties_get_int( properties, "ilme" ) )
526                                 c->flags |= CODEC_FLAG_INTERLACED_ME;
527                 }
528                 
529                 // parse the ratecontrol override string
530                 int i;
531                 char *rc_override = mlt_properties_get( properties, "rc_override" );
532                 for ( i = 0; rc_override; i++ )
533                 {
534                         int start, end, q;
535                         int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
536                         if ( e != 3 )
537                                 fprintf( stderr, "%s: Error parsing rc_override\n", __FILE__ );
538                         c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
539                         c->rc_override[i].start_frame = start;
540                         c->rc_override[i].end_frame = end;
541                         if ( q > 0 )
542                         {
543                                 c->rc_override[i].qscale = q;
544                                 c->rc_override[i].quality_factor = 1.0;
545                         }
546                         else
547                         {
548                                 c->rc_override[i].qscale = 0;
549                                 c->rc_override[i].quality_factor = -q / 100.0;
550                         }
551                         rc_override = strchr( rc_override, '/' );
552                         if ( rc_override )
553                                 rc_override++;
554                 }
555                 c->rc_override_count = i;
556                 if ( !c->rc_initial_buffer_occupancy )
557                         c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
558                 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
559
560                 // Setup dual-pass
561                 i = mlt_properties_get_int( properties, "pass" );
562                 if ( i == 1 )
563                         c->flags |= CODEC_FLAG_PASS1;
564                 else if ( i == 2 )
565                         c->flags |= CODEC_FLAG_PASS2;
566                 if ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) )
567                 {
568                         char logfilename[1024];
569                         FILE *f;
570                         int size;
571                         char *logbuffer;
572
573                         snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
574                                 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
575                         if ( c->flags & CODEC_FLAG_PASS1 )
576                         {
577                                 f = fopen( logfilename, "w" );
578                                 if ( !f )
579                                         perror( logfilename );
580                                 else
581                                         mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
582                         }
583                         else
584                         {
585                                 /* read the log file */
586                                 f = fopen( logfilename, "r" );
587                                 if ( !f )
588                                 {
589                                         perror(logfilename);
590                                 }
591                                 else
592                                 {
593                                         fseek( f, 0, SEEK_END );
594                                         size = ftell( f );
595                                         fseek( f, 0, SEEK_SET );
596                                         logbuffer = av_malloc( size + 1 );
597                                         if ( !logbuffer )
598                                                 fprintf( stderr, "%s: Could not allocate log buffer\n", __FILE__ );
599                                         else
600                                         {
601                                                 size = fread( logbuffer, 1, size, f );
602                                                 fclose( f );
603                                                 logbuffer[size] = '\0';
604                                                 c->stats_in = logbuffer;
605                                                 mlt_properties_set_data( properties, "_logbuffer", logbuffer, 0, ( mlt_destructor )av_free, NULL );
606                                         }
607                                 }
608                         }
609                 }
610         }
611         else
612         {
613                 fprintf( stderr, "%s: Could not allocate a stream for video\n", __FILE__ );
614         }
615  
616         return st;
617 }
618
619 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
620 {
621         // Allocate a frame
622         AVFrame *picture = avcodec_alloc_frame();
623
624         // Determine size of the 
625         int size = avpicture_get_size(pix_fmt, width, height);
626
627         // Allocate the picture buf
628         uint8_t *picture_buf = av_malloc(size);
629
630         // If we have both, then fill the image
631         if ( picture != NULL && picture_buf != NULL )
632         {
633                 // Fill the frame with the allocated buffer
634                 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
635         }
636         else
637         {
638                 // Something failed - clean up what we can
639                 av_free( picture );
640                 av_free( picture_buf );
641                 picture = NULL;
642         }
643
644         return picture;
645 }
646         
647 static int open_video(AVFormatContext *oc, AVStream *st)
648 {
649         // Get the codec
650         AVCodecContext *video_enc = st->codec;
651
652         // find the video encoder
653         AVCodec *codec = avcodec_find_encoder( video_enc->codec_id );
654
655         if( codec && codec->pix_fmts )
656         {
657                 const enum PixelFormat *p = codec->pix_fmts;
658                 for( ; *p!=-1; p++ )
659                 {
660                         if( *p == video_enc->pix_fmt )
661                                 break;
662                 }
663                 if( *p == -1 )
664                         video_enc->pix_fmt = codec->pix_fmts[ 0 ];
665         }
666
667         // Open the codec safely
668         return codec != NULL && avcodec_open( video_enc, codec ) >= 0;
669 }
670
671 void close_video(AVFormatContext *oc, AVStream *st)
672 {
673         avcodec_close(st->codec);
674 }
675
676 static inline long time_difference( struct timeval *time1 )
677 {
678         struct timeval time2;
679         gettimeofday( &time2, NULL );
680         return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
681 }
682
683 /** The main thread - the argument is simply the consumer.
684 */
685
686 static void *consumer_thread( void *arg )
687 {
688         // Map the argument to the object
689         mlt_consumer this = arg;
690
691         // Get the properties
692         mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
693
694         // Get the terminate on pause property
695         int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
696         int terminated = 0;
697
698         // Determine if feed is slow (for realtime stuff)
699         int real_time_output = mlt_properties_get_int( properties, "real_time" );
700
701         // Time structures
702         struct timeval ante;
703
704         // Get the frame rate
705         double fps = mlt_properties_get_double( properties, "fps" );
706
707         // Get width and height
708         int width = mlt_properties_get_int( properties, "width" );
709         int height = mlt_properties_get_int( properties, "height" );
710         int img_width = width;
711         int img_height = height;
712
713         // Get default audio properties
714         mlt_audio_format aud_fmt = mlt_audio_pcm;
715         int channels = mlt_properties_get_int( properties, "channels" );
716         int frequency = mlt_properties_get_int( properties, "frequency" );
717         int16_t *pcm = NULL;
718         int samples = 0;
719
720         // AVFormat audio buffer and frame size
721         int audio_outbuf_size = 10000;
722         uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
723         int audio_input_frame_size = 0;
724
725         // AVFormat video buffer and frame count
726         int frame_count = 0;
727         int video_outbuf_size = ( 1024 * 1024 );
728         uint8_t *video_outbuf = av_malloc( video_outbuf_size );
729
730         // Used for the frame properties
731         mlt_frame frame = NULL;
732         mlt_properties frame_properties = NULL;
733
734         // Get the queues
735         mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
736         sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
737
738         // Need two av pictures for converting
739         AVFrame *output = NULL;
740         AVFrame *input = alloc_picture( PIX_FMT_YUV422, width, height );
741
742         // For receiving images from an mlt_frame
743         uint8_t *image;
744         mlt_image_format img_fmt = mlt_image_yuv422;
745
746         // For receiving audio samples back from the fifo
747         int16_t *buffer = av_malloc( 48000 * 2 );
748         int count = 0;
749
750         // Allocate the context
751         AVFormatContext *oc = av_alloc_format_context( );
752
753         // Streams
754         AVStream *audio_st = NULL;
755         AVStream *video_st = NULL;
756
757         // Time stamps
758         double audio_pts = 0;
759         double video_pts = 0;
760
761         // Loop variable
762         int i;
763
764         // Frames despatched
765         long int frames = 0;
766         long int total_time = 0;
767
768         // Determine the format
769         AVOutputFormat *fmt = NULL;
770         char *filename = mlt_properties_get( properties, "target" );
771         char *format = mlt_properties_get( properties, "f" );
772         char *vcodec = mlt_properties_get( properties, "vcodec" );
773         char *acodec = mlt_properties_get( properties, "acodec" );
774         
775         // Used to store and override codec ids
776         int audio_codec_id;
777         int video_codec_id;
778
779         // Check for user selected format first
780         if ( format != NULL )
781                 fmt = guess_format( format, NULL, NULL );
782
783         // Otherwise check on the filename
784         if ( fmt == NULL && filename != NULL )
785                 fmt = guess_format( NULL, filename, NULL );
786
787         // Otherwise default to mpeg
788         if ( fmt == NULL )
789                 fmt = guess_format( "mpeg", NULL, NULL );
790
791         // We need a filename - default to stdout?
792         if ( filename == NULL || !strcmp( filename, "" ) )
793                 filename = "pipe:";
794
795         // Get the codec ids selected
796         audio_codec_id = fmt->audio_codec;
797         video_codec_id = fmt->video_codec;
798
799         // Check for audio codec overides
800         if ( acodec != NULL )
801         {
802                 AVCodec *p = avcodec_find_encoder_by_name( acodec );
803                 if ( p != NULL )
804                         audio_codec_id = p->id;
805                 else
806                         fprintf( stderr, "%s: audio codec %s unrecognised - ignoring\n", __FILE__, acodec );
807         }
808
809         // Check for video codec overides
810         if ( vcodec != NULL )
811         {
812                 AVCodec *p = avcodec_find_encoder_by_name( vcodec );
813                 if ( p != NULL )
814                         video_codec_id = p->id;
815                 else
816                         fprintf( stderr, "%s: video codec %s unrecognised - ignoring\n", __FILE__, vcodec );
817         }
818
819         // Write metadata
820         char *tmp = NULL;
821         int metavalue;
822
823         tmp = mlt_properties_get( properties, "meta.attr.title.markup");
824         if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
825
826         tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
827         if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
828
829         tmp = mlt_properties_get( properties, "meta.attr.author.markup");
830         if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
831
832         tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
833         if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
834
835         tmp = mlt_properties_get( properties, "meta.attr.album.markup");
836         if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
837
838         metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
839         if (metavalue != 0) oc->year = metavalue;
840
841         metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
842         if (metavalue != 0) oc->track = metavalue;
843
844         oc->oformat = fmt;
845         snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
846
847         // Add audio and video streams 
848         if ( fmt->video_codec != CODEC_ID_NONE )
849                 video_st = add_video_stream( this, oc, video_codec_id );
850         if ( fmt->audio_codec != CODEC_ID_NONE )
851                 audio_st = add_audio_stream( this, oc, audio_codec_id );
852
853         // Set the parameters (even though we have none...)
854         if ( av_set_parameters(oc, NULL) >= 0 ) 
855         {
856                 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
857                 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
858
859                 // Process properties as AVOptions
860                 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
861
862                 if ( video_st && !open_video( oc, video_st ) )
863                         video_st = NULL;
864                 if ( audio_st )
865                         audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
866
867                 // Open the output file, if needed
868                 if ( !( fmt->flags & AVFMT_NOFILE ) ) 
869                 {
870                         if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 ) 
871                         {
872                                 fprintf( stderr, "%s: Could not open '%s'\n", __FILE__, filename );
873                                 mlt_properties_set_int( properties, "running", 0 );
874                         }
875                 }
876         
877                 // Write the stream header, if any
878                 if ( mlt_properties_get_int( properties, "running" ) )
879                         av_write_header( oc );
880         }
881         else
882         {
883                 fprintf( stderr, "%s: Invalid output format parameters\n", __FILE__ );
884                 mlt_properties_set_int( properties, "running", 0 );
885         }
886
887         // Allocate picture
888         if ( video_st )
889                 output = alloc_picture( video_st->codec->pix_fmt, width, height );
890
891         // Last check - need at least one stream
892         if ( audio_st == NULL && video_st == NULL )
893                 mlt_properties_set_int( properties, "running", 0 );
894
895         // Get the starting time (can ignore the times above)
896         gettimeofday( &ante, NULL );
897
898         // Loop while running
899         while( mlt_properties_get_int( properties, "running" ) && !terminated )
900         {
901                 // Get the frame
902                 frame = mlt_consumer_rt_frame( this );
903
904                 // Check that we have a frame to work with
905                 if ( frame != NULL )
906                 {
907                         // Increment frames despatched
908                         frames ++;
909
910                         // Default audio args
911                         frame_properties = MLT_FRAME_PROPERTIES( frame );
912
913                         // Check for the terminated condition
914                         terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
915
916                         // Get audio and append to the fifo
917                         if ( !terminated && audio_st )
918                         {
919                                 samples = mlt_sample_calculator( fps, frequency, count ++ );
920                                 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
921
922                                 // Create the fifo if we don't have one
923                                 if ( fifo == NULL )
924                                 {
925                                         fifo = sample_fifo_init( frequency, channels );
926                                         mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
927                                 }
928
929                                 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
930                                         memset( pcm, 0, samples * channels * 2 );
931
932                                 // Append the samples
933                                 sample_fifo_append( fifo, pcm, samples * channels );
934                                 total_time += ( samples * 1000000 ) / frequency;
935                         }
936
937                         // Encode the image
938                         if ( !terminated && video_st )
939                                 mlt_deque_push_back( queue, frame );
940                         else
941                                 mlt_frame_close( frame );
942                 }
943
944                 // While we have stuff to process, process...
945                 while ( 1 )
946                 {
947                         if (audio_st)
948                                 audio_pts = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;
949                         else
950                                 audio_pts = 0.0;
951         
952                         if (video_st)
953                                 video_pts = (double)video_st->pts.val * video_st->time_base.num / video_st->time_base.den;
954                         else
955                                 video_pts = 0.0;
956
957                         // Write interleaved audio and video frames
958                         if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
959                         {
960                                 if ( channels * audio_input_frame_size < sample_fifo_used( fifo ) )
961                                 {
962                                         AVCodecContext *c;
963                                         AVPacket pkt;
964                                         av_init_packet( &pkt );
965
966                                         c = audio_st->codec;
967
968                                         sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
969
970                                         pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
971                                         // Write the compressed frame in the media file
972                                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
973                                                 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
974                                         pkt.flags |= PKT_FLAG_KEY;
975                                         pkt.stream_index= audio_st->index;
976                                         pkt.data= audio_outbuf;
977
978                                         if ( pkt.size )
979                                                 if ( av_interleaved_write_frame( oc, &pkt ) != 0) 
980                                                         fprintf( stderr, "%s: Error while writing audio frame\n", __FILE__ );
981
982                                         audio_pts += c->frame_size;
983                                 }
984                                 else
985                                 {
986                                         break;
987                                 }
988                         }
989                         else if ( video_st )
990                         {
991                                 if ( mlt_deque_count( queue ) )
992                                 {
993                                         int out_size, ret;
994                                         AVCodecContext *c;
995
996                                         frame = mlt_deque_pop_front( queue );
997                                         frame_properties = MLT_FRAME_PROPERTIES( frame );
998
999                                         c = video_st->codec;
1000                                         
1001                                         if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1002                                         {
1003                                                 int i = 0;
1004                                                 int j = 0;
1005                                                 uint8_t *p;
1006                                                 uint8_t *q;
1007
1008                                                 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1009
1010                                                 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1011
1012                                                 q = image;
1013
1014                                                 // Convert the mlt frame to an AVPicture
1015                                                 for ( i = 0; i < height; i ++ )
1016                                                 {
1017                                                         p = input->data[ 0 ] + i * input->linesize[ 0 ];
1018                                                         j = width;
1019                                                         while( j -- )
1020                                                         {
1021                                                                 *p ++ = *q ++;
1022                                                                 *p ++ = *q ++;
1023                                                         }
1024                                                 }
1025
1026                                                 // Do the colour space conversion
1027 #ifdef SWSCALE
1028                                                 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUV422,
1029                                                         width, height, video_st->codec->pix_fmt, SWS_FAST_BILINEAR, NULL, NULL, NULL);
1030                                                 sws_scale( context, input->data, input->linesize, 0, height,
1031                                                         output->data, output->linesize);
1032                                                 sws_freeContext( context );
1033 #else
1034                                                 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUV422, width, height );
1035 #endif
1036
1037                                                 // Apply the alpha if applicable
1038                                                 if ( video_st->codec->pix_fmt == PIX_FMT_RGBA32 )
1039                                                 {
1040                                                         uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1041                                                         register int n;
1042
1043                                                         for ( i = 0; i < height; i ++ )
1044                                                         {
1045                                                                 n = ( width + 7 ) / 8;
1046                                                                 p = output->data[ 0 ] + i * output->linesize[ 0 ];
1047
1048                                                                 #ifndef __DARWIN__
1049                                                                 p += 3;
1050                                                                 #endif
1051
1052                                                                 switch( width % 8 )
1053                                                                 {
1054                                                                         case 0: do { *p = *alpha++; p += 4;
1055                                                                         case 7:          *p = *alpha++; p += 4;
1056                                                                         case 6:          *p = *alpha++; p += 4;
1057                                                                         case 5:          *p = *alpha++; p += 4;
1058                                                                         case 4:          *p = *alpha++; p += 4;
1059                                                                         case 3:          *p = *alpha++; p += 4;
1060                                                                         case 2:          *p = *alpha++; p += 4;
1061                                                                         case 1:          *p = *alpha++; p += 4;
1062                                                                                         }
1063                                                                                         while( --n );
1064                                                                 }
1065                                                         }
1066                                                 }
1067                                         }
1068
1069                                         if (oc->oformat->flags & AVFMT_RAWPICTURE) 
1070                                         {
1071                                                 // raw video case. The API will change slightly in the near future for that
1072                                                 AVPacket pkt;
1073                                                 av_init_packet(&pkt);
1074
1075                                                 pkt.flags |= PKT_FLAG_KEY;
1076                                                 pkt.stream_index= video_st->index;
1077                                                 pkt.data= (uint8_t *)output;
1078                                                 pkt.size= sizeof(AVPicture);
1079
1080                                                 ret = av_write_frame(oc, &pkt);
1081                                                 video_pts += c->frame_size;
1082                                         } 
1083                                         else 
1084                                         {
1085                                                 // Set the quality
1086                                                 output->quality = video_st->quality;
1087
1088                                                 // Set frame interlace hints
1089                                                 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1090                                                 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1091
1092                                                 // Encode the image
1093                                                 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1094
1095                                                 // If zero size, it means the image was buffered
1096                                                 if (out_size > 0) 
1097                                                 {
1098                                                         AVPacket pkt;
1099                                                         av_init_packet( &pkt );
1100
1101                                                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1102                                                                 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1103                                                         if( c->coded_frame && c->coded_frame->key_frame )
1104                                                                 pkt.flags |= PKT_FLAG_KEY;
1105                                                         pkt.stream_index= video_st->index;
1106                                                         pkt.data= video_outbuf;
1107                                                         pkt.size= out_size;
1108
1109                                                         // write the compressed frame in the media file
1110                                                         ret = av_interleaved_write_frame(oc, &pkt);
1111                                                         video_pts += c->frame_size;
1112                                                         
1113                                                         // Dual pass logging
1114                                                         if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out)
1115                                                                 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1116                                                 } 
1117                                                 else
1118                                                 {
1119                                                         fprintf( stderr, "%s: error with video encode\n", __FILE__ );
1120                                                 }
1121                                         }
1122                                         frame_count++;
1123                                         mlt_frame_close( frame );
1124                                 }
1125                                 else
1126                                 {
1127                                         break;
1128                                 }
1129                         }
1130                 }
1131
1132                 if ( real_time_output == 1 && frames % 12 == 0 )
1133                 {
1134                         long passed = time_difference( &ante );
1135                         if ( fifo != NULL )
1136                         {
1137                                 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1138                                 passed -= pending;
1139                         }
1140                         if ( passed < total_time )
1141                         {
1142                                 long total = ( total_time - passed );
1143                                 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1144                                 nanosleep( &t, NULL );
1145                         }
1146                 }
1147         }
1148
1149 #ifdef FLUSH
1150         if ( ! real_time_output )
1151         {
1152                 // Flush audio fifo
1153                 if ( audio_st && audio_st->codec->frame_size > 1 ) for (;;)
1154                 {
1155                         AVCodecContext *c = audio_st->codec;
1156                         AVPacket pkt;
1157                         av_init_packet( &pkt );
1158                         pkt.size = 0;
1159
1160                         if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1161                                 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1162                         {
1163                                 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
1164                                 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
1165                         }
1166                         if ( pkt.size <= 0 )
1167                                 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1168                         if ( pkt.size <= 0 )
1169                                 break;
1170
1171                         // Write the compressed frame in the media file
1172                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1173                                 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
1174                         pkt.flags |= PKT_FLAG_KEY;
1175                         pkt.stream_index = audio_st->index;
1176                         pkt.data = audio_outbuf;
1177                         if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1178                         {
1179                                 fprintf( stderr, "%s: Error while writing flushed audio frame\n", __FILE__ );
1180                                 break;
1181                         }
1182                 }
1183
1184                 // Flush video
1185                 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1186                 {
1187                         AVCodecContext *c = video_st->codec;
1188                         AVPacket pkt;
1189                         av_init_packet( &pkt );
1190
1191                         // Encode the image
1192                         pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1193                         if ( pkt.size <= 0 )
1194                                 break;
1195
1196                         if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1197                                 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1198                         if( c->coded_frame && c->coded_frame->key_frame )
1199                                 pkt.flags |= PKT_FLAG_KEY;
1200                         pkt.stream_index = video_st->index;
1201                         pkt.data = video_outbuf;
1202
1203                         // write the compressed frame in the media file
1204                         if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1205                         {
1206                                 fprintf( stderr, "%s: Error while writing flushed video frame\n". __FILE__ );
1207                                 break;
1208                         }
1209                 }
1210         }
1211 #endif
1212
1213         // close each codec 
1214         if (video_st)
1215                 close_video(oc, video_st);
1216         if (audio_st)
1217                 close_audio(oc, audio_st);
1218
1219         // Write the trailer, if any
1220         av_write_trailer(oc);
1221
1222         // Free the streams
1223         for(i = 0; i < oc->nb_streams; i++)
1224                 av_freep(&oc->streams[i]);
1225
1226         // Close the output file
1227         if (!(fmt->flags & AVFMT_NOFILE))
1228 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1229                 url_fclose(oc->pb);
1230 #else
1231                 url_fclose(&oc->pb);
1232 #endif
1233
1234         // Clean up input and output frames
1235         if ( output )
1236                 av_free( output->data[0] );
1237         av_free( output );
1238         av_free( input->data[0] );
1239         av_free( input );
1240         av_free( video_outbuf );
1241         av_free( buffer );
1242
1243         // Free the stream
1244         av_free(oc);
1245
1246         // Just in case we terminated on pause
1247         mlt_properties_set_int( properties, "running", 0 );
1248
1249         mlt_consumer_stopped( this );
1250
1251         return NULL;
1252 }
1253
1254 /** Close the consumer.
1255 */
1256
1257 static void consumer_close( mlt_consumer this )
1258 {
1259         // Stop the consumer
1260         mlt_consumer_stop( this );
1261
1262         // Close the parent
1263         mlt_consumer_close( this );
1264
1265         // Free the memory
1266         free( this );
1267 }