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