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