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