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