minor clean ups; added a null consumer for easier valgrind testing
[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 // Find default audio and video streams
271 find_default_streams( context, &audio_index, &video_index );
272
273 // Check if we're seekable (something funny about mpeg here :-/)
274 if ( strstr( file, ".mpg" ) == NULL && strstr( file, ".mpeg" ) == NULL )
275 mlt_properties_set_int( properties, "seekable", av_seek_frame( context, -1, context->start_time ) >= 0 );
276 else
277 mlt_properties_set_int( properties, "seekable", 1 );
278
279 // Store selected audio and video indexes on properties
280 mlt_properties_set_int( properties, "audio_index", audio_index );
281 mlt_properties_set_int( properties, "video_index", video_index );
282
283 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
284 if ( audio_index != -1 && video_index != -1 )
285 {
286 // We'll use the open one as our video_context
287 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
288
289 // And open again for our audio context
290 av_open_input_file( &context, file, NULL, 0, NULL );
291 av_find_stream_info( context );
292
293 // Audio context
294 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
295 }
296 else if ( video_index != -1 )
297 {
298 // We only have a video context
299 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
300 }
301 else if ( audio_index != -1 )
302 {
303 // We only have an audio context
304 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
305 }
306 else
307 {
308 // Something has gone wrong
309 error = -1;
310 }
311 }
312 }
313
314 // Unlock the mutex now
315 avformat_unlock( );
316
317 return error;
318 }
319
320 /** Convert a frame position to a time code.
321 */
322
323 static double producer_time_of_frame( mlt_producer this, mlt_position position )
324 {
325 // Get the properties
326 mlt_properties properties = mlt_producer_properties( this );
327
328 // Obtain the fps
329 double fps = mlt_properties_get_double( properties, "fps" );
330
331 // Do the calc
332 return ( double )position / fps;
333 }
334
335 /** Get an image from a frame.
336 */
337
338 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
339 {
340 // Get the properties from the frame
341 mlt_properties frame_properties = mlt_frame_properties( frame );
342
343 // Obtain the frame number of this frame
344 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
345
346 // Get the producer
347 mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
348
349 // Get the producer properties
350 mlt_properties properties = mlt_producer_properties( this );
351
352 // Fetch the video_context
353 AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
354
355 // Get the video_index
356 int index = mlt_properties_get_int( properties, "video_index" );
357
358 // Obtain the expected frame numer
359 mlt_position expected = mlt_properties_get_position( properties, "video_expected" );
360
361 // Calculate the real time code
362 double real_timecode = producer_time_of_frame( this, position );
363
364 // Get the video stream
365 AVStream *stream = context->streams[ index ];
366
367 // Get codec context
368 AVCodecContext *codec_context = &stream->codec;
369
370 // Packet
371 AVPacket pkt;
372
373 // Get the conversion frame
374 AVPicture *output = mlt_properties_get_data( properties, "video_output_frame", NULL );
375
376 // Special case pause handling flag
377 int paused = 0;
378
379 // Special case ffwd handling
380 int ignore = 0;
381
382 // Current time calcs
383 double current_time = mlt_properties_get_double( properties, "current_time" );
384
385 // We may want to use the source fps if available
386 double source_fps = mlt_properties_get_double( properties, "source_fps" );
387
388 // Set the result arguments that we know here (only *buffer is now required)
389 *format = mlt_image_yuv422;
390 *width = codec_context->width;
391 *height = codec_context->height;
392
393 // Set this on the frame properties
394 mlt_properties_set_int( frame_properties, "width", *width );
395 mlt_properties_set_int( frame_properties, "height", *height );
396
397 // Lock the mutex now
398 avformat_lock( );
399
400 // Construct an AVFrame for YUV422 conversion
401 if ( output == NULL )
402 {
403 int size = avpicture_get_size( PIX_FMT_YUV422, *width, *height + 1 );
404 uint8_t *buf = mlt_pool_alloc( size );
405 output = mlt_pool_alloc( sizeof( AVPicture ) );
406 avpicture_fill( output, buf, PIX_FMT_YUV422, *width, *height );
407 mlt_properties_set_data( properties, "video_output_frame", output, 0, ( mlt_destructor )mlt_pool_release, NULL );
408 mlt_properties_set_data( properties, "video_output_buffer", buf, 0, ( mlt_destructor )mlt_pool_release, NULL );
409 }
410
411 // Seek if necessary
412 if ( position != expected )
413 {
414 if ( position + 1 == expected )
415 {
416 // We're paused - use last image
417 paused = 1;
418 }
419 else if ( position > expected && ( position - expected ) < 250 )
420 {
421 // Fast forward - seeking is inefficient for small distances - just ignore following frames
422 ignore = position - expected;
423 }
424 else
425 {
426 // Set to the real timecode
427 av_seek_frame( context, -1, context->start_time + real_timecode * 1000000.0 );
428
429 // Remove the cached info relating to the previous position
430 mlt_properties_set_double( properties, "current_time", real_timecode );
431 mlt_properties_set_data( properties, "current_image", NULL, 0, NULL, NULL );
432 }
433 }
434
435 // Duplicate the last image if necessary
436 if ( mlt_properties_get_data( properties, "current_image", NULL ) != NULL &&
437 ( paused || mlt_properties_get_double( properties, "current_time" ) >= real_timecode ) )
438 {
439 // Get current image and size
440 int size = 0;
441 uint8_t *image = mlt_properties_get_data( properties, "current_image", &size );
442
443 // Duplicate it
444 *buffer = mlt_pool_alloc( size );
445 memcpy( *buffer, image, size );
446
447 // Set this on the frame properties
448 mlt_properties_set_data( frame_properties, "image", *buffer, size, ( mlt_destructor )mlt_pool_release, NULL );
449 }
450 else
451 {
452 int ret = 0;
453 int got_picture = 0;
454 AVFrame frame;
455
456 memset( &pkt, 0, sizeof( pkt ) );
457 memset( &frame, 0, sizeof( frame ) );
458
459 while( ret >= 0 && !got_picture )
460 {
461 // Read a packet
462 ret = av_read_frame( context, &pkt );
463
464 // We only deal with video from the selected video_index
465 if ( ret >= 0 && pkt.stream_index == index && pkt.size > 0 )
466 {
467 // Decode the image
468 ret = avcodec_decode_video( codec_context, &frame, &got_picture, pkt.data, pkt.size );
469
470 if ( got_picture )
471 {
472 if ( pkt.pts != AV_NOPTS_VALUE && pkt.pts != 0 )
473 current_time = ( double )pkt.pts / 1000000.0;
474 else
475 current_time = real_timecode;
476
477 // Handle ignore
478 if ( ( int )( current_time * 100 ) < ( int )( real_timecode * 100 ) - 7 )
479 {
480 ignore = 0;
481 got_picture = 0;
482 }
483 else if ( current_time >= real_timecode )
484 {
485 //current_time = real_timecode;
486 ignore = 0;
487 }
488 else if ( ignore -- )
489 {
490 got_picture = 0;
491 }
492 mlt_properties_set_int( properties, "top_field_first", frame.top_field_first );
493 }
494 }
495
496 // We're finished with this packet regardless
497 av_free_packet( &pkt );
498 }
499
500 // Now handle the picture if we have one
501 if ( got_picture )
502 {
503 // Get current image and size
504 int size = 0;
505 uint8_t *image = mlt_properties_get_data( properties, "current_image", &size );
506
507 if ( image == NULL || size != *width * *height * 2 )
508 {
509 size = *width * ( *height + 1 ) * 2;
510 image = mlt_pool_alloc( size );
511 mlt_properties_set_data( properties, "current_image", image, size, ( mlt_destructor )mlt_pool_release, NULL );
512 }
513
514 *buffer = mlt_pool_alloc( size );
515
516 // EXPERIMENTAL IMAGE NORMALISATIONS
517 if ( codec_context->pix_fmt == PIX_FMT_YUV420P )
518 {
519 register int i, j;
520 register int half = *width >> 1;
521 register uint8_t *Y = ( ( AVPicture * )&frame )->data[ 0 ];
522 register uint8_t *U = ( ( AVPicture * )&frame )->data[ 1 ];
523 register uint8_t *V = ( ( AVPicture * )&frame )->data[ 2 ];
524 register uint8_t *d = *buffer;
525 register uint8_t *y, *u, *v;
526
527 i = *height >> 1;
528 while ( i -- )
529 {
530 y = Y;
531 u = U;
532 v = V;
533 j = half;
534 while ( j -- )
535 {
536 *d ++ = *y ++;
537 *d ++ = *u ++;
538 *d ++ = *y ++;
539 *d ++ = *v ++;
540 }
541
542 Y += ( ( AVPicture * )&frame )->linesize[ 0 ];
543 y = Y;
544 u = U;
545 v = V;
546 j = half;
547 while ( j -- )
548 {
549 *d ++ = *y ++;
550 *d ++ = *u ++;
551 *d ++ = *y ++;
552 *d ++ = *v ++;
553 }
554
555 Y += ( ( AVPicture * )&frame )->linesize[ 0 ];
556 U += ( ( AVPicture * )&frame )->linesize[ 1 ];
557 V += ( ( AVPicture * )&frame )->linesize[ 2 ];
558 }
559 }
560 else
561 {
562 img_convert( output, PIX_FMT_YUV422, (AVPicture *)&frame, codec_context->pix_fmt, *width, *height );
563 memcpy( *buffer, output->data[ 0 ], size );
564 }
565
566 memcpy( image, *buffer, size );
567 mlt_properties_set_data( frame_properties, "image", *buffer, size, ( mlt_destructor )mlt_pool_release, NULL );
568
569 if ( current_time == 0 && source_fps != 0 )
570 {
571 double fps = mlt_properties_get_double( properties, "fps" );
572 current_time = ceil( source_fps * ( double )position / fps ) * ( 1 / source_fps );
573 mlt_properties_set_double( properties, "current_time", current_time );
574 }
575 else
576 {
577 mlt_properties_set_double( properties, "current_time", current_time );
578 }
579 }
580 }
581
582 // Set the field order property for this frame
583 mlt_properties_set_int( frame_properties, "top_field_first",
584 mlt_properties_get_int( properties, "top_field_first" ) );
585
586 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
587 mlt_properties_set_position( properties, "video_expected", position + 1 );
588
589 // Unlock the mutex now
590 avformat_unlock( );
591
592 return 0;
593 }
594
595 /** Set up video handling.
596 */
597
598 static void producer_set_up_video( mlt_producer this, mlt_frame frame )
599 {
600 // Get the properties
601 mlt_properties properties = mlt_producer_properties( this );
602
603 // Fetch the video_context
604 AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
605
606 // Get the video_index
607 int index = mlt_properties_get_int( properties, "video_index" );
608
609 // Get the frame properties
610 mlt_properties frame_properties = mlt_frame_properties( frame );
611
612 // Lock the mutex now
613 avformat_lock( );
614
615 if ( context != NULL && index != -1 )
616 {
617 // Get the video stream
618 AVStream *stream = context->streams[ index ];
619
620 // Get codec context
621 AVCodecContext *codec_context = &stream->codec;
622
623 // Get the codec
624 AVCodec *codec = mlt_properties_get_data( properties, "video_codec", NULL );
625
626 // Initialise the codec if necessary
627 if ( codec == NULL )
628 {
629 // Find the codec
630 codec = avcodec_find_decoder( codec_context->codec_id );
631
632 // If we don't have a codec and we can't initialise it, we can't do much more...
633 if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
634 {
635 // Now store the codec with its destructor
636 mlt_properties_set_data( properties, "video_codec", codec_context, 0, producer_codec_close, NULL );
637 }
638 else
639 {
640 // Remember that we can't use this later
641 mlt_properties_set_int( properties, "video_index", -1 );
642 }
643 }
644
645 // No codec, no show...
646 if ( codec != NULL )
647 {
648 double aspect_ratio = 1;
649 double source_fps = 0;
650
651 // Set aspect ratio
652 if ( codec_context->sample_aspect_ratio.num > 0 )
653 aspect_ratio = av_q2d( codec_context->sample_aspect_ratio );
654
655 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
656 //fprintf( stderr, "AVFORMAT: sample aspect %f %dx%d\n", av_q2d( codec_context->sample_aspect_ratio ), codec_context->width, codec_context->height );
657
658 // Determine the fps
659 source_fps = ( double )codec_context->frame_rate / ( codec_context->frame_rate_base == 0 ? 1 : codec_context->frame_rate_base );
660
661 // We'll use fps if it's available
662 if ( source_fps > 0 && source_fps < 30 )
663 mlt_properties_set_double( properties, "source_fps", source_fps );
664
665 // Set the width and height
666 mlt_properties_set_int( frame_properties, "width", codec_context->width );
667 mlt_properties_set_int( frame_properties, "height", codec_context->height );
668
669 mlt_frame_push_get_image( frame, producer_get_image );
670 mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
671 }
672 else
673 {
674 mlt_properties_set_int( frame_properties, "test_image", 1 );
675 }
676 }
677 else
678 {
679 mlt_properties_set_int( frame_properties, "test_image", 1 );
680 }
681
682 // Unlock the mutex now
683 avformat_unlock( );
684 }
685
686 /** Get the audio from a frame.
687 */
688
689 static int producer_get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
690 {
691 // Get the properties from the frame
692 mlt_properties frame_properties = mlt_frame_properties( frame );
693
694 // Obtain the frame number of this frame
695 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
696
697 // Get the producer
698 mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
699
700 // Get the producer properties
701 mlt_properties properties = mlt_producer_properties( this );
702
703 // Fetch the audio_context
704 AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
705
706 // Get the audio_index
707 int index = mlt_properties_get_int( properties, "audio_index" );
708
709 // Get the seekable status
710 int seekable = mlt_properties_get_int( properties, "seekable" );
711
712 // Obtain the expected frame numer
713 mlt_position expected = mlt_properties_get_position( properties, "audio_expected" );
714
715 // Obtain the resample context if it exists (not always needed)
716 ReSampleContext *resample = mlt_properties_get_data( properties, "audio_resample", NULL );
717
718 // Obtain the audio buffer
719 int16_t *audio_buffer = mlt_properties_get_data( properties, "audio_buffer", NULL );
720
721 // Get amount of audio used
722 int audio_used = mlt_properties_get_int( properties, "audio_used" );
723
724 // Calculate the real time code
725 double real_timecode = producer_time_of_frame( this, position );
726
727 // Get the audio stream
728 AVStream *stream = context->streams[ index ];
729
730 // Get codec context
731 AVCodecContext *codec_context = &stream->codec;
732
733 // Packet
734 AVPacket pkt;
735
736 // Number of frames to ignore (for ffwd)
737 int ignore = 0;
738
739 // Flag for paused (silence)
740 int paused = 0;
741
742 // Lock the mutex now
743 avformat_lock( );
744
745 // Check for resample and create if necessary
746 if ( resample == NULL && codec_context->channels <= 2 )
747 {
748 // Create the resampler
749 resample = audio_resample_init( *channels, codec_context->channels, *frequency, codec_context->sample_rate );
750
751 // And store it on properties
752 mlt_properties_set_data( properties, "audio_resample", resample, 0, ( mlt_destructor )audio_resample_close, NULL );
753 }
754 else if ( resample == NULL )
755 {
756 *channels = codec_context->channels;
757 *frequency = codec_context->sample_rate;
758 }
759
760 // Check for audio buffer and create if necessary
761 if ( audio_buffer == NULL )
762 {
763 // Allocate the audio buffer
764 audio_buffer = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
765
766 // And store it on properties for reuse
767 mlt_properties_set_data( properties, "audio_buffer", audio_buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
768 }
769
770 // Seek if necessary
771 if ( position != expected )
772 {
773 if ( position + 1 == expected )
774 {
775 // We're paused - silence required
776 paused = 1;
777 }
778 else if ( position > expected && ( position - expected ) < 250 )
779 {
780 // Fast forward - seeking is inefficient for small distances - just ignore following frames
781 ignore = position - expected;
782 }
783 else
784 {
785 // Set to the real timecode
786 if ( !seekable || av_seek_frame( context, -1, context->start_time + real_timecode * 1000000.0 ) != 0 )
787 paused = 1;
788
789 // Clear the usage in the audio buffer
790 audio_used = 0;
791 }
792 }
793
794 // Get the audio if required
795 if ( !paused )
796 {
797 int ret = 0;
798 int got_audio = 0;
799 int16_t *temp = mlt_pool_alloc( sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE );
800
801 memset( &pkt, 0, sizeof( pkt ) );
802
803 while( ret >= 0 && !got_audio )
804 {
805 // Check if the buffer already contains the samples required
806 if ( audio_used >= *samples && ignore == 0 )
807 {
808 got_audio = 1;
809 break;
810 }
811
812 // Read a packet
813 ret = av_read_frame( context, &pkt );
814
815 int len = pkt.size;
816 uint8_t *ptr = pkt.data;
817 int data_size;
818
819 // We only deal with audio from the selected audio_index
820 while ( ptr != NULL && ret >= 0 && pkt.stream_index == index && len > 0 )
821 {
822 // Decode the audio
823 ret = avcodec_decode_audio( codec_context, temp, &data_size, ptr, len );
824
825 if ( ret < 0 )
826 {
827 ret = 0;
828 break;
829 }
830
831 len -= ret;
832 ptr += ret;
833
834 if ( data_size > 0 )
835 {
836 if ( resample != NULL )
837 {
838 audio_used += audio_resample( resample, &audio_buffer[ audio_used * *channels ], temp, data_size / ( codec_context->channels * sizeof( int16_t ) ) );
839 }
840 else
841 {
842 memcpy( &audio_buffer[ audio_used * *channels ], temp, data_size );
843 audio_used += data_size / ( codec_context->channels * sizeof( int16_t ) );
844 }
845
846 // Handle ignore
847 while ( ignore && audio_used > *samples )
848 {
849 ignore --;
850 audio_used -= *samples;
851 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * sizeof( int16_t ) );
852 }
853 }
854
855 // If we're behind, ignore this packet
856 float current_pts = (float)pkt.pts / 1000000.0;
857 double discrepancy = mlt_properties_get_double( properties, "discrepancy" );
858 if ( current_pts != 0 && real_timecode != 0 )
859 {
860 if ( discrepancy != 1 )
861 discrepancy = ( discrepancy + ( real_timecode / current_pts ) ) / 2;
862 else
863 discrepancy = real_timecode / current_pts;
864 if ( discrepancy > 0.9 && discrepancy < 1.1 )
865 discrepancy = 1.0;
866 else
867 discrepancy = floor( discrepancy + 0.5 );
868
869 if ( discrepancy == 0 )
870 discrepancy = 1.0;
871
872 mlt_properties_set_double( properties, "discrepancy", discrepancy );
873 }
874
875 if ( seekable && ( !ignore && discrepancy * current_pts <= ( real_timecode - 0.02 ) ) )
876 ignore = 1;
877 }
878
879 // We're finished with this packet regardless
880 av_free_packet( &pkt );
881 }
882
883 *buffer = mlt_pool_alloc( *samples * *channels * sizeof( int16_t ) );
884 mlt_properties_set_data( frame_properties, "audio", *buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
885
886 // Now handle the audio if we have enough
887 if ( audio_used >= *samples )
888 {
889 memcpy( *buffer, audio_buffer, *samples * *channels * sizeof( int16_t ) );
890 audio_used -= *samples;
891 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * *channels * sizeof( int16_t ) );
892 }
893 else
894 {
895 memset( *buffer, 0, *samples * *channels * sizeof( int16_t ) );
896 }
897
898 // Store the number of audio samples still available
899 mlt_properties_set_int( properties, "audio_used", audio_used );
900
901 // Release the temporary audio
902 mlt_pool_release( temp );
903 }
904 else
905 {
906 // Get silence and don't touch the context
907 frame->get_audio = NULL;
908 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
909 }
910
911 // Regardless of speed (other than paused), we expect to get the next frame
912 if ( !paused )
913 mlt_properties_set_position( properties, "audio_expected", position + 1 );
914
915 // Unlock the mutex now
916 avformat_unlock( );
917
918 return 0;
919 }
920
921 /** Set up audio handling.
922 */
923
924 static void producer_set_up_audio( mlt_producer this, mlt_frame frame )
925 {
926 // Get the properties
927 mlt_properties properties = mlt_producer_properties( this );
928
929 // Fetch the audio_context
930 AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
931
932 // Get the audio_index
933 int index = mlt_properties_get_int( properties, "audio_index" );
934
935 // Lock the mutex now
936 avformat_lock( );
937
938 // Deal with audio context
939 if ( context != NULL && index != -1 )
940 {
941 // Get the frame properties
942 mlt_properties frame_properties = mlt_frame_properties( frame );
943
944 // Get the audio stream
945 AVStream *stream = context->streams[ index ];
946
947 // Get codec context
948 AVCodecContext *codec_context = &stream->codec;
949
950 // Get the codec
951 AVCodec *codec = mlt_properties_get_data( properties, "audio_codec", NULL );
952
953 // Initialise the codec if necessary
954 if ( codec == NULL )
955 {
956 // Find the codec
957 codec = avcodec_find_decoder( codec_context->codec_id );
958
959 // If we don't have a codec and we can't initialise it, we can't do much more...
960 if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
961 {
962 // Now store the codec with its destructor
963 mlt_properties_set_data( properties, "audio_codec", codec_context, 0, producer_codec_close, NULL );
964
965 }
966 else
967 {
968 // Remember that we can't use this later
969 mlt_properties_set_int( properties, "audio_index", -1 );
970 }
971 }
972
973 // No codec, no show...
974 if ( codec != NULL )
975 {
976 frame->get_audio = producer_get_audio;
977 mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
978 }
979 }
980
981 // Unlock the mutex now
982 avformat_unlock( );
983 }
984
985 /** Our get frame implementation.
986 */
987
988 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index )
989 {
990 // Create an empty frame
991 *frame = mlt_frame_init( );
992
993 // Update timecode on the frame we're creating
994 mlt_frame_set_position( *frame, mlt_producer_position( this ) );
995
996 // Set the position of this producer
997 mlt_properties_set_position( mlt_frame_properties( *frame ), "avformat_position", mlt_producer_position( this ) );
998
999 // Set up the video
1000 producer_set_up_video( this, *frame );
1001
1002 // Set up the audio
1003 producer_set_up_audio( this, *frame );
1004
1005 // Set the aspect_ratio
1006 mlt_properties_set_double( mlt_frame_properties( *frame ), "aspect_ratio", mlt_properties_get_double( mlt_producer_properties( this ), "aspect_ratio" ) );
1007
1008 // Calculate the next timecode
1009 mlt_producer_prepare_next( this );
1010
1011 return 0;
1012 }