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