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