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