c36c890c6bd8b014db9877b20983f462145154e7
[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" ) ) >= 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 );
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
683 // XXX: We won't know the real aspect ratio until an image is decoded
684 // but we do need it now (to satisfy filter_resize) - take a guess based
685 // on pal/ntsc
686 if ( codec_context->sample_aspect_ratio.num > 0 )
687 {
688 mlt_properties_set_double( properties, "aspect_ratio", av_q2d( codec_context->sample_aspect_ratio ) );
689 }
690 else
691 {
692 int is_pal = mlt_properties_get_double( properties, "fps" ) == 25.0;
693 mlt_properties_set_double( properties, "aspect_ratio", is_pal ? 128.0/117.0 : 72.0/79.0 );
694 }
695
696 //fprintf( stderr, "AVFORMAT: sample aspect %f %dx%d\n", av_q2d( codec_context->sample_aspect_ratio ), codec_context->width, codec_context->height );
697
698 // Determine the fps
699 source_fps = ( double )codec_context->frame_rate / ( codec_context->frame_rate_base == 0 ? 1 : codec_context->frame_rate_base );
700
701 // We'll use fps if it's available
702 if ( source_fps > 0 && source_fps < 30 )
703 mlt_properties_set_double( properties, "source_fps", source_fps );
704
705 // Set the width and height
706 mlt_properties_set_int( frame_properties, "width", codec_context->width );
707 mlt_properties_set_int( frame_properties, "height", codec_context->height );
708
709 mlt_frame_push_get_image( frame, producer_get_image );
710 mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
711 }
712 else
713 {
714 mlt_properties_set_int( frame_properties, "test_image", 1 );
715 }
716 }
717 else
718 {
719 mlt_properties_set_int( frame_properties, "test_image", 1 );
720 }
721 }
722
723 /** Get the audio from a frame.
724 */
725
726 static int producer_get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
727 {
728 // Get the properties from the frame
729 mlt_properties frame_properties = mlt_frame_properties( frame );
730
731 // Obtain the frame number of this frame
732 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
733
734 // Get the producer
735 mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
736
737 // Get the producer properties
738 mlt_properties properties = mlt_producer_properties( this );
739
740 // Fetch the audio_context
741 AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
742
743 // Get the audio_index
744 int index = mlt_properties_get_int( properties, "audio_index" );
745
746 // Get the seekable status
747 int seekable = mlt_properties_get_int( properties, "seekable" );
748
749 // Obtain the expected frame numer
750 mlt_position expected = mlt_properties_get_position( properties, "audio_expected" );
751
752 // Obtain the resample context if it exists (not always needed)
753 ReSampleContext *resample = mlt_properties_get_data( properties, "audio_resample", NULL );
754
755 // Obtain the audio buffer
756 int16_t *audio_buffer = mlt_properties_get_data( properties, "audio_buffer", NULL );
757
758 // Get amount of audio used
759 int audio_used = mlt_properties_get_int( properties, "audio_used" );
760
761 // Calculate the real time code
762 double real_timecode = producer_time_of_frame( this, position );
763
764 // Get the audio stream
765 AVStream *stream = context->streams[ index ];
766
767 // Get codec context
768 AVCodecContext *codec_context = &stream->codec;
769
770 // Packet
771 AVPacket pkt;
772
773 // Number of frames to ignore (for ffwd)
774 int ignore = 0;
775
776 // Flag for paused (silence)
777 int paused = 0;
778
779 // Check for resample and create if necessary
780 if ( resample == NULL && codec_context->channels <= 2 )
781 {
782 // Create the resampler
783 resample = audio_resample_init( *channels, codec_context->channels, *frequency, codec_context->sample_rate );
784
785 // And store it on properties
786 mlt_properties_set_data( properties, "audio_resample", resample, 0, ( mlt_destructor )audio_resample_close, NULL );
787 }
788 else if ( resample == NULL )
789 {
790 *channels = codec_context->channels;
791 *frequency = codec_context->sample_rate;
792 }
793
794 // Check for audio buffer and create if necessary
795 if ( audio_buffer == NULL )
796 {
797 // Allocate the audio buffer
798 audio_buffer = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
799
800 // And store it on properties for reuse
801 mlt_properties_set_data( properties, "audio_buffer", audio_buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
802 }
803
804 // Seek if necessary
805 if ( position != expected )
806 {
807 if ( position + 1 == expected )
808 {
809 // We're paused - silence required
810 paused = 1;
811 }
812 else if ( !seekable && position > expected && ( position - expected ) < 250 )
813 {
814 // Fast forward - seeking is inefficient for small distances - just ignore following frames
815 ignore = position - expected;
816 }
817 else if ( position < expected || position - expected >= 12 )
818 {
819 // Set to the real timecode
820 if ( av_seek_frame( context, -1, mlt_properties_get_double( properties, "start_time" ) + real_timecode * 1000000.0 ) != 0 )
821 paused = 1;
822
823 // Clear the usage in the audio buffer
824 audio_used = 0;
825 }
826 }
827
828 // Get the audio if required
829 if ( !paused )
830 {
831 int ret = 0;
832 int got_audio = 0;
833 int16_t *temp = mlt_pool_alloc( sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE );
834
835 memset( &pkt, 0, sizeof( pkt ) );
836
837 while( ret >= 0 && !got_audio )
838 {
839 // Check if the buffer already contains the samples required
840 if ( audio_used >= *samples && ignore == 0 )
841 {
842 got_audio = 1;
843 break;
844 }
845
846 // Read a packet
847 ret = av_read_frame( context, &pkt );
848
849 int len = pkt.size;
850 uint8_t *ptr = pkt.data;
851 int data_size;
852
853 // We only deal with audio from the selected audio_index
854 while ( ptr != NULL && ret >= 0 && pkt.stream_index == index && len > 0 )
855 {
856 // Decode the audio
857 ret = avcodec_decode_audio( codec_context, temp, &data_size, ptr, len );
858
859 if ( ret < 0 )
860 {
861 ret = 0;
862 break;
863 }
864
865 len -= ret;
866 ptr += ret;
867
868 if ( data_size > 0 )
869 {
870 if ( resample != NULL )
871 {
872 audio_used += audio_resample( resample, &audio_buffer[ audio_used * *channels ], temp, data_size / ( codec_context->channels * sizeof( int16_t ) ) );
873 }
874 else
875 {
876 memcpy( &audio_buffer[ audio_used * *channels ], temp, data_size );
877 audio_used += data_size / ( codec_context->channels * sizeof( int16_t ) );
878 }
879
880 // Handle ignore
881 while ( ignore && audio_used > *samples )
882 {
883 ignore --;
884 audio_used -= *samples;
885 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * sizeof( int16_t ) );
886 }
887 }
888
889 // If we're behind, ignore this packet
890 float current_pts = (float)pkt.pts / 1000000.0;
891 if ( seekable && ( !ignore && current_pts <= ( real_timecode - 0.02 ) ) )
892 ignore = 1;
893 }
894
895 // We're finished with this packet regardless
896 av_free_packet( &pkt );
897 }
898
899 *buffer = mlt_pool_alloc( *samples * *channels * sizeof( int16_t ) );
900 mlt_properties_set_data( frame_properties, "audio", *buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
901
902 // Now handle the audio if we have enough
903 if ( audio_used >= *samples )
904 {
905 memcpy( *buffer, audio_buffer, *samples * *channels * sizeof( int16_t ) );
906 audio_used -= *samples;
907 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * *channels * sizeof( int16_t ) );
908 }
909 else
910 {
911 memset( *buffer, 0, *samples * *channels * sizeof( int16_t ) );
912 }
913
914 // Store the number of audio samples still available
915 mlt_properties_set_int( properties, "audio_used", audio_used );
916
917 // Release the temporary audio
918 mlt_pool_release( temp );
919 }
920 else
921 {
922 // Get silence and don't touch the context
923 frame->get_audio = NULL;
924 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
925 }
926
927 // Regardless of speed (other than paused), we expect to get the next frame
928 if ( !paused )
929 mlt_properties_set_position( properties, "audio_expected", position + 1 );
930
931 return 0;
932 }
933
934 /** Set up audio handling.
935 */
936
937 static void producer_set_up_audio( mlt_producer this, mlt_frame frame )
938 {
939 // Get the properties
940 mlt_properties properties = mlt_producer_properties( this );
941
942 // Fetch the audio_context
943 AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
944
945 // Get the audio_index
946 int index = mlt_properties_get_int( properties, "audio_index" );
947
948 // Deal with audio context
949 if ( context != NULL && index != -1 )
950 {
951 // Get the frame properties
952 mlt_properties frame_properties = mlt_frame_properties( frame );
953
954 // Get the audio stream
955 AVStream *stream = context->streams[ index ];
956
957 // Get codec context
958 AVCodecContext *codec_context = &stream->codec;
959
960 // Get the codec
961 AVCodec *codec = mlt_properties_get_data( properties, "audio_codec", NULL );
962
963 // Initialise the codec if necessary
964 if ( codec == NULL )
965 {
966 // Find the codec
967 codec = avcodec_find_decoder( codec_context->codec_id );
968
969 // If we don't have a codec and we can't initialise it, we can't do much more...
970 if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
971 {
972 // Now store the codec with its destructor
973 mlt_properties_set_data( properties, "audio_codec", codec_context, 0, producer_codec_close, NULL );
974
975 }
976 else
977 {
978 // Remember that we can't use this later
979 mlt_properties_set_int( properties, "audio_index", -1 );
980 }
981 }
982
983 // No codec, no show...
984 if ( codec != NULL )
985 {
986 frame->get_audio = producer_get_audio;
987 mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
988 }
989 }
990 }
991
992 /** Our get frame implementation.
993 */
994
995 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index )
996 {
997 // Create an empty frame
998 *frame = mlt_frame_init( );
999
1000 // Update timecode on the frame we're creating
1001 mlt_frame_set_position( *frame, mlt_producer_position( this ) );
1002
1003 // Set the position of this producer
1004 mlt_properties_set_position( mlt_frame_properties( *frame ), "avformat_position", mlt_producer_frame( this ) );
1005
1006 // Set up the video
1007 producer_set_up_video( this, *frame );
1008
1009 // Set up the audio
1010 producer_set_up_audio( this, *frame );
1011
1012 // Set the aspect_ratio
1013 mlt_properties_set_double( mlt_frame_properties( *frame ), "aspect_ratio", mlt_properties_get_double( mlt_producer_properties( this ), "aspect_ratio" ) );
1014
1015 // Calculate the next timecode
1016 mlt_producer_prepare_next( this );
1017
1018 return 0;
1019 }