gop/b frame fix, http/pipe handling and logging off
[melted] / src / modules / avformat / producer_avformat.c
1 /*
2 * producer_avformat.c -- avformat producer
3 * Copyright (C) 2003-2004 Ushodaya Enterprises Limited
4 * Author: Charles Yates <charles.yates@pandora.be>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 */
20
21 // Local header files
22 #include "producer_avformat.h"
23
24 // MLT Header files
25 #include <framework/mlt_frame.h>
26
27 // ffmpeg Header files
28 #include <avformat.h>
29
30 // System header files
31 #include <stdlib.h>
32 #include <string.h>
33 #include <pthread.h>
34 #include <math.h>
35
36 void avformat_lock( );
37 void avformat_unlock( );
38
39 // Forward references.
40 static int producer_open( mlt_producer this, char *file );
41 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index );
42
43 /** Constructor for libavformat.
44 */
45
46 mlt_producer producer_avformat_init( char *file )
47 {
48 mlt_producer this = NULL;
49
50 // Check that we have a non-NULL argument
51 if ( file != NULL )
52 {
53 // Construct the producer
54 this = calloc( 1, sizeof( struct mlt_producer_s ) );
55
56 // Initialise it
57 if ( mlt_producer_init( this, NULL ) == 0 )
58 {
59 // Get the properties
60 mlt_properties properties = mlt_producer_properties( this );
61
62 // Set the resource property (required for all producers)
63 mlt_properties_set( properties, "resource", file );
64
65 // Register our get_frame implementation
66 this->get_frame = producer_get_frame;
67
68 // Open the file
69 if ( producer_open( this, file ) != 0 )
70 {
71 // Clean up
72 mlt_producer_close( this );
73 this = NULL;
74 }
75 }
76 }
77
78 return this;
79 }
80
81 /** Find the default streams.
82 */
83
84 static void find_default_streams( AVFormatContext *context, int *audio_index, int *video_index )
85 {
86 int i;
87
88 // Allow for multiple audio and video streams in the file and select first of each (if available)
89 for( i = 0; i < context->nb_streams; i++ )
90 {
91 // Get the codec context
92 AVCodecContext *codec_context = &context->streams[ i ]->codec;
93
94 // Determine the type and obtain the first index of each type
95 switch( codec_context->codec_type )
96 {
97 case CODEC_TYPE_VIDEO:
98 if ( *video_index < 0 )
99 *video_index = i;
100 break;
101 case CODEC_TYPE_AUDIO:
102 if ( *audio_index < 0 )
103 *audio_index = i;
104 break;
105 default:
106 break;
107 }
108 }
109 }
110
111 /** Producer file destructor.
112 */
113
114 static void producer_file_close( void *context )
115 {
116 if ( context != NULL )
117 {
118 // Lock the mutex now
119 avformat_lock( );
120
121 // Close the file
122 av_close_input_file( context );
123
124 // Unlock the mutex now
125 avformat_unlock( );
126 }
127 }
128
129 /** Producer file destructor.
130 */
131
132 static void producer_codec_close( void *codec )
133 {
134 if ( codec != NULL )
135 {
136 // Lock the mutex now
137 avformat_lock( );
138
139 // Close the file
140 avcodec_close( codec );
141
142 // Unlock the mutex now
143 avformat_unlock( );
144 }
145 }
146
147 /** Open the file.
148 */
149
150 static int producer_open( mlt_producer this, char *file )
151 {
152 // Return an error code (0 == no error)
153 int error = 0;
154
155 // Context for avformat
156 AVFormatContext *context = NULL;
157
158 // Get the properties
159 mlt_properties properties = mlt_producer_properties( this );
160
161 // We will treat everything with the producer fps
162 double fps = mlt_properties_get_double( properties, "fps" );
163
164 // Lock the mutex now
165 avformat_lock( );
166
167 // If "MRL", then create AVInputFormat
168 AVInputFormat *format = NULL;
169 AVFormatParameters *params = NULL;
170 char *standard = NULL;
171 char *mrl = strchr( file, ':' );
172
173 // AV option (0 = both, 1 = video, 2 = audio)
174 int av = 0;
175
176 // Setting lowest log level
177 av_log_set_level( -1 );
178
179 // Only if there is not a protocol specification that avformat can handle
180 if ( mrl && !url_exist( file ) )
181 {
182 // 'file' becomes format abbreviation
183 mrl[0] = 0;
184
185 // Lookup the format
186 format = av_find_input_format( file );
187
188 // Eat the format designator
189 file = ++mrl;
190
191 if ( format )
192 {
193 // Allocate params
194 params = calloc( sizeof( AVFormatParameters ), 1 );
195
196 // These are required by video4linux (defaults)
197 params->width = 640;
198 params->height = 480;
199 params->frame_rate = 25;
200 params->frame_rate_base = 1;
201 params->device = file;
202 params->channels = 2;
203 params->sample_rate = 48000;
204 }
205
206 // Parse out params
207 mrl = strchr( file, '?' );
208 while ( mrl )
209 {
210 mrl[0] = 0;
211 char *name = strdup( ++mrl );
212 char *value = strchr( name, ':' );
213 if ( value )
214 {
215 value[0] = 0;
216 value++;
217 char *t = strchr( value, '&' );
218 if ( t )
219 t[0] = 0;
220 if ( !strcmp( name, "frame_rate" ) )
221 params->frame_rate = atoi( value );
222 else if ( !strcmp( name, "frame_rate_base" ) )
223 params->frame_rate_base = atoi( value );
224 else if ( !strcmp( name, "sample_rate" ) )
225 params->sample_rate = atoi( value );
226 else if ( !strcmp( name, "channels" ) )
227 params->channels = atoi( value );
228 else if ( !strcmp( name, "width" ) )
229 params->width = atoi( value );
230 else if ( !strcmp( name, "height" ) )
231 params->height = atoi( value );
232 else if ( !strcmp( name, "standard" ) )
233 {
234 standard = strdup( value );
235 params->standard = standard;
236 }
237 else if ( !strcmp( name, "av" ) )
238 av = atoi( value );
239 }
240 free( name );
241 mrl = strchr( mrl, '&' );
242 }
243 }
244
245 // Now attempt to open the file
246 error = av_open_input_file( &context, file, format, 0, params );
247 error = error < 0;
248
249 // Cleanup AVFormatParameters
250 free( standard );
251 free( params );
252
253 // If successful, then try to get additional info
254 if ( error == 0 )
255 {
256 // Get the stream info
257 error = av_find_stream_info( context ) < 0;
258
259 // Continue if no error
260 if ( error == 0 )
261 {
262 // We will default to the first audio and video streams found
263 int audio_index = -1;
264 int video_index = -1;
265 int av_bypass = 0;
266
267 // Now set properties where we can (use default unknowns if required)
268 if ( context->duration != AV_NOPTS_VALUE )
269 {
270 // This isn't going to be accurate for all formats
271 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps );
272 mlt_properties_set_position( properties, "out", frames - 2 );
273 mlt_properties_set_position( properties, "length", frames - 1 );
274 }
275
276 // Find default audio and video streams
277 find_default_streams( context, &audio_index, &video_index );
278
279 if ( context->start_time != AV_NOPTS_VALUE )
280 mlt_properties_set_double( properties, "start_time", context->start_time );
281
282 // Check if we're seekable (something funny about mpeg here :-/)
283 if ( strcmp( file, "pipe:" ) && strncmp( file, "http://", 6 ) )
284 mlt_properties_set_int( properties, "seekable", av_seek_frame( context, -1, mlt_properties_get_double( properties, "start_time" ) ) >= 0 );
285 else
286 av_bypass = 1;
287
288 // Store selected audio and video indexes on properties
289 mlt_properties_set_int( properties, "audio_index", audio_index );
290 mlt_properties_set_int( properties, "video_index", video_index );
291
292 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
293 if ( av == 0 && !av_bypass && audio_index != -1 && video_index != -1 )
294 {
295 // We'll use the open one as our video_context
296 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
297
298 // And open again for our audio context
299 av_open_input_file( &context, file, NULL, 0, NULL );
300 av_find_stream_info( context );
301
302 // Audio context
303 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
304 }
305 else if ( av != 2 && video_index != -1 )
306 {
307 // We only have a video context
308 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
309 }
310 else if ( audio_index != -1 )
311 {
312 // We only have an audio context
313 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
314 }
315 else
316 {
317 // Something has gone wrong
318 error = -1;
319 }
320
321 mlt_properties_set_int( properties, "av_bypass", av_bypass );
322 }
323 }
324
325 // Unlock the mutex now
326 avformat_unlock( );
327
328 return error;
329 }
330
331 /** Convert a frame position to a time code.
332 */
333
334 static double producer_time_of_frame( mlt_producer this, mlt_position position )
335 {
336 // Get the properties
337 mlt_properties properties = mlt_producer_properties( this );
338
339 // Obtain the fps
340 double fps = mlt_properties_get_double( properties, "fps" );
341
342 // Do the calc
343 return ( double )position / fps;
344 }
345
346 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt, mlt_image_format format, int width, int height )
347 {
348 // EXPERIMENTAL IMAGE NORMALISATIONS
349 if ( pix_fmt == PIX_FMT_YUV420P && format == mlt_image_yuv422 )
350 {
351 register int i, j;
352 register int half = width >> 1;
353 register uint8_t *Y = ( ( AVPicture * )frame )->data[ 0 ];
354 register uint8_t *U = ( ( AVPicture * )frame )->data[ 1 ];
355 register uint8_t *V = ( ( AVPicture * )frame )->data[ 2 ];
356 register uint8_t *d = buffer;
357 register uint8_t *y, *u, *v;
358
359 i = height >> 1;
360 while ( i -- )
361 {
362 y = Y;
363 u = U;
364 v = V;
365 j = half;
366 while ( j -- )
367 {
368 *d ++ = *y ++;
369 *d ++ = *u ++;
370 *d ++ = *y ++;
371 *d ++ = *v ++;
372 }
373
374 Y += ( ( AVPicture * )frame )->linesize[ 0 ];
375 y = Y;
376 u = U;
377 v = V;
378 j = half;
379 while ( j -- )
380 {
381 *d ++ = *y ++;
382 *d ++ = *u ++;
383 *d ++ = *y ++;
384 *d ++ = *v ++;
385 }
386
387 Y += ( ( AVPicture * )frame )->linesize[ 0 ];
388 U += ( ( AVPicture * )frame )->linesize[ 1 ];
389 V += ( ( AVPicture * )frame )->linesize[ 2 ];
390 }
391 }
392 else if ( format == mlt_image_yuv420p )
393 {
394 AVPicture pict;
395 pict.data[0] = buffer;
396 pict.data[1] = buffer + width * height;
397 pict.data[2] = buffer + ( 3 * width * height ) / 2;
398 pict.linesize[0] = width;
399 pict.linesize[1] = width >> 1;
400 pict.linesize[2] = width >> 1;
401 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
402 }
403 else if ( format == mlt_image_rgb24 )
404 {
405 AVPicture output;
406 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
407 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
408 }
409 else
410 {
411 AVPicture output;
412 avpicture_fill( &output, buffer, PIX_FMT_YUV422, width, height );
413 img_convert( &output, PIX_FMT_YUV422, (AVPicture *)frame, pix_fmt, width, height );
414 }
415 }
416
417 /** Get an image from a frame.
418 */
419
420 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
421 {
422 // Get the properties from the frame
423 mlt_properties frame_properties = mlt_frame_properties( frame );
424
425 // Obtain the frame number of this frame
426 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
427
428 // Get the producer
429 mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
430
431 // Get the producer properties
432 mlt_properties properties = mlt_producer_properties( this );
433
434 // Fetch the video_context
435 AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
436
437 // Get the video_index
438 int index = mlt_properties_get_int( properties, "video_index" );
439
440 // Obtain the expected frame numer
441 mlt_position expected = mlt_properties_get_position( properties, "video_expected" );
442
443 // Calculate the real time code
444 double real_timecode = producer_time_of_frame( this, position );
445
446 // Get the video stream
447 AVStream *stream = context->streams[ index ];
448
449 // Get codec context
450 AVCodecContext *codec_context = &stream->codec;
451
452 // Packet
453 AVPacket pkt;
454
455 // Get the conversion frame
456 AVFrame *av_frame = mlt_properties_get_data( properties, "av_frame", NULL );
457
458 // Special case pause handling flag
459 int paused = 0;
460
461 // Special case ffwd handling
462 int ignore = 0;
463
464 // Current time calcs
465 double current_time = mlt_properties_get_double( properties, "current_time" );
466
467 // We may want to use the source fps if available
468 double source_fps = mlt_properties_get_double( properties, "source_fps" );
469
470 // Get the seekable status
471 int seekable = mlt_properties_get_int( properties, "seekable" );
472
473 // Generate the size in bytes
474 int size = 0;
475
476 // Hopefully provide better support for streams...
477 int av_bypass = mlt_properties_get_int( properties, "av_bypass" );
478
479 // Set the result arguments that we know here (only *buffer is now required)
480 *width = codec_context->width;
481 *height = codec_context->height;
482
483 switch ( *format )
484 {
485 case mlt_image_yuv420p:
486 size = *width * 3 * ( *height + 1 ) / 2;
487 break;
488 case mlt_image_rgb24:
489 size = *width * ( *height + 1 ) * 3;
490 break;
491 default:
492 *format = mlt_image_yuv422;
493 size = *width * ( *height + 1 ) * 2;
494 break;
495 }
496
497 // Set this on the frame properties
498 mlt_properties_set_int( frame_properties, "width", *width );
499 mlt_properties_set_int( frame_properties, "height", *height );
500
501 // Construct the output image
502 *buffer = mlt_pool_alloc( size );
503
504 // Seek if necessary
505 if ( position != expected )
506 {
507 if ( position + 1 == expected )
508 {
509 // We're paused - use last image
510 paused = 1;
511 }
512 else if ( !seekable && position > expected && ( position - expected ) < 250 )
513 {
514 // Fast forward - seeking is inefficient for small distances - just ignore following frames
515 ignore = position - expected;
516 }
517 else if ( codec_context->has_b_frames == 0 || ( position < expected || position - expected >= 12 ) )
518 {
519 // Set to the real timecode
520 av_seek_frame( context, -1, mlt_properties_get_double( properties, "start_time" ) + real_timecode * 1000000.0 );
521
522 // Remove the cached info relating to the previous position
523 mlt_properties_set_double( properties, "current_time", real_timecode );
524
525 mlt_properties_set_data( properties, "av_frame", NULL, 0, NULL, NULL );
526 av_frame = NULL;
527 }
528 }
529
530 // Duplicate the last image if necessary
531 if ( av_frame != NULL && ( paused || mlt_properties_get_double( properties, "current_time" ) >= real_timecode ) &&
532 av_bypass == 0 )
533 {
534 // Duplicate it
535 convert_image( av_frame, *buffer, codec_context->pix_fmt, *format, *width, *height );
536
537 // Set this on the frame properties
538 mlt_properties_set_data( frame_properties, "image", *buffer, size, ( mlt_destructor )mlt_pool_release, NULL );
539 }
540 else
541 {
542 int ret = 0;
543 int got_picture = 0;
544
545 memset( &pkt, 0, sizeof( pkt ) );
546
547 // Construct an AVFrame for YUV422 conversion
548 if ( av_frame == NULL )
549 {
550 av_frame = calloc( 1, sizeof( AVFrame ) );
551 mlt_properties_set_data( properties, "av_frame", av_frame, 0, free, NULL );
552 }
553
554 while( ret >= 0 && !got_picture )
555 {
556 // Read a packet
557 ret = av_read_frame( context, &pkt );
558
559 // We only deal with video from the selected video_index
560 if ( ret >= 0 && pkt.stream_index == index && pkt.size > 0 )
561 {
562 // Decode the image
563 ret = avcodec_decode_video( codec_context, av_frame, &got_picture, pkt.data, pkt.size );
564
565 if ( got_picture )
566 {
567 if ( pkt.pts != AV_NOPTS_VALUE )
568 current_time = ( double )pkt.pts / 1000000.0;
569 else
570 current_time = real_timecode;
571
572 // Handle ignore
573 if ( ( int )( current_time * 100 ) < ( int )( real_timecode * 100 ) - 7 )
574 {
575 ignore = 0;
576 got_picture = 0;
577 }
578 else if ( current_time >= real_timecode )
579 {
580 //current_time = real_timecode;
581 ignore = 0;
582 }
583 else if ( ignore -- )
584 {
585 got_picture = 0;
586 }
587 mlt_properties_set_int( properties, "top_field_first", av_frame->top_field_first );
588 }
589 }
590
591 // We're finished with this packet regardless
592 av_free_packet( &pkt );
593 }
594
595 // Now handle the picture if we have one
596 if ( got_picture )
597 {
598 convert_image( av_frame, *buffer, codec_context->pix_fmt, *format, *width, *height );
599
600 mlt_properties_set_data( frame_properties, "image", *buffer, size, (mlt_destructor)mlt_pool_release, NULL );
601
602 if ( current_time == 0 && source_fps != 0 )
603 {
604 double fps = mlt_properties_get_double( properties, "fps" );
605 current_time = ceil( source_fps * ( double )position / fps ) * ( 1 / source_fps );
606 mlt_properties_set_double( properties, "current_time", current_time );
607 }
608 else
609 {
610 mlt_properties_set_double( properties, "current_time", current_time );
611 }
612 }
613 }
614
615 // Set the field order property for this frame
616 mlt_properties_set_int( frame_properties, "top_field_first",
617 mlt_properties_get_int( properties, "top_field_first" ) );
618
619 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
620 mlt_properties_set_position( properties, "video_expected", position + 1 );
621
622 return 0;
623 }
624
625 /** Set up video handling.
626 */
627
628 static void producer_set_up_video( mlt_producer this, mlt_frame frame )
629 {
630 // Get the properties
631 mlt_properties properties = mlt_producer_properties( this );
632
633 // Fetch the video_context
634 AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
635
636 // Get the video_index
637 int index = mlt_properties_get_int( properties, "video_index" );
638
639 // Get the frame properties
640 mlt_properties frame_properties = mlt_frame_properties( frame );
641
642 if ( context != NULL && index != -1 )
643 {
644 // Get the video stream
645 AVStream *stream = context->streams[ index ];
646
647 // Get codec context
648 AVCodecContext *codec_context = &stream->codec;
649
650 // Get the codec
651 AVCodec *codec = mlt_properties_get_data( properties, "video_codec", NULL );
652
653 // Initialise the codec if necessary
654 if ( codec == NULL )
655 {
656 // Find the codec
657 codec = avcodec_find_decoder( codec_context->codec_id );
658
659 // If we don't have a codec and we can't initialise it, we can't do much more...
660 if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
661 {
662 // Now store the codec with its destructor
663 mlt_properties_set_data( properties, "video_codec", codec_context, 0, producer_codec_close, NULL );
664 }
665 else
666 {
667 // Remember that we can't use this later
668 mlt_properties_set_int( properties, "video_index", -1 );
669 }
670 }
671
672 // No codec, no show...
673 if ( codec != NULL )
674 {
675 double source_fps = 0;
676
677 // XXX: We won't know the real aspect ratio until an image is decoded
678 // but we do need it now (to satisfy filter_resize) - take a guess based
679 // on pal/ntsc
680 if ( codec_context->sample_aspect_ratio.num > 0 )
681 {
682 mlt_properties_set_double( properties, "aspect_ratio", av_q2d( codec_context->sample_aspect_ratio ) );
683 }
684 else
685 {
686 int is_pal = mlt_properties_get_double( properties, "fps" ) == 25.0;
687 mlt_properties_set_double( properties, "aspect_ratio", is_pal ? 128.0/117.0 : 72.0/79.0 );
688 }
689
690 //fprintf( stderr, "AVFORMAT: sample aspect %f %dx%d\n", av_q2d( codec_context->sample_aspect_ratio ), codec_context->width, codec_context->height );
691
692 // Determine the fps
693 source_fps = ( double )codec_context->frame_rate / ( codec_context->frame_rate_base == 0 ? 1 : codec_context->frame_rate_base );
694
695 // We'll use fps if it's available
696 if ( source_fps > 0 && source_fps < 30 )
697 mlt_properties_set_double( properties, "source_fps", source_fps );
698
699 // Set the width and height
700 mlt_properties_set_int( frame_properties, "width", codec_context->width );
701 mlt_properties_set_int( frame_properties, "height", codec_context->height );
702
703 mlt_frame_push_get_image( frame, producer_get_image );
704 mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
705 }
706 else
707 {
708 mlt_properties_set_int( frame_properties, "test_image", 1 );
709 }
710 }
711 else
712 {
713 mlt_properties_set_int( frame_properties, "test_image", 1 );
714 }
715 }
716
717 /** Get the audio from a frame.
718 */
719
720 static int producer_get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
721 {
722 // Get the properties from the frame
723 mlt_properties frame_properties = mlt_frame_properties( frame );
724
725 // Obtain the frame number of this frame
726 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
727
728 // Get the producer
729 mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
730
731 // Get the producer properties
732 mlt_properties properties = mlt_producer_properties( this );
733
734 // Fetch the audio_context
735 AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
736
737 // Get the audio_index
738 int index = mlt_properties_get_int( properties, "audio_index" );
739
740 // Get the seekable status
741 int seekable = mlt_properties_get_int( properties, "seekable" );
742
743 // Obtain the expected frame numer
744 mlt_position expected = mlt_properties_get_position( properties, "audio_expected" );
745
746 // Obtain the resample context if it exists (not always needed)
747 ReSampleContext *resample = mlt_properties_get_data( properties, "audio_resample", NULL );
748
749 // Obtain the audio buffer
750 int16_t *audio_buffer = mlt_properties_get_data( properties, "audio_buffer", NULL );
751
752 // Get amount of audio used
753 int audio_used = mlt_properties_get_int( properties, "audio_used" );
754
755 // Calculate the real time code
756 double real_timecode = producer_time_of_frame( this, position );
757
758 // Get the audio stream
759 AVStream *stream = context->streams[ index ];
760
761 // Get codec context
762 AVCodecContext *codec_context = &stream->codec;
763
764 // Packet
765 AVPacket pkt;
766
767 // Number of frames to ignore (for ffwd)
768 int ignore = 0;
769
770 // Flag for paused (silence)
771 int paused = 0;
772
773 // Check for resample and create if necessary
774 if ( resample == NULL && codec_context->channels <= 2 )
775 {
776 // Create the resampler
777 resample = audio_resample_init( *channels, codec_context->channels, *frequency, codec_context->sample_rate );
778
779 // And store it on properties
780 mlt_properties_set_data( properties, "audio_resample", resample, 0, ( mlt_destructor )audio_resample_close, NULL );
781 }
782 else if ( resample == NULL )
783 {
784 *channels = codec_context->channels;
785 *frequency = codec_context->sample_rate;
786 }
787
788 // Check for audio buffer and create if necessary
789 if ( audio_buffer == NULL )
790 {
791 // Allocate the audio buffer
792 audio_buffer = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
793
794 // And store it on properties for reuse
795 mlt_properties_set_data( properties, "audio_buffer", audio_buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
796 }
797
798 // Seek if necessary
799 if ( position != expected )
800 {
801 if ( position + 1 == expected )
802 {
803 // We're paused - silence required
804 paused = 1;
805 }
806 else if ( !seekable && position > expected && ( position - expected ) < 250 )
807 {
808 // Fast forward - seeking is inefficient for small distances - just ignore following frames
809 ignore = position - expected;
810 }
811 else if ( position < expected || position - expected >= 12 )
812 {
813 // Set to the real timecode
814 if ( av_seek_frame( context, -1, mlt_properties_get_double( properties, "start_time" ) + real_timecode * 1000000.0 ) != 0 )
815 paused = 1;
816
817 // Clear the usage in the audio buffer
818 audio_used = 0;
819 }
820 }
821
822 // Get the audio if required
823 if ( !paused )
824 {
825 int ret = 0;
826 int got_audio = 0;
827 int16_t *temp = mlt_pool_alloc( sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE );
828
829 memset( &pkt, 0, sizeof( pkt ) );
830
831 while( ret >= 0 && !got_audio )
832 {
833 // Check if the buffer already contains the samples required
834 if ( audio_used >= *samples && ignore == 0 )
835 {
836 got_audio = 1;
837 break;
838 }
839
840 // Read a packet
841 ret = av_read_frame( context, &pkt );
842
843 int len = pkt.size;
844 uint8_t *ptr = pkt.data;
845 int data_size;
846
847 // We only deal with audio from the selected audio_index
848 while ( ptr != NULL && ret >= 0 && pkt.stream_index == index && len > 0 )
849 {
850 // Decode the audio
851 ret = avcodec_decode_audio( codec_context, temp, &data_size, ptr, len );
852
853 if ( ret < 0 )
854 {
855 ret = 0;
856 break;
857 }
858
859 len -= ret;
860 ptr += ret;
861
862 if ( data_size > 0 )
863 {
864 if ( resample != NULL )
865 {
866 audio_used += audio_resample( resample, &audio_buffer[ audio_used * *channels ], temp, data_size / ( codec_context->channels * sizeof( int16_t ) ) );
867 }
868 else
869 {
870 memcpy( &audio_buffer[ audio_used * *channels ], temp, data_size );
871 audio_used += data_size / ( codec_context->channels * sizeof( int16_t ) );
872 }
873
874 // Handle ignore
875 while ( ignore && audio_used > *samples )
876 {
877 ignore --;
878 audio_used -= *samples;
879 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * sizeof( int16_t ) );
880 }
881 }
882
883 // If we're behind, ignore this packet
884 float current_pts = (float)pkt.pts / 1000000.0;
885 if ( seekable && ( !ignore && current_pts <= ( real_timecode - 0.02 ) ) )
886 ignore = 1;
887 }
888
889 // We're finished with this packet regardless
890 av_free_packet( &pkt );
891 }
892
893 *buffer = mlt_pool_alloc( *samples * *channels * sizeof( int16_t ) );
894 mlt_properties_set_data( frame_properties, "audio", *buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
895
896 // Now handle the audio if we have enough
897 if ( audio_used >= *samples )
898 {
899 memcpy( *buffer, audio_buffer, *samples * *channels * sizeof( int16_t ) );
900 audio_used -= *samples;
901 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * *channels * sizeof( int16_t ) );
902 }
903 else
904 {
905 memset( *buffer, 0, *samples * *channels * sizeof( int16_t ) );
906 }
907
908 // Store the number of audio samples still available
909 mlt_properties_set_int( properties, "audio_used", audio_used );
910
911 // Release the temporary audio
912 mlt_pool_release( temp );
913 }
914 else
915 {
916 // Get silence and don't touch the context
917 frame->get_audio = NULL;
918 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
919 }
920
921 // Regardless of speed (other than paused), we expect to get the next frame
922 if ( !paused )
923 mlt_properties_set_position( properties, "audio_expected", position + 1 );
924
925 return 0;
926 }
927
928 /** Set up audio handling.
929 */
930
931 static void producer_set_up_audio( mlt_producer this, mlt_frame frame )
932 {
933 // Get the properties
934 mlt_properties properties = mlt_producer_properties( this );
935
936 // Fetch the audio_context
937 AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
938
939 // Get the audio_index
940 int index = mlt_properties_get_int( properties, "audio_index" );
941
942 // Deal with audio context
943 if ( context != NULL && index != -1 )
944 {
945 // Get the frame properties
946 mlt_properties frame_properties = mlt_frame_properties( frame );
947
948 // Get the audio stream
949 AVStream *stream = context->streams[ index ];
950
951 // Get codec context
952 AVCodecContext *codec_context = &stream->codec;
953
954 // Get the codec
955 AVCodec *codec = mlt_properties_get_data( properties, "audio_codec", NULL );
956
957 // Initialise the codec if necessary
958 if ( codec == NULL )
959 {
960 // Find the codec
961 codec = avcodec_find_decoder( codec_context->codec_id );
962
963 // If we don't have a codec and we can't initialise it, we can't do much more...
964 if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
965 {
966 // Now store the codec with its destructor
967 mlt_properties_set_data( properties, "audio_codec", codec_context, 0, producer_codec_close, NULL );
968
969 }
970 else
971 {
972 // Remember that we can't use this later
973 mlt_properties_set_int( properties, "audio_index", -1 );
974 }
975 }
976
977 // No codec, no show...
978 if ( codec != NULL )
979 {
980 frame->get_audio = producer_get_audio;
981 mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
982 }
983 }
984 }
985
986 /** Our get frame implementation.
987 */
988
989 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index )
990 {
991 // Create an empty frame
992 *frame = mlt_frame_init( );
993
994 // Update timecode on the frame we're creating
995 mlt_frame_set_position( *frame, mlt_producer_position( this ) );
996
997 // Set the position of this producer
998 mlt_properties_set_position( mlt_frame_properties( *frame ), "avformat_position", mlt_producer_position( this ) );
999
1000 // Set up the video
1001 producer_set_up_video( this, *frame );
1002
1003 // Set up the audio
1004 producer_set_up_audio( this, *frame );
1005
1006 // Set the aspect_ratio
1007 mlt_properties_set_double( mlt_frame_properties( *frame ), "aspect_ratio", mlt_properties_get_double( mlt_producer_properties( this ), "aspect_ratio" ) );
1008
1009 // Calculate the next timecode
1010 mlt_producer_prepare_next( this );
1011
1012 return 0;
1013 }