consumer_avformat.c: fix build on older libavformat versions
[melted] / src / modules / avformat / consumer_avformat.c
1 /*
2 * consumer_avformat.c -- an encoder based on avformat
3 * Copyright (C) 2003-2004 Ushodaya Enterprises Limited
4 * Author: Charles Yates <charles.yates@pandora.be>
5 * 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 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
471 st->sample_aspect_ratio.num = 10;
472 st->sample_aspect_ratio.den = 11;
473 #endif
474 }
475 else if ( ar == 16.0/15.0 ) // 4:3 PAL
476 {
477 c->sample_aspect_ratio.num = 159;
478 c->sample_aspect_ratio.den = 54;
479 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
480 st->sample_aspect_ratio.num = 159;
481 st->sample_aspect_ratio.den = 54;
482 #endif
483 }
484 else if ( ar == 32.0/27.0 ) // 16:9 NTSC
485 {
486 c->sample_aspect_ratio.num = 40;
487 c->sample_aspect_ratio.den = 33;
488 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
489 st->sample_aspect_ratio.num = 40;
490 st->sample_aspect_ratio.den = 33;
491 #endif
492 }
493 else // 16:9 PAL
494 {
495 c->sample_aspect_ratio.num = 118;
496 c->sample_aspect_ratio.den = 81;
497 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
498 st->sample_aspect_ratio.num = 118;
499 st->sample_aspect_ratio.den = 81;
500 #endif
501 }
502 }
503 else if ( mlt_properties_get( properties, "aspect" ) )
504 {
505 double ar = mlt_properties_get_double( properties, "aspect" );
506 c->sample_aspect_ratio = av_d2q( ar * c->height / c->width , 255);
507 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
508 st->sample_aspect_ratio = av_d2q( ar * c->height / c->width , 255);
509 #endif
510 }
511 else
512 {
513 c->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
514 c->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
515 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
516 st->sample_aspect_ratio.num = mlt_properties_get_int( properties, "sample_aspect_num" );
517 st->sample_aspect_ratio.den = mlt_properties_get_int( properties, "sample_aspect_den" );
518 #endif
519 }
520
521 if ( mlt_properties_get_double( properties, "qscale" ) > 0 )
522 {
523 c->flags |= CODEC_FLAG_QSCALE;
524 st->quality = FF_QP2LAMBDA * mlt_properties_get_double( properties, "qscale" );
525 }
526
527 // Allow the user to override the video fourcc
528 if ( mlt_properties_get( properties, "vtag" ) )
529 {
530 char *tail = NULL;
531 const char *arg = mlt_properties_get( properties, "vtag" );
532 int tag = strtol( arg, &tail, 0);
533 if( !tail || *tail )
534 tag = arg[ 0 ] + ( arg[ 1 ] << 8 ) + ( arg[ 2 ] << 16 ) + ( arg[ 3 ] << 24 );
535 c->codec_tag = tag;
536 }
537
538 // Some formats want stream headers to be seperate
539 if ( oc->oformat->flags & AVFMT_GLOBALHEADER )
540 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
541
542 // Translate these standard mlt consumer properties to ffmpeg
543 if ( mlt_properties_get_int( properties, "progressive" ) == 0 &&
544 mlt_properties_get_int( properties, "deinterlace" ) == 0 )
545 {
546 if ( mlt_properties_get_int( properties, "ildct" ) )
547 c->flags |= CODEC_FLAG_INTERLACED_DCT;
548 if ( mlt_properties_get_int( properties, "ilme" ) )
549 c->flags |= CODEC_FLAG_INTERLACED_ME;
550 }
551
552 // parse the ratecontrol override string
553 int i;
554 char *rc_override = mlt_properties_get( properties, "rc_override" );
555 for ( i = 0; rc_override; i++ )
556 {
557 int start, end, q;
558 int e = sscanf( rc_override, "%d,%d,%d", &start, &end, &q );
559 if ( e != 3 )
560 fprintf( stderr, "%s: Error parsing rc_override\n", __FILE__ );
561 c->rc_override = av_realloc( c->rc_override, sizeof( RcOverride ) * ( i + 1 ) );
562 c->rc_override[i].start_frame = start;
563 c->rc_override[i].end_frame = end;
564 if ( q > 0 )
565 {
566 c->rc_override[i].qscale = q;
567 c->rc_override[i].quality_factor = 1.0;
568 }
569 else
570 {
571 c->rc_override[i].qscale = 0;
572 c->rc_override[i].quality_factor = -q / 100.0;
573 }
574 rc_override = strchr( rc_override, '/' );
575 if ( rc_override )
576 rc_override++;
577 }
578 c->rc_override_count = i;
579 if ( !c->rc_initial_buffer_occupancy )
580 c->rc_initial_buffer_occupancy = c->rc_buffer_size * 3/4;
581 c->intra_dc_precision = mlt_properties_get_int( properties, "dc" ) - 8;
582
583 // Setup dual-pass
584 i = mlt_properties_get_int( properties, "pass" );
585 if ( i == 1 )
586 c->flags |= CODEC_FLAG_PASS1;
587 else if ( i == 2 )
588 c->flags |= CODEC_FLAG_PASS2;
589 if ( c->flags & ( CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2 ) )
590 {
591 char logfilename[1024];
592 FILE *f;
593 int size;
594 char *logbuffer;
595
596 snprintf( logfilename, sizeof(logfilename), "%s_2pass.log",
597 mlt_properties_get( properties, "passlogfile" ) ? mlt_properties_get( properties, "passlogfile" ) : mlt_properties_get( properties, "target" ) );
598 if ( c->flags & CODEC_FLAG_PASS1 )
599 {
600 f = fopen( logfilename, "w" );
601 if ( !f )
602 perror( logfilename );
603 else
604 mlt_properties_set_data( properties, "_logfile", f, 0, ( mlt_destructor )fclose, NULL );
605 }
606 else
607 {
608 /* read the log file */
609 f = fopen( logfilename, "r" );
610 if ( !f )
611 {
612 perror(logfilename);
613 }
614 else
615 {
616 fseek( f, 0, SEEK_END );
617 size = ftell( f );
618 fseek( f, 0, SEEK_SET );
619 logbuffer = av_malloc( size + 1 );
620 if ( !logbuffer )
621 fprintf( stderr, "%s: Could not allocate log buffer\n", __FILE__ );
622 else
623 {
624 size = fread( logbuffer, 1, size, f );
625 fclose( f );
626 logbuffer[size] = '\0';
627 c->stats_in = logbuffer;
628 mlt_properties_set_data( properties, "_logbuffer", logbuffer, 0, ( mlt_destructor )av_free, NULL );
629 }
630 }
631 }
632 }
633 }
634 else
635 {
636 fprintf( stderr, "%s: Could not allocate a stream for video\n", __FILE__ );
637 }
638
639 return st;
640 }
641
642 static AVFrame *alloc_picture( int pix_fmt, int width, int height )
643 {
644 // Allocate a frame
645 AVFrame *picture = avcodec_alloc_frame();
646
647 // Determine size of the
648 int size = avpicture_get_size(pix_fmt, width, height);
649
650 // Allocate the picture buf
651 uint8_t *picture_buf = av_malloc(size);
652
653 // If we have both, then fill the image
654 if ( picture != NULL && picture_buf != NULL )
655 {
656 // Fill the frame with the allocated buffer
657 avpicture_fill( (AVPicture *)picture, picture_buf, pix_fmt, width, height);
658 }
659 else
660 {
661 // Something failed - clean up what we can
662 av_free( picture );
663 av_free( picture_buf );
664 picture = NULL;
665 }
666
667 return picture;
668 }
669
670 static int open_video(AVFormatContext *oc, AVStream *st)
671 {
672 // Get the codec
673 AVCodecContext *video_enc = st->codec;
674
675 // find the video encoder
676 AVCodec *codec = avcodec_find_encoder( video_enc->codec_id );
677
678 if( codec && codec->pix_fmts )
679 {
680 const enum PixelFormat *p = codec->pix_fmts;
681 for( ; *p!=-1; p++ )
682 {
683 if( *p == video_enc->pix_fmt )
684 break;
685 }
686 if( *p == -1 )
687 video_enc->pix_fmt = codec->pix_fmts[ 0 ];
688 }
689
690 // Open the codec safely
691 return codec != NULL && avcodec_open( video_enc, codec ) >= 0;
692 }
693
694 void close_video(AVFormatContext *oc, AVStream *st)
695 {
696 avcodec_close(st->codec);
697 }
698
699 static inline long time_difference( struct timeval *time1 )
700 {
701 struct timeval time2;
702 gettimeofday( &time2, NULL );
703 return time2.tv_sec * 1000000 + time2.tv_usec - time1->tv_sec * 1000000 - time1->tv_usec;
704 }
705
706 /** The main thread - the argument is simply the consumer.
707 */
708
709 static void *consumer_thread( void *arg )
710 {
711 // Map the argument to the object
712 mlt_consumer this = arg;
713
714 // Get the properties
715 mlt_properties properties = MLT_CONSUMER_PROPERTIES( this );
716
717 // Get the terminate on pause property
718 int terminate_on_pause = mlt_properties_get_int( properties, "terminate_on_pause" );
719 int terminated = 0;
720
721 // Determine if feed is slow (for realtime stuff)
722 int real_time_output = mlt_properties_get_int( properties, "real_time" );
723
724 // Time structures
725 struct timeval ante;
726
727 // Get the frame rate
728 double fps = mlt_properties_get_double( properties, "fps" );
729
730 // Get width and height
731 int width = mlt_properties_get_int( properties, "width" );
732 int height = mlt_properties_get_int( properties, "height" );
733 int img_width = width;
734 int img_height = height;
735
736 // Get default audio properties
737 mlt_audio_format aud_fmt = mlt_audio_pcm;
738 int channels = mlt_properties_get_int( properties, "channels" );
739 int frequency = mlt_properties_get_int( properties, "frequency" );
740 int16_t *pcm = NULL;
741 int samples = 0;
742
743 // AVFormat audio buffer and frame size
744 int audio_outbuf_size = 10000;
745 uint8_t *audio_outbuf = av_malloc( audio_outbuf_size );
746 int audio_input_frame_size = 0;
747
748 // AVFormat video buffer and frame count
749 int frame_count = 0;
750 int video_outbuf_size = ( 1024 * 1024 );
751 uint8_t *video_outbuf = av_malloc( video_outbuf_size );
752
753 // Used for the frame properties
754 mlt_frame frame = NULL;
755 mlt_properties frame_properties = NULL;
756
757 // Get the queues
758 mlt_deque queue = mlt_properties_get_data( properties, "frame_queue", NULL );
759 sample_fifo fifo = mlt_properties_get_data( properties, "sample_fifo", NULL );
760
761 // Need two av pictures for converting
762 AVFrame *output = NULL;
763 AVFrame *input = alloc_picture( PIX_FMT_YUV422, width, height );
764
765 // For receiving images from an mlt_frame
766 uint8_t *image;
767 mlt_image_format img_fmt = mlt_image_yuv422;
768
769 // For receiving audio samples back from the fifo
770 int16_t *buffer = av_malloc( 48000 * 2 );
771 int count = 0;
772
773 // Allocate the context
774 AVFormatContext *oc = av_alloc_format_context( );
775
776 // Streams
777 AVStream *audio_st = NULL;
778 AVStream *video_st = NULL;
779
780 // Time stamps
781 double audio_pts = 0;
782 double video_pts = 0;
783
784 // Loop variable
785 int i;
786
787 // Frames despatched
788 long int frames = 0;
789 long int total_time = 0;
790
791 // Determine the format
792 AVOutputFormat *fmt = NULL;
793 char *filename = mlt_properties_get( properties, "target" );
794 char *format = mlt_properties_get( properties, "f" );
795 char *vcodec = mlt_properties_get( properties, "vcodec" );
796 char *acodec = mlt_properties_get( properties, "acodec" );
797
798 // Used to store and override codec ids
799 int audio_codec_id;
800 int video_codec_id;
801
802 // Check for user selected format first
803 if ( format != NULL )
804 fmt = guess_format( format, NULL, NULL );
805
806 // Otherwise check on the filename
807 if ( fmt == NULL && filename != NULL )
808 fmt = guess_format( NULL, filename, NULL );
809
810 // Otherwise default to mpeg
811 if ( fmt == NULL )
812 fmt = guess_format( "mpeg", NULL, NULL );
813
814 // We need a filename - default to stdout?
815 if ( filename == NULL || !strcmp( filename, "" ) )
816 filename = "pipe:";
817
818 // Get the codec ids selected
819 audio_codec_id = fmt->audio_codec;
820 video_codec_id = fmt->video_codec;
821
822 // Check for audio codec overides
823 if ( acodec != NULL )
824 {
825 AVCodec *p = avcodec_find_encoder_by_name( acodec );
826 if ( p != NULL )
827 audio_codec_id = p->id;
828 else
829 fprintf( stderr, "%s: audio codec %s unrecognised - ignoring\n", __FILE__, acodec );
830 }
831
832 // Check for video codec overides
833 if ( vcodec != NULL )
834 {
835 AVCodec *p = avcodec_find_encoder_by_name( vcodec );
836 if ( p != NULL )
837 video_codec_id = p->id;
838 else
839 fprintf( stderr, "%s: video codec %s unrecognised - ignoring\n", __FILE__, vcodec );
840 }
841
842 // Write metadata
843 char *tmp = NULL;
844 int metavalue;
845
846 tmp = mlt_properties_get( properties, "meta.attr.title.markup");
847 if (tmp != NULL) snprintf( oc->title, sizeof(oc->title), "%s", tmp );
848
849 tmp = mlt_properties_get( properties, "meta.attr.comment.markup");
850 if (tmp != NULL) snprintf( oc->comment, sizeof(oc->comment), "%s", tmp );
851
852 tmp = mlt_properties_get( properties, "meta.attr.author.markup");
853 if (tmp != NULL) snprintf( oc->author, sizeof(oc->author), "%s", tmp );
854
855 tmp = mlt_properties_get( properties, "meta.attr.copyright.markup");
856 if (tmp != NULL) snprintf( oc->copyright, sizeof(oc->copyright), "%s", tmp );
857
858 tmp = mlt_properties_get( properties, "meta.attr.album.markup");
859 if (tmp != NULL) snprintf( oc->album, sizeof(oc->album), "%s", tmp );
860
861 metavalue = mlt_properties_get_int( properties, "meta.attr.year.markup");
862 if (metavalue != 0) oc->year = metavalue;
863
864 metavalue = mlt_properties_get_int( properties, "meta.attr.track.markup");
865 if (metavalue != 0) oc->track = metavalue;
866
867 oc->oformat = fmt;
868 snprintf( oc->filename, sizeof(oc->filename), "%s", filename );
869
870 // Add audio and video streams
871 if ( fmt->video_codec != CODEC_ID_NONE )
872 video_st = add_video_stream( this, oc, video_codec_id );
873 if ( fmt->audio_codec != CODEC_ID_NONE )
874 audio_st = add_audio_stream( this, oc, audio_codec_id );
875
876 // Set the parameters (even though we have none...)
877 if ( av_set_parameters(oc, NULL) >= 0 )
878 {
879 oc->preload = ( int )( mlt_properties_get_double( properties, "muxpreload" ) * AV_TIME_BASE );
880 oc->max_delay= ( int )( mlt_properties_get_double( properties, "muxdelay" ) * AV_TIME_BASE );
881
882 // Process properties as AVOptions
883 apply_properties( oc, properties, AV_OPT_FLAG_ENCODING_PARAM );
884
885 if ( video_st && !open_video( oc, video_st ) )
886 video_st = NULL;
887 if ( audio_st )
888 audio_input_frame_size = open_audio( oc, audio_st, audio_outbuf_size );
889
890 // Open the output file, if needed
891 if ( !( fmt->flags & AVFMT_NOFILE ) )
892 {
893 if ( url_fopen( &oc->pb, filename, URL_WRONLY ) < 0 )
894 {
895 fprintf( stderr, "%s: Could not open '%s'\n", __FILE__, filename );
896 mlt_properties_set_int( properties, "running", 0 );
897 }
898 }
899
900 // Write the stream header, if any
901 if ( mlt_properties_get_int( properties, "running" ) )
902 av_write_header( oc );
903 }
904 else
905 {
906 fprintf( stderr, "%s: Invalid output format parameters\n", __FILE__ );
907 mlt_properties_set_int( properties, "running", 0 );
908 }
909
910 // Allocate picture
911 if ( video_st )
912 output = alloc_picture( video_st->codec->pix_fmt, width, height );
913
914 // Last check - need at least one stream
915 if ( audio_st == NULL && video_st == NULL )
916 mlt_properties_set_int( properties, "running", 0 );
917
918 // Get the starting time (can ignore the times above)
919 gettimeofday( &ante, NULL );
920
921 // Loop while running
922 while( mlt_properties_get_int( properties, "running" ) && !terminated )
923 {
924 // Get the frame
925 frame = mlt_consumer_rt_frame( this );
926
927 // Check that we have a frame to work with
928 if ( frame != NULL )
929 {
930 // Increment frames despatched
931 frames ++;
932
933 // Default audio args
934 frame_properties = MLT_FRAME_PROPERTIES( frame );
935
936 // Check for the terminated condition
937 terminated = terminate_on_pause && mlt_properties_get_double( frame_properties, "_speed" ) == 0.0;
938
939 // Get audio and append to the fifo
940 if ( !terminated && audio_st )
941 {
942 samples = mlt_sample_calculator( fps, frequency, count ++ );
943 mlt_frame_get_audio( frame, &pcm, &aud_fmt, &frequency, &channels, &samples );
944
945 // Create the fifo if we don't have one
946 if ( fifo == NULL )
947 {
948 fifo = sample_fifo_init( frequency, channels );
949 mlt_properties_set_data( properties, "sample_fifo", fifo, 0, ( mlt_destructor )sample_fifo_close, NULL );
950 }
951
952 if ( mlt_properties_get_double( frame_properties, "_speed" ) != 1.0 )
953 memset( pcm, 0, samples * channels * 2 );
954
955 // Append the samples
956 sample_fifo_append( fifo, pcm, samples * channels );
957 total_time += ( samples * 1000000 ) / frequency;
958 }
959
960 // Encode the image
961 if ( !terminated && video_st )
962 mlt_deque_push_back( queue, frame );
963 else
964 mlt_frame_close( frame );
965 }
966
967 // While we have stuff to process, process...
968 while ( 1 )
969 {
970 if (audio_st)
971 audio_pts = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;
972 else
973 audio_pts = 0.0;
974
975 if (video_st)
976 video_pts = (double)video_st->pts.val * video_st->time_base.num / video_st->time_base.den;
977 else
978 video_pts = 0.0;
979
980 // Write interleaved audio and video frames
981 if ( !video_st || ( video_st && audio_st && audio_pts < video_pts ) )
982 {
983 if ( channels * audio_input_frame_size < sample_fifo_used( fifo ) )
984 {
985 AVCodecContext *c;
986 AVPacket pkt;
987 av_init_packet( &pkt );
988
989 c = audio_st->codec;
990
991 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
992
993 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
994 // Write the compressed frame in the media file
995 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
996 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
997 pkt.flags |= PKT_FLAG_KEY;
998 pkt.stream_index= audio_st->index;
999 pkt.data= audio_outbuf;
1000
1001 if ( pkt.size )
1002 if ( av_interleaved_write_frame( oc, &pkt ) != 0)
1003 fprintf( stderr, "%s: Error while writing audio frame\n", __FILE__ );
1004
1005 audio_pts += c->frame_size;
1006 }
1007 else
1008 {
1009 break;
1010 }
1011 }
1012 else if ( video_st )
1013 {
1014 if ( mlt_deque_count( queue ) )
1015 {
1016 int out_size, ret;
1017 AVCodecContext *c;
1018
1019 frame = mlt_deque_pop_front( queue );
1020 frame_properties = MLT_FRAME_PROPERTIES( frame );
1021
1022 c = video_st->codec;
1023
1024 if ( mlt_properties_get_int( frame_properties, "rendered" ) )
1025 {
1026 int i = 0;
1027 int j = 0;
1028 uint8_t *p;
1029 uint8_t *q;
1030
1031 mlt_events_fire( properties, "consumer-frame-show", frame, NULL );
1032
1033 mlt_frame_get_image( frame, &image, &img_fmt, &img_width, &img_height, 0 );
1034
1035 q = image;
1036
1037 // Convert the mlt frame to an AVPicture
1038 for ( i = 0; i < height; i ++ )
1039 {
1040 p = input->data[ 0 ] + i * input->linesize[ 0 ];
1041 j = width;
1042 while( j -- )
1043 {
1044 *p ++ = *q ++;
1045 *p ++ = *q ++;
1046 }
1047 }
1048
1049 // Do the colour space conversion
1050 #ifdef SWSCALE
1051 struct SwsContext *context = sws_getContext( width, height, PIX_FMT_YUV422,
1052 width, height, video_st->codec->pix_fmt, SWS_FAST_BILINEAR, NULL, NULL, NULL);
1053 sws_scale( context, input->data, input->linesize, 0, height,
1054 output->data, output->linesize);
1055 sws_freeContext( context );
1056 #else
1057 img_convert( ( AVPicture * )output, video_st->codec->pix_fmt, ( AVPicture * )input, PIX_FMT_YUV422, width, height );
1058 #endif
1059
1060 // Apply the alpha if applicable
1061 if ( video_st->codec->pix_fmt == PIX_FMT_RGBA32 )
1062 {
1063 uint8_t *alpha = mlt_frame_get_alpha_mask( frame );
1064 register int n;
1065
1066 for ( i = 0; i < height; i ++ )
1067 {
1068 n = ( width + 7 ) / 8;
1069 p = output->data[ 0 ] + i * output->linesize[ 0 ];
1070
1071 #ifndef __DARWIN__
1072 p += 3;
1073 #endif
1074
1075 switch( width % 8 )
1076 {
1077 case 0: do { *p = *alpha++; p += 4;
1078 case 7: *p = *alpha++; p += 4;
1079 case 6: *p = *alpha++; p += 4;
1080 case 5: *p = *alpha++; p += 4;
1081 case 4: *p = *alpha++; p += 4;
1082 case 3: *p = *alpha++; p += 4;
1083 case 2: *p = *alpha++; p += 4;
1084 case 1: *p = *alpha++; p += 4;
1085 }
1086 while( --n );
1087 }
1088 }
1089 }
1090 }
1091
1092 if (oc->oformat->flags & AVFMT_RAWPICTURE)
1093 {
1094 // raw video case. The API will change slightly in the near future for that
1095 AVPacket pkt;
1096 av_init_packet(&pkt);
1097
1098 pkt.flags |= PKT_FLAG_KEY;
1099 pkt.stream_index= video_st->index;
1100 pkt.data= (uint8_t *)output;
1101 pkt.size= sizeof(AVPicture);
1102
1103 ret = av_write_frame(oc, &pkt);
1104 video_pts += c->frame_size;
1105 }
1106 else
1107 {
1108 // Set the quality
1109 output->quality = video_st->quality;
1110
1111 // Set frame interlace hints
1112 output->interlaced_frame = !mlt_properties_get_int( frame_properties, "progressive" );
1113 output->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1114
1115 // Encode the image
1116 out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, output );
1117
1118 // If zero size, it means the image was buffered
1119 if (out_size > 0)
1120 {
1121 AVPacket pkt;
1122 av_init_packet( &pkt );
1123
1124 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1125 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1126 if( c->coded_frame && c->coded_frame->key_frame )
1127 pkt.flags |= PKT_FLAG_KEY;
1128 pkt.stream_index= video_st->index;
1129 pkt.data= video_outbuf;
1130 pkt.size= out_size;
1131
1132 // write the compressed frame in the media file
1133 ret = av_interleaved_write_frame(oc, &pkt);
1134 video_pts += c->frame_size;
1135
1136 // Dual pass logging
1137 if ( mlt_properties_get_data( properties, "_logfile", NULL ) && c->stats_out)
1138 fprintf( mlt_properties_get_data( properties, "_logfile", NULL ), "%s", c->stats_out );
1139 }
1140 else
1141 {
1142 fprintf( stderr, "%s: error with video encode\n", __FILE__ );
1143 }
1144 }
1145 frame_count++;
1146 mlt_frame_close( frame );
1147 }
1148 else
1149 {
1150 break;
1151 }
1152 }
1153 }
1154
1155 if ( real_time_output == 1 && frames % 12 == 0 )
1156 {
1157 long passed = time_difference( &ante );
1158 if ( fifo != NULL )
1159 {
1160 long pending = ( ( ( long )sample_fifo_used( fifo ) * 1000 ) / frequency ) * 1000;
1161 passed -= pending;
1162 }
1163 if ( passed < total_time )
1164 {
1165 long total = ( total_time - passed );
1166 struct timespec t = { total / 1000000, ( total % 1000000 ) * 1000 };
1167 nanosleep( &t, NULL );
1168 }
1169 }
1170 }
1171
1172 #ifdef FLUSH
1173 if ( ! real_time_output )
1174 {
1175 // Flush audio fifo
1176 if ( audio_st && audio_st->codec->frame_size > 1 ) for (;;)
1177 {
1178 AVCodecContext *c = audio_st->codec;
1179 AVPacket pkt;
1180 av_init_packet( &pkt );
1181 pkt.size = 0;
1182
1183 if ( /*( c->capabilities & CODEC_CAP_SMALL_LAST_FRAME ) &&*/
1184 ( channels * audio_input_frame_size < sample_fifo_used( fifo ) ) )
1185 {
1186 sample_fifo_fetch( fifo, buffer, channels * audio_input_frame_size );
1187 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, buffer );
1188 }
1189 if ( pkt.size <= 0 )
1190 pkt.size = avcodec_encode_audio( c, audio_outbuf, audio_outbuf_size, NULL );
1191 if ( pkt.size <= 0 )
1192 break;
1193
1194 // Write the compressed frame in the media file
1195 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1196 pkt.pts = av_rescale_q( c->coded_frame->pts, c->time_base, audio_st->time_base );
1197 pkt.flags |= PKT_FLAG_KEY;
1198 pkt.stream_index = audio_st->index;
1199 pkt.data = audio_outbuf;
1200 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1201 {
1202 fprintf( stderr, "%s: Error while writing flushed audio frame\n", __FILE__ );
1203 break;
1204 }
1205 }
1206
1207 // Flush video
1208 if ( video_st && !( oc->oformat->flags & AVFMT_RAWPICTURE ) ) for (;;)
1209 {
1210 AVCodecContext *c = video_st->codec;
1211 AVPacket pkt;
1212 av_init_packet( &pkt );
1213
1214 // Encode the image
1215 pkt.size = avcodec_encode_video( c, video_outbuf, video_outbuf_size, NULL );
1216 if ( pkt.size <= 0 )
1217 break;
1218
1219 if ( c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE )
1220 pkt.pts= av_rescale_q( c->coded_frame->pts, c->time_base, video_st->time_base );
1221 if( c->coded_frame && c->coded_frame->key_frame )
1222 pkt.flags |= PKT_FLAG_KEY;
1223 pkt.stream_index = video_st->index;
1224 pkt.data = video_outbuf;
1225
1226 // write the compressed frame in the media file
1227 if ( av_interleaved_write_frame( oc, &pkt ) != 0 )
1228 {
1229 fprintf( stderr, "%s: Error while writing flushed video frame\n". __FILE__ );
1230 break;
1231 }
1232 }
1233 }
1234 #endif
1235
1236 // close each codec
1237 if (video_st)
1238 close_video(oc, video_st);
1239 if (audio_st)
1240 close_audio(oc, audio_st);
1241
1242 // Write the trailer, if any
1243 av_write_trailer(oc);
1244
1245 // Free the streams
1246 for(i = 0; i < oc->nb_streams; i++)
1247 av_freep(&oc->streams[i]);
1248
1249 // Close the output file
1250 if (!(fmt->flags & AVFMT_NOFILE))
1251 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(0<<8)+0)
1252 url_fclose(oc->pb);
1253 #else
1254 url_fclose(&oc->pb);
1255 #endif
1256
1257 // Clean up input and output frames
1258 if ( output )
1259 av_free( output->data[0] );
1260 av_free( output );
1261 av_free( input->data[0] );
1262 av_free( input );
1263 av_free( video_outbuf );
1264 av_free( buffer );
1265
1266 // Free the stream
1267 av_free(oc);
1268
1269 // Just in case we terminated on pause
1270 mlt_properties_set_int( properties, "running", 0 );
1271
1272 mlt_consumer_stopped( this );
1273
1274 return NULL;
1275 }
1276
1277 /** Close the consumer.
1278 */
1279
1280 static void consumer_close( mlt_consumer this )
1281 {
1282 // Stop the consumer
1283 mlt_consumer_stop( this );
1284
1285 // Close the parent
1286 mlt_consumer_close( this );
1287
1288 // Free the memory
1289 free( this );
1290 }