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