+ General improved media 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 if ( avcodec_find_decoder( codec_context->codec_id ) == NULL )
95 continue;
96
97 // Determine the type and obtain the first index of each type
98 switch( codec_context->codec_type )
99 {
100 case CODEC_TYPE_VIDEO:
101 if ( *video_index < 0 )
102 *video_index = i;
103 break;
104 case CODEC_TYPE_AUDIO:
105 if ( *audio_index < 0 )
106 *audio_index = i;
107 break;
108 default:
109 break;
110 }
111 }
112 }
113
114 /** Producer file destructor.
115 */
116
117 static void producer_file_close( void *context )
118 {
119 if ( context != NULL )
120 {
121 // Lock the mutex now
122 avformat_lock( );
123
124 // Close the file
125 av_close_input_file( context );
126
127 // Unlock the mutex now
128 avformat_unlock( );
129 }
130 }
131
132 /** Producer file destructor.
133 */
134
135 static void producer_codec_close( void *codec )
136 {
137 if ( codec != NULL )
138 {
139 // Lock the mutex now
140 avformat_lock( );
141
142 // Close the file
143 avcodec_close( codec );
144
145 // Unlock the mutex now
146 avformat_unlock( );
147 }
148 }
149
150 /** Open the file.
151 */
152
153 static int producer_open( mlt_producer this, char *file )
154 {
155 // Return an error code (0 == no error)
156 int error = 0;
157
158 // Context for avformat
159 AVFormatContext *context = NULL;
160
161 // Get the properties
162 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
163
164 // We will treat everything with the producer fps
165 double fps = mlt_properties_get_double( properties, "fps" );
166
167 // Lock the mutex now
168 avformat_lock( );
169
170 // If "MRL", then create AVInputFormat
171 AVInputFormat *format = NULL;
172 AVFormatParameters *params = NULL;
173 char *standard = NULL;
174 char *mrl = strchr( file, ':' );
175
176 // AV option (0 = both, 1 = video, 2 = audio)
177 int av = 0;
178
179 // Setting lowest log level
180 av_log_set_level( -1 );
181
182 // Only if there is not a protocol specification that avformat can handle
183 if ( mrl && !url_exist( file ) )
184 {
185 // 'file' becomes format abbreviation
186 mrl[0] = 0;
187
188 // Lookup the format
189 format = av_find_input_format( file );
190
191 // Eat the format designator
192 file = ++mrl;
193
194 if ( format )
195 {
196 // Allocate params
197 params = calloc( sizeof( AVFormatParameters ), 1 );
198
199 // These are required by video4linux (defaults)
200 params->width = 640;
201 params->height = 480;
202 params->time_base= (AVRational){1,25};
203 params->device = file;
204 params->channels = 2;
205 params->sample_rate = 48000;
206 }
207
208 // Parse out params
209 mrl = strchr( file, '?' );
210 while ( mrl )
211 {
212 mrl[0] = 0;
213 char *name = strdup( ++mrl );
214 char *value = strchr( name, ':' );
215 if ( value )
216 {
217 value[0] = 0;
218 value++;
219 char *t = strchr( value, '&' );
220 if ( t )
221 t[0] = 0;
222 if ( !strcmp( name, "frame_rate" ) )
223 params->time_base.den = atoi( value );
224 else if ( !strcmp( name, "frame_rate_base" ) )
225 params->time_base.num = atoi( value );
226 else if ( !strcmp( name, "sample_rate" ) )
227 params->sample_rate = atoi( value );
228 else if ( !strcmp( name, "channels" ) )
229 params->channels = atoi( value );
230 else if ( !strcmp( name, "width" ) )
231 params->width = atoi( value );
232 else if ( !strcmp( name, "height" ) )
233 params->height = atoi( value );
234 else if ( !strcmp( name, "standard" ) )
235 {
236 standard = strdup( value );
237 params->standard = standard;
238 }
239 else if ( !strcmp( name, "av" ) )
240 av = atoi( value );
241 }
242 free( name );
243 mrl = strchr( mrl, '&' );
244 }
245 }
246
247 // Now attempt to open the file
248 error = av_open_input_file( &context, file, format, 0, params ) < 0;
249
250 // Cleanup AVFormatParameters
251 free( standard );
252 free( params );
253
254 // If successful, then try to get additional info
255 if ( error == 0 )
256 {
257 // Get the stream info
258 error = av_find_stream_info( context ) < 0;
259
260 // Continue if no error
261 if ( error == 0 )
262 {
263 // We will default to the first audio and video streams found
264 int audio_index = -1;
265 int video_index = -1;
266 int av_bypass = 0;
267
268 // Now set properties where we can (use default unknowns if required)
269 if ( context->duration != AV_NOPTS_VALUE )
270 {
271 // This isn't going to be accurate for all formats
272 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps );
273 mlt_properties_set_position( properties, "out", frames - 2 );
274 mlt_properties_set_position( properties, "length", frames - 1 );
275 }
276
277 // Find default audio and video streams
278 find_default_streams( context, &audio_index, &video_index );
279
280 if ( context->start_time != AV_NOPTS_VALUE )
281 mlt_properties_set_double( properties, "_start_time", context->start_time );
282
283 // Check if we're seekable (something funny about mpeg here :-/)
284 if ( strcmp( file, "pipe:" ) && strncmp( file, "http://", 6 ) )
285 mlt_properties_set_int( properties, "seekable", av_seek_frame( context, -1, mlt_properties_get_double( properties, "_start_time" ), AVSEEK_FLAG_BACKWARD ) >= 0 );
286 else
287 av_bypass = 1;
288
289 // Store selected audio and video indexes on properties
290 mlt_properties_set_int( properties, "audio_index", audio_index );
291 mlt_properties_set_int( properties, "video_index", video_index );
292 mlt_properties_set_int( properties, "_last_position", -1 );
293
294 // Fetch the width, height and aspect ratio
295 if ( video_index != -1 )
296 {
297 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
298 mlt_properties_set_int( properties, "width", codec_context->width );
299 mlt_properties_set_int( properties, "height", codec_context->height );
300 mlt_properties_set_double( properties, "aspect_ratio", av_q2d( codec_context->sample_aspect_ratio ) );
301 }
302
303 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
304 if ( av == 0 && !av_bypass && audio_index != -1 && video_index != -1 )
305 {
306 // We'll use the open one as our video_context
307 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
308 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
309
310 // And open again for our audio context
311 av_open_input_file( &context, file, NULL, 0, NULL );
312 av_find_stream_info( context );
313
314 // Audio context
315 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
316 }
317 else if ( av != 2 && video_index != -1 )
318 {
319 // We only have a video context
320 mlt_properties_set_data( properties, "video_context", context, 0, producer_file_close, NULL );
321 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
322 }
323 else if ( audio_index != -1 )
324 {
325 // We only have an audio context
326 mlt_properties_set_data( properties, "audio_context", context, 0, producer_file_close, NULL );
327 }
328 else
329 {
330 // Something has gone wrong
331 error = -1;
332 }
333
334 mlt_properties_set_int( properties, "av_bypass", av_bypass );
335 }
336 }
337
338 // Unlock the mutex now
339 avformat_unlock( );
340
341 return error;
342 }
343
344 /** Convert a frame position to a time code.
345 */
346
347 static double producer_time_of_frame( mlt_producer this, mlt_position position )
348 {
349 // Get the properties
350 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
351
352 // Obtain the fps
353 double fps = mlt_properties_get_double( properties, "fps" );
354
355 // Do the calc
356 return ( double )position / fps;
357 }
358
359 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt, mlt_image_format format, int width, int height )
360 {
361 if ( format == mlt_image_yuv420p )
362 {
363 AVPicture pict;
364 pict.data[0] = buffer;
365 pict.data[1] = buffer + width * height;
366 pict.data[2] = buffer + ( 3 * width * height ) / 2;
367 pict.linesize[0] = width;
368 pict.linesize[1] = width >> 1;
369 pict.linesize[2] = width >> 1;
370 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
371 }
372 else if ( format == mlt_image_rgb24 )
373 {
374 AVPicture output;
375 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
376 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
377 }
378 else
379 {
380 AVPicture output;
381 avpicture_fill( &output, buffer, PIX_FMT_YUV422, width, height );
382 img_convert( &output, PIX_FMT_YUV422, (AVPicture *)frame, pix_fmt, width, height );
383 }
384 }
385
386 /** Get an image from a frame.
387 */
388
389 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
390 {
391 // Get the properties from the frame
392 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
393
394 // Obtain the frame number of this frame
395 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
396
397 // Get the producer
398 mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
399
400 // Get the producer properties
401 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
402
403 // Fetch the video_context
404 AVFormatContext *context = mlt_properties_get_data( properties, "video_context", NULL );
405
406 // Get the video_index
407 int index = mlt_properties_get_int( properties, "video_index" );
408
409 // Obtain the expected frame numer
410 mlt_position expected = mlt_properties_get_position( properties, "_video_expected" );
411
412 // Calculate the real time code
413 double real_timecode = producer_time_of_frame( this, position );
414
415 // Get the video stream
416 AVStream *stream = context->streams[ index ];
417
418 // Get codec context
419 AVCodecContext *codec_context = stream->codec;
420
421 // Packet
422 AVPacket pkt;
423
424 // Get the conversion frame
425 AVFrame *av_frame = mlt_properties_get_data( properties, "av_frame", NULL );
426
427 // Special case pause handling flag
428 int paused = 0;
429
430 // Special case ffwd handling
431 int ignore = 0;
432
433 // Current time calcs
434 int current_position = mlt_properties_get_double( properties, "_current_position" );
435
436 // We may want to use the source fps if available
437 double source_fps = mlt_properties_get_double( properties, "source_fps" );
438 double fps = mlt_properties_get_double( properties, "fps" );
439
440 // This is the physical frame position in the source
441 int req_position = ( int )( position / fps * source_fps );
442
443 // Get the seekable status
444 int seekable = mlt_properties_get_int( properties, "seekable" );
445
446 // Generate the size in bytes
447 int size = 0;
448
449 // Hopefully provide better support for streams...
450 int av_bypass = mlt_properties_get_int( properties, "av_bypass" );
451
452 // Determines if we have to decode all frames in a sequence
453 int must_decode = 1;
454
455 // Set the result arguments that we know here (only *buffer is now required)
456 *width = codec_context->width;
457 *height = codec_context->height;
458
459 switch ( *format )
460 {
461 case mlt_image_yuv420p:
462 size = *width * 3 * ( *height + 1 ) / 2;
463 break;
464 case mlt_image_rgb24:
465 size = *width * ( *height + 1 ) * 3;
466 break;
467 default:
468 *format = mlt_image_yuv422;
469 size = *width * ( *height + 1 ) * 2;
470 break;
471 }
472
473 // Set this on the frame properties
474 mlt_properties_set_int( frame_properties, "width", *width );
475 mlt_properties_set_int( frame_properties, "height", *height );
476
477 // Construct the output image
478 *buffer = mlt_pool_alloc( size );
479
480 // Temporary hack to improve intra frame only
481 must_decode = strcmp( codec_context->codec->name, "mjpeg" ) &&
482 strcmp( codec_context->codec->name, "rawvideo" ) &&
483 strcmp( codec_context->codec->name, "dvvideo" );
484
485 // Seek if necessary
486 if ( position != expected )
487 {
488 if ( av_frame != NULL && position + 1 == expected )
489 {
490 // We're paused - use last image
491 paused = 1;
492 }
493 else if ( !seekable && position > expected && ( position - expected ) < 250 )
494 {
495 // Fast forward - seeking is inefficient for small distances - just ignore following frames
496 ignore = ( int )( ( position - expected ) / fps * source_fps );
497 }
498 else if ( seekable && ( position < expected || position - expected >= 12 ) )
499 {
500 // Calculate the timestamp for the requested frame
501 int64_t timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE );
502 if ( ( uint64_t )context->start_time != AV_NOPTS_VALUE )
503 timestamp += context->start_time;
504 if ( must_decode )
505 timestamp -= AV_TIME_BASE;
506 if ( timestamp < 0 )
507 timestamp = 0;
508
509 // Set to the timestamp
510 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
511
512 // Remove the cached info relating to the previous position
513 mlt_properties_set_int( properties, "_current_position", -1 );
514 mlt_properties_set_int( properties, "_last_position", -1 );
515 mlt_properties_set_data( properties, "av_frame", NULL, 0, NULL, NULL );
516 av_frame = NULL;
517 }
518 }
519
520 // Duplicate the last image if necessary (see comment on rawvideo below)
521 if ( av_frame != NULL && ( paused || mlt_properties_get_int( properties, "_current_position" ) >= req_position ) && av_bypass == 0 )
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 int int_position = 0;
534
535 av_init_packet( &pkt );
536
537 // Construct an AVFrame for YUV422 conversion
538 if ( av_frame == NULL )
539 {
540 av_frame = avcodec_alloc_frame( );
541 mlt_properties_set_data( properties, "av_frame", av_frame, 0, av_free, NULL );
542 }
543
544 while( ret >= 0 && !got_picture )
545 {
546 // Read a packet
547 ret = av_read_frame( context, &pkt );
548
549 // We only deal with video from the selected video_index
550 if ( ret >= 0 && pkt.stream_index == index && pkt.size > 0 )
551 {
552 // Determine time code of the packet
553 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps );
554 if ( context->start_time != AV_NOPTS_VALUE )
555 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE );
556
557 int last_position = mlt_properties_get_int( properties, "_last_position" );
558 if ( int_position == last_position )
559 int_position = last_position + 1;
560 mlt_properties_set_int( properties, "_last_position", int_position );
561
562 // Decode the image
563 if ( must_decode || int_position >= req_position )
564 ret = avcodec_decode_video( codec_context, av_frame, &got_picture, pkt.data, pkt.size );
565
566 if ( got_picture )
567 {
568 // Handle ignore
569 if ( int_position < req_position )
570 {
571 ignore = 0;
572 got_picture = 0;
573 }
574 else if ( int_position >= req_position )
575 {
576 ignore = 0;
577 }
578 else if ( ignore -- )
579 {
580 got_picture = 0;
581 }
582 }
583 }
584
585 // Now handle the picture if we have one
586 if ( got_picture )
587 {
588 mlt_properties_set_int( frame_properties, "progressive", !av_frame->interlaced_frame );
589 mlt_properties_set_int( frame_properties, "top_field_first", av_frame->top_field_first );
590 convert_image( av_frame, *buffer, codec_context->pix_fmt, *format, *width, *height );
591 mlt_properties_set_data( frame_properties, "image", *buffer, size, (mlt_destructor)mlt_pool_release, NULL );
592 mlt_properties_set_double( properties, "_current_position", int_position );
593 }
594
595 // We're finished with this packet regardless
596 av_free_packet( &pkt );
597 }
598 }
599
600 // Very untidy - for rawvideo, the packet contains the frame, hence the free packet
601 // above will break the pause behaviour - so we wipe the frame now
602 if ( !strcmp( codec_context->codec->name, "rawvideo" ) )
603 mlt_properties_set_data( properties, "av_frame", NULL, 0, NULL, NULL );
604
605 // Set the field order property for this frame
606 mlt_properties_set_int( frame_properties, "top_field_first", 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 int norm_aspect_ratio = mlt_properties_get_int( properties, "norm_aspect_ratio" );
666 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
667 double aspect_ratio;
668
669 // XXX: We won't know the real aspect ratio until an image is decoded
670 // but we do need it now (to satisfy filter_resize) - take a guess based
671 // on pal/ntsc
672 if ( force_aspect_ratio > 0.0 )
673 {
674 aspect_ratio = force_aspect_ratio;
675 }
676 else if ( !norm_aspect_ratio && codec_context->sample_aspect_ratio.num > 0 )
677 {
678 aspect_ratio = av_q2d( codec_context->sample_aspect_ratio );
679 }
680 else
681 {
682 int is_pal = mlt_properties_get_double( properties, "fps" ) == 25.0;
683 aspect_ratio = is_pal ? 59.0/54.0 : 10.0/11.0;
684 }
685
686 // Determine the fps
687 source_fps = ( double )codec_context->time_base.den / ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num );
688
689 // We'll use fps if it's available
690 if ( source_fps > 0 && source_fps < 30 )
691 mlt_properties_set_double( properties, "source_fps", source_fps );
692 else
693 mlt_properties_set_double( properties, "source_fps", mlt_properties_get_double( properties, "fps" ) );
694 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
695
696 // Set the width and height
697 mlt_properties_set_int( frame_properties, "width", codec_context->width );
698 mlt_properties_set_int( frame_properties, "height", codec_context->height );
699 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
700
701 mlt_frame_push_get_image( frame, producer_get_image );
702 mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
703 }
704 else
705 {
706 mlt_properties_set_int( frame_properties, "test_image", 1 );
707 }
708 }
709 else
710 {
711 mlt_properties_set_int( frame_properties, "test_image", 1 );
712 }
713 }
714
715 /** Get the audio from a frame.
716 */
717
718 static int producer_get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
719 {
720 // Get the properties from the frame
721 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
722
723 // Obtain the frame number of this frame
724 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
725
726 // Get the producer
727 mlt_producer this = mlt_properties_get_data( frame_properties, "avformat_producer", NULL );
728
729 // Get the producer properties
730 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
731
732 // Fetch the audio_context
733 AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
734
735 // Get the audio_index
736 int index = mlt_properties_get_int( properties, "audio_index" );
737
738 // Get the seekable status
739 int seekable = mlt_properties_get_int( properties, "seekable" );
740
741 // Obtain the expected frame numer
742 mlt_position expected = mlt_properties_get_position( properties, "_audio_expected" );
743
744 // Obtain the resample context if it exists (not always needed)
745 ReSampleContext *resample = mlt_properties_get_data( properties, "audio_resample", NULL );
746
747 // Obtain the audio buffer
748 int16_t *audio_buffer = mlt_properties_get_data( properties, "audio_buffer", NULL );
749
750 // Get amount of audio used
751 int audio_used = mlt_properties_get_int( properties, "_audio_used" );
752
753 // Calculate the real time code
754 double real_timecode = producer_time_of_frame( this, position );
755
756 // Get the audio stream
757 AVStream *stream = context->streams[ index ];
758
759 // Get codec context
760 AVCodecContext *codec_context = stream->codec;
761
762 // Packet
763 AVPacket pkt;
764
765 // Number of frames to ignore (for ffwd)
766 int ignore = 0;
767
768 // Flag for paused (silence)
769 int paused = 0;
770
771 // Check for resample and create if necessary
772 if ( resample == NULL && codec_context->channels <= 2 )
773 {
774 // Create the resampler
775 resample = audio_resample_init( *channels, codec_context->channels, *frequency, codec_context->sample_rate );
776
777 // And store it on properties
778 mlt_properties_set_data( properties, "audio_resample", resample, 0, ( mlt_destructor )audio_resample_close, NULL );
779 }
780 else if ( resample == NULL )
781 {
782 *channels = codec_context->channels;
783 *frequency = codec_context->sample_rate;
784 }
785
786 // Check for audio buffer and create if necessary
787 if ( audio_buffer == NULL )
788 {
789 // Allocate the audio buffer
790 audio_buffer = mlt_pool_alloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
791
792 // And store it on properties for reuse
793 mlt_properties_set_data( properties, "audio_buffer", audio_buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
794 }
795
796 // Seek if necessary
797 if ( position != expected )
798 {
799 if ( position + 1 == expected )
800 {
801 // We're paused - silence required
802 paused = 1;
803 }
804 else if ( !seekable && position > expected && ( position - expected ) < 250 )
805 {
806 // Fast forward - seeking is inefficient for small distances - just ignore following frames
807 ignore = position - expected;
808 }
809 else if ( position < expected || position - expected >= 12 )
810 {
811 // Set to the real timecode
812 if ( av_seek_frame( context, -1, mlt_properties_get_double( properties, "_start_time" ) + real_timecode * 1000000.0, AVSEEK_FLAG_BACKWARD ) != 0 )
813 paused = 1;
814
815 // Clear the usage in the audio buffer
816 audio_used = 0;
817 }
818 }
819
820 // Get the audio if required
821 if ( !paused )
822 {
823 int ret = 0;
824 int got_audio = 0;
825 int16_t *temp = mlt_pool_alloc( sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE );
826
827 av_init_packet( &pkt );
828
829 while( ret >= 0 && !got_audio )
830 {
831 // Check if the buffer already contains the samples required
832 if ( audio_used >= *samples && ignore == 0 )
833 {
834 got_audio = 1;
835 break;
836 }
837
838 // Read a packet
839 ret = av_read_frame( context, &pkt );
840
841 int len = pkt.size;
842 uint8_t *ptr = pkt.data;
843 int data_size;
844
845 // We only deal with audio from the selected audio_index
846 while ( ptr != NULL && ret >= 0 && pkt.stream_index == index && len > 0 )
847 {
848 // Decode the audio
849 ret = avcodec_decode_audio( codec_context, temp, &data_size, ptr, len );
850
851 if ( ret < 0 )
852 {
853 ret = 0;
854 break;
855 }
856
857 len -= ret;
858 ptr += ret;
859
860 if ( data_size > 0 )
861 {
862 if ( resample != NULL )
863 {
864 audio_used += audio_resample( resample, &audio_buffer[ audio_used * *channels ], temp, data_size / ( codec_context->channels * sizeof( int16_t ) ) );
865 }
866 else
867 {
868 memcpy( &audio_buffer[ audio_used * *channels ], temp, data_size );
869 audio_used += data_size / ( codec_context->channels * sizeof( int16_t ) );
870 }
871
872 // Handle ignore
873 while ( ignore && audio_used > *samples )
874 {
875 ignore --;
876 audio_used -= *samples;
877 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * sizeof( int16_t ) );
878 }
879 }
880
881 // If we're behind, ignore this packet
882 float current_pts = av_q2d( stream->time_base ) * pkt.pts;
883 if ( seekable && ( !ignore && current_pts <= ( real_timecode - 0.02 ) ) )
884 ignore = 1;
885 }
886
887 // We're finished with this packet regardless
888 av_free_packet( &pkt );
889 }
890
891 *buffer = mlt_pool_alloc( *samples * *channels * sizeof( int16_t ) );
892 mlt_properties_set_data( frame_properties, "audio", *buffer, 0, ( mlt_destructor )mlt_pool_release, NULL );
893
894 // Now handle the audio if we have enough
895 if ( audio_used >= *samples )
896 {
897 memcpy( *buffer, audio_buffer, *samples * *channels * sizeof( int16_t ) );
898 audio_used -= *samples;
899 memmove( audio_buffer, &audio_buffer[ *samples * *channels ], audio_used * *channels * sizeof( int16_t ) );
900 }
901 else
902 {
903 memset( *buffer, 0, *samples * *channels * sizeof( int16_t ) );
904 }
905
906 // Store the number of audio samples still available
907 mlt_properties_set_int( properties, "_audio_used", audio_used );
908
909 // Release the temporary audio
910 mlt_pool_release( temp );
911 }
912 else
913 {
914 // Get silence and don't touch the context
915 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
916 }
917
918 // Regardless of speed (other than paused), we expect to get the next frame
919 if ( !paused )
920 mlt_properties_set_position( properties, "_audio_expected", position + 1 );
921
922 return 0;
923 }
924
925 /** Set up audio handling.
926 */
927
928 static void producer_set_up_audio( mlt_producer this, mlt_frame frame )
929 {
930 // Get the properties
931 mlt_properties properties = MLT_PRODUCER_PROPERTIES( this );
932
933 // Fetch the audio_context
934 AVFormatContext *context = mlt_properties_get_data( properties, "audio_context", NULL );
935
936 // Get the audio_index
937 int index = mlt_properties_get_int( properties, "audio_index" );
938
939 // Deal with audio context
940 if ( context != NULL && index != -1 )
941 {
942 // Get the frame properties
943 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
944
945 // Get the audio stream
946 AVStream *stream = context->streams[ index ];
947
948 // Get codec context
949 AVCodecContext *codec_context = stream->codec;
950
951 // Get the codec
952 AVCodec *codec = mlt_properties_get_data( properties, "audio_codec", NULL );
953
954 // Initialise the codec if necessary
955 if ( codec == NULL )
956 {
957 // Find the codec
958 codec = avcodec_find_decoder( codec_context->codec_id );
959
960 // If we don't have a codec and we can't initialise it, we can't do much more...
961 if ( codec != NULL && avcodec_open( codec_context, codec ) >= 0 )
962 {
963 // Now store the codec with its destructor
964 mlt_properties_set_data( properties, "audio_codec", codec_context, 0, producer_codec_close, NULL );
965
966 }
967 else
968 {
969 // Remember that we can't use this later
970 mlt_properties_set_int( properties, "audio_index", -1 );
971 }
972 }
973
974 // No codec, no show...
975 if ( codec != NULL )
976 {
977 mlt_frame_push_audio( frame, producer_get_audio );
978 mlt_properties_set_data( frame_properties, "avformat_producer", this, 0, NULL, NULL );
979 mlt_properties_set_int( frame_properties, "frequency", codec_context->sample_rate );
980 mlt_properties_set_int( frame_properties, "channels", codec_context->channels );
981 }
982 }
983 }
984
985 /** Our get frame implementation.
986 */
987
988 static int producer_get_frame( mlt_producer this, mlt_frame_ptr frame, int index )
989 {
990 // Create an empty frame
991 *frame = mlt_frame_init( );
992
993 // Update timecode on the frame we're creating
994 mlt_frame_set_position( *frame, mlt_producer_position( this ) );
995
996 // Set the position of this producer
997 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( this ) );
998
999 // Set up the video
1000 producer_set_up_video( this, *frame );
1001
1002 // Set up the audio
1003 producer_set_up_audio( this, *frame );
1004
1005 // Set the aspect_ratio
1006 mlt_properties_set_double( MLT_FRAME_PROPERTIES( *frame ), "aspect_ratio", mlt_properties_get_double( MLT_PRODUCER_PROPERTIES( this ), "aspect_ratio" ) );
1007
1008 // Calculate the next timecode
1009 mlt_producer_prepare_next( this );
1010
1011 return 0;
1012 }