2 * producer_avformat.c -- avformat producer
3 * Copyright (C) 2003-2009 Ushodaya Enterprises Limited
4 * Author: Charles Yates <charles.yates@pandora.be>
5 * Author: Dan Dennedy <dan@dennedy.org>
6 * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include <framework/mlt_producer.h>
25 #include <framework/mlt_frame.h>
26 #include <framework/mlt_profile.h>
27 #include <framework/mlt_log.h>
28 #include <framework/mlt_deque.h>
29 #include <framework/mlt_factory.h>
30 #include <framework/mlt_cache.h>
32 // ffmpeg Header files
33 #include <libavformat/avformat.h>
35 # include <libswscale/swscale.h>
37 #if LIBAVCODEC_VERSION_MAJOR > 52
38 #include <libavutil/samplefmt.h>
39 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
40 const char *avcodec_get_sample_fmt_name(int sample_fmt);
43 # include <libavcodec/vdpau.h>
45 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
46 # include <libavutil/pixdesc.h>
49 // System header files
55 #if LIBAVUTIL_VERSION_INT < (50<<16)
56 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
57 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
60 #if LIBAVCODEC_VERSION_MAJOR > 52
61 #include <libavutil/opt.h>
62 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
63 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
64 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
66 #include <libavcodec/opt.h>
69 #define POSITION_INITIAL (-2)
70 #define POSITION_INVALID (-1)
72 #define MAX_AUDIO_STREAMS (10)
73 #define MAX_VDPAU_SURFACES (10)
75 void avformat_lock( );
76 void avformat_unlock( );
78 struct producer_avformat_s
81 AVFormatContext *dummy_context;
82 AVFormatContext *audio_format;
83 AVFormatContext *video_format;
84 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
85 AVCodecContext *video_codec;
87 ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
88 mlt_position audio_expected;
89 mlt_position video_expected;
99 uint8_t *audio_buffer[ MAX_AUDIO_STREAMS ];
100 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
101 uint8_t *decode_buffer[ MAX_AUDIO_STREAMS ];
102 int audio_used[ MAX_AUDIO_STREAMS ];
104 int audio_max_stream;
108 unsigned int invalid_pts_counter;
109 double resample_factor;
110 mlt_cache image_cache;
112 pthread_mutex_t video_mutex;
113 pthread_mutex_t audio_mutex;
118 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
129 typedef struct producer_avformat_s *producer_avformat;
131 // Forward references.
132 static int list_components( char* file );
133 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL );
134 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
135 static void producer_avformat_close( producer_avformat );
136 static void producer_close( mlt_producer parent );
137 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
138 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
139 static void apply_properties( void *obj, mlt_properties properties, int flags );
140 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
146 /** Constructor for libavformat.
149 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
151 if ( list_components( file ) )
154 mlt_producer producer = NULL;
156 // Check that we have a non-NULL argument
159 // Construct the producer
160 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
161 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
164 if ( mlt_producer_init( producer, self ) == 0 )
166 self->parent = producer;
168 // Get the properties
169 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
171 // Set the resource property (required for all producers)
172 mlt_properties_set( properties, "resource", file );
174 // Register transport implementation with the producer
175 producer->close = (mlt_destructor) producer_close;
177 // Register our get_frame implementation
178 producer->get_frame = producer_get_frame;
180 if ( strcmp( service, "avformat-novalidate" ) )
183 if ( producer_open( self, profile, file ) != 0 )
186 mlt_producer_close( producer );
191 // Close the file to release resources for large playlists - reopen later as needed
193 if ( self->dummy_context )
194 av_close_input_file( self->dummy_context );
195 self->dummy_context = NULL;
196 if ( self->audio_format )
197 av_close_input_file( self->audio_format );
198 self->audio_format = NULL;
199 if ( self->video_format )
200 av_close_input_file( self->video_format );
201 self->video_format = NULL;
204 // Default the user-selectable indices from the auto-detected indices
205 mlt_properties_set_int( properties, "audio_index", self->audio_index );
206 mlt_properties_set_int( properties, "video_index", self->video_index );
212 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
214 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
221 int list_components( char* file )
225 // Report information about available demuxers and codecs as YAML Tiny
226 if ( file && strstr( file, "f-list" ) )
228 fprintf( stderr, "---\nformats:\n" );
229 AVInputFormat *format = NULL;
230 while ( ( format = av_iformat_next( format ) ) )
231 fprintf( stderr, " - %s\n", format->name );
232 fprintf( stderr, "...\n" );
235 if ( file && strstr( file, "acodec-list" ) )
237 fprintf( stderr, "---\naudio_codecs:\n" );
238 AVCodec *codec = NULL;
239 while ( ( codec = av_codec_next( codec ) ) )
240 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
241 fprintf( stderr, " - %s\n", codec->name );
242 fprintf( stderr, "...\n" );
245 if ( file && strstr( file, "vcodec-list" ) )
247 fprintf( stderr, "---\nvideo_codecs:\n" );
248 AVCodec *codec = NULL;
249 while ( ( codec = av_codec_next( codec ) ) )
250 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
251 fprintf( stderr, " - %s\n", codec->name );
252 fprintf( stderr, "...\n" );
259 /** Find the default streams.
262 static mlt_properties find_default_streams( producer_avformat self )
266 AVMetadataTag *tag = NULL;
267 AVFormatContext *context = self->video_format;
268 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
270 // Default to the first audio and video streams found
271 self->audio_index = -1;
272 self->video_index = -1;
274 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
276 // Allow for multiple audio and video streams in the file and select first of each (if available)
277 for( i = 0; i < context->nb_streams; i++ )
279 // Get the codec context
280 AVStream *stream = context->streams[ i ];
281 if ( ! stream ) continue;
282 AVCodecContext *codec_context = stream->codec;
283 if ( ! codec_context ) continue;
284 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
285 if ( ! codec ) continue;
287 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
289 // Determine the type and obtain the first index of each type
290 switch( codec_context->codec_type )
292 case CODEC_TYPE_VIDEO:
293 // Use first video stream
294 if ( self->video_index < 0 )
295 self->video_index = i;
296 mlt_properties_set( meta_media, key, "video" );
297 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
298 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
299 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
300 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
301 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
302 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
304 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
307 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
308 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
309 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
311 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
312 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
313 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
314 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
315 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
316 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
317 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
318 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
319 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
320 switch ( codec_context->colorspace )
322 case AVCOL_SPC_SMPTE240M:
323 mlt_properties_set_int( meta_media, key, 240 );
325 case AVCOL_SPC_BT470BG:
326 case AVCOL_SPC_SMPTE170M:
327 mlt_properties_set_int( meta_media, key, 601 );
329 case AVCOL_SPC_BT709:
330 mlt_properties_set_int( meta_media, key, 709 );
333 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
334 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
339 case CODEC_TYPE_AUDIO:
340 // Use first audio stream
341 if ( self->audio_index < 0 )
342 self->audio_index = i;
343 mlt_properties_set( meta_media, key, "audio" );
344 #if LIBAVCODEC_VERSION_MAJOR > 52
345 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
346 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
347 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
348 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
349 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
351 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
352 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
353 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
354 mlt_properties_set_int( meta_media, key, codec_context->channels );
359 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
360 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
361 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
362 mlt_properties_set( meta_media, key, codec->name );
363 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
364 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
365 mlt_properties_set( meta_media, key, codec->long_name );
367 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
368 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
369 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
370 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
371 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
372 // mlt_properties_set_int( meta_media, key, codec_context->profile );
373 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
374 // mlt_properties_set_int( meta_media, key, codec_context->level );
377 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
378 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
380 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
382 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
383 mlt_properties_set( meta_media, key, tag->value );
388 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
389 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
391 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
393 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
394 mlt_properties_set( meta_media, key, tag->value );
398 if ( context->title && strcmp( context->title, "" ) )
399 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
400 if ( context->author && strcmp( context->author, "" ) )
401 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
402 if ( context->copyright && strcmp( context->copyright, "" ) )
403 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
404 if ( context->comment )
405 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
406 if ( context->album )
407 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
409 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
410 if ( context->track )
411 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
417 static inline int dv_is_pal( AVPacket *pkt )
419 return pkt->data[3] & 0x80;
422 static int dv_is_wide( AVPacket *pkt )
424 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
426 for ( ; i < pkt->size; i += 5 /* packet size */ )
428 if ( pkt->data[ i ] == 0x61 )
430 uint8_t x = pkt->data[ i + 2 ] & 0x7;
431 return ( x == 2 ) || ( x == 7 );
437 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
439 double aspect_ratio = 1.0;
441 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
445 if ( dv_is_pal( pkt ) )
447 if ( dv_is_wide( pkt ) )
449 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
450 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
454 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
455 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
460 if ( dv_is_wide( pkt ) )
462 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
463 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
467 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
468 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
475 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
476 stream->sample_aspect_ratio;
478 codec_context->sample_aspect_ratio;
480 // Override FFmpeg's notion of DV aspect ratios, which are
481 // based upon a width of 704. Since we do not have a normaliser
482 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
483 // we just coerce the values to facilitate a passive behaviour through
484 // the rescale normaliser when using equivalent producers and consumers.
485 // = display_aspect / (width * height)
486 if ( ar.num == 10 && ar.den == 11 )
489 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
490 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
492 else if ( ar.num == 59 && ar.den == 54 )
495 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
496 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
498 else if ( ar.num == 40 && ar.den == 33 )
501 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
502 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
504 else if ( ar.num == 118 && ar.den == 81 )
507 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
508 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
514 AVRational codec_sar = codec_context->sample_aspect_ratio;
515 AVRational stream_sar =
516 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
517 stream->sample_aspect_ratio;
521 if ( codec_sar.num > 0 )
523 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
524 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
526 else if ( stream_sar.num > 0 )
528 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
529 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
533 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
534 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
537 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
538 aspect_ratio = av_q2d( ar );
539 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
544 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters **parameters )
546 if ( !URL ) return NULL;
549 char *protocol = strdup( URL );
550 char *url = strchr( protocol, ':' );
552 // Only if there is not a protocol specification that avformat can handle
553 #if LIBAVFORMAT_VERSION_MAJOR > 52
554 if ( url && avio_check( URL, 0 ) < 0 )
556 if ( url && !url_exist( URL ) )
559 // Truncate protocol string
563 *format = av_find_input_format( protocol );
565 // Eat the format designator
571 AVFormatParameters *params = *parameters = calloc( 1, sizeof( AVFormatParameters ) );
573 // These are required by video4linux2 (defaults)
574 params->width = profile->width;
575 params->height = profile->height;
576 params->time_base= (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
577 params->channels = 2;
578 params->sample_rate = 48000;
581 url = strchr( url, '?' );
585 char *name = strdup( ++url );
586 char *value = strchr( name, ':' );
591 char *t = strchr( value, '&' );
594 if ( !strcmp( name, "frame_rate" ) )
595 params->time_base.den = atoi( value );
596 else if ( !strcmp( name, "frame_rate_base" ) )
597 params->time_base.num = atoi( value );
598 else if ( !strcmp( name, "sample_rate" ) )
599 params->sample_rate = atoi( value );
600 else if ( !strcmp( name, "channel" ) )
601 params->channel = atoi( value );
602 else if ( !strcmp( name, "channels" ) )
603 params->channels = atoi( value );
604 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
605 else if ( !strcmp( name, "pix_fmt" ) )
606 params->pix_fmt = av_get_pix_fmt( value );
608 else if ( !strcmp( name, "width" ) )
609 params->width = atoi( value );
610 else if ( !strcmp( name, "height" ) )
611 params->height = atoi( value );
612 else if ( !strcmp( name, "standard" ) )
613 params->standard = strdup( value );
616 url = strchr( url, '&' );
621 return result ? strdup( result ) : strdup( URL );
624 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
628 // Get the properties
629 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
631 AVFormatContext *format = self->video_format;
633 // We will treat everything with the producer fps.
634 // TODO: make this more flexible.
635 double fps = mlt_profile_fps( profile );
638 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
640 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
641 // when producer_open is called after initial call when restoring or reseting the producer.
642 if ( format->duration != AV_NOPTS_VALUE )
644 // This isn't going to be accurate for all formats
645 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
646 mlt_properties_set_position( properties, "out", frames - 1 );
647 mlt_properties_set_position( properties, "length", frames );
648 mlt_properties_set_int( properties, "_length_computed", 1 );
652 // Set live sources to run forever
653 mlt_properties_set_position( properties, "length", INT_MAX );
654 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
655 mlt_properties_set( properties, "eof", "loop" );
656 mlt_properties_set_int( properties, "_length_computed", 1 );
660 if ( format->start_time != AV_NOPTS_VALUE )
661 self->start_time = format->start_time;
663 // Check if we're seekable
664 // avdevices are typically AVFMT_NOFILE and not seekable
665 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
668 // protocols can indicate if they support seeking
669 #if LIBAVFORMAT_VERSION_MAJOR > 52
670 self->seekable = context->pb->seekable;
672 URLContext *uc = url_fileno( format->pb );
674 self->seekable = !uc->is_streamed;
677 if ( self->seekable )
679 // Do a more rigourous test of seekable on a disposable context
680 self->seekable = av_seek_frame( format, -1, self->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
681 mlt_properties_set_int( properties, "seekable", self->seekable );
682 self->dummy_context = format;
683 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
684 format = self->video_format;
685 av_find_stream_info( format );
688 // Fetch the width, height and aspect ratio
689 if ( self->video_index != -1 )
691 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
692 mlt_properties_set_int( properties, "width", codec_context->width );
693 mlt_properties_set_int( properties, "height", codec_context->height );
695 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
697 // Fetch the first frame of DV so we can read it directly
702 ret = av_read_frame( format, &pkt );
703 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
705 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
712 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
716 // Verify that we can convert this to YUV 4:2:2
717 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
718 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
719 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
721 sws_freeContext( context );
732 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL )
734 // Return an error code (0 == no error)
738 pthread_mutex_init( &self->audio_mutex, NULL );
739 pthread_mutex_init( &self->video_mutex, NULL );
740 pthread_mutex_lock( &self->audio_mutex );
741 pthread_mutex_lock( &self->video_mutex );
744 AVInputFormat *format = NULL;
745 AVFormatParameters *params = NULL;
746 char *filename = parse_url( profile, URL, &format, ¶ms );
748 // Now attempt to open the file
749 error = av_open_input_file( &self->video_format, filename, format, 0, params ) < 0;
751 // Cleanup AVFormatParameters
754 if ( params->standard )
755 free( (void*) params->standard );
759 // If successful, then try to get additional info
762 // Get the stream info
763 error = av_find_stream_info( self->video_format ) < 0;
765 // Continue if no error
768 // Find default audio and video streams
769 find_default_streams( self );
770 error = get_basic_info( self, profile, filename );
772 // Initialize position info
773 self->first_pts = -1;
774 self->last_position = POSITION_INITIAL;
776 // We're going to cheat here - for seekable A/V files, we will have separate contexts
777 // to support independent seeking of audio from video.
778 // TODO: Is this really necessary?
779 if ( self->audio_index != -1 && self->video_index != -1 )
781 // And open again for our audio context
782 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
783 av_find_stream_info( self->audio_format );
785 else if ( self->audio_index != -1 )
787 // We only have an audio context
788 self->audio_format = self->video_format;
789 self->video_format = NULL;
791 else if ( self->video_index == -1 )
793 // Something has gone wrong
801 // Unlock the service
802 pthread_mutex_unlock( &self->audio_mutex );
803 pthread_mutex_unlock( &self->video_mutex );
808 static void reopen_video( producer_avformat self, mlt_producer producer )
810 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
811 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
812 pthread_mutex_lock( &self->audio_mutex );
814 if ( self->video_codec )
817 avcodec_close( self->video_codec );
820 self->video_codec = NULL;
821 if ( self->dummy_context )
822 av_close_input_file( self->dummy_context );
823 self->dummy_context = NULL;
824 if ( self->video_format )
825 av_close_input_file( self->video_format );
826 self->video_format = NULL;
828 int audio_index = self->audio_index;
829 int video_index = self->video_index;
831 mlt_events_block( properties, producer );
832 pthread_mutex_unlock( &self->audio_mutex );
833 pthread_mutex_unlock( &self->video_mutex );
834 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
835 mlt_properties_get( properties, "resource" ) );
836 pthread_mutex_lock( &self->video_mutex );
837 pthread_mutex_lock( &self->audio_mutex );
838 if ( self->dummy_context )
840 av_close_input_file( self->dummy_context );
841 self->dummy_context = NULL;
843 mlt_events_unblock( properties, producer );
844 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
845 #if LIBAVFORMAT_VERSION_MAJOR > 52
846 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
847 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
850 self->audio_index = audio_index;
851 if ( self->video_format && video_index > -1 )
853 self->video_index = video_index;
854 video_codec_init( self, video_index, properties );
857 pthread_mutex_unlock( &self->audio_mutex );
858 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
861 static int seek_video( producer_avformat self, mlt_position position,
862 int req_position, int must_decode, int use_new_seek, int *ignore )
864 mlt_producer producer = self->parent;
867 if ( position != self->video_expected || self->last_position < 0 )
869 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
871 // Fetch the video format context
872 AVFormatContext *context = self->video_format;
874 // Get the video stream
875 AVStream *stream = context->streams[ self->video_index ];
878 AVCodecContext *codec_context = stream->codec;
880 // We may want to use the source fps if available
881 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
882 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
884 if ( self->av_frame && position + 1 == self->video_expected )
886 // We're paused - use last image
889 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
891 // Fast forward - seeking is inefficient for small distances - just ignore following frames
892 *ignore = ( int )( ( position - self->video_expected ) / mlt_producer_get_fps( producer ) * source_fps );
893 codec_context->skip_loop_filter = AVDISCARD_NONREF;
895 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
897 if ( use_new_seek && self->last_position == POSITION_INITIAL )
899 // find first key frame
904 while ( ret >= 0 && toscan-- > 0 )
906 ret = av_read_frame( context, &pkt );
907 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
909 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n", pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
910 self->first_pts = pkt.pts;
913 av_free_packet( &pkt );
916 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
919 // Calculate the timestamp for the requested frame
923 timestamp = ( req_position - 0.1 / source_fps ) /
924 ( av_q2d( stream->time_base ) * source_fps );
925 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %"PRId64" ", req_position, timestamp );
926 if ( self->first_pts > 0 )
927 timestamp += self->first_pts;
928 else if ( context->start_time != AV_NOPTS_VALUE )
929 timestamp += context->start_time;
933 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
934 if ( context->start_time != AV_NOPTS_VALUE )
935 timestamp += context->start_time;
938 timestamp -= AV_TIME_BASE;
941 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %d\n",
942 timestamp, position, self->video_expected, self->last_position );
944 // Seek to the timestamp
947 codec_context->skip_loop_filter = AVDISCARD_NONREF;
948 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
950 else if ( req_position > 0 || self->last_position <= 0 )
952 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
956 // Re-open video stream when rewinding to beginning from somewhere else.
957 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
958 // not reliably seeking to the first frame across formats.
959 reopen_video( self, producer );
962 // Remove the cached info relating to the previous position
963 self->current_position = POSITION_INVALID;
964 self->last_position = POSITION_INVALID;
965 av_freep( &self->av_frame );
969 // flush any pictures still in decode buffer
970 avcodec_flush_buffers( codec_context );
977 /** Convert a frame position to a time code.
980 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
982 return ( double )position / mlt_producer_get_fps( producer );
985 // Collect information about all audio streams
987 static void get_audio_streams_info( producer_avformat self )
989 // Fetch the audio format context
990 AVFormatContext *context = self->audio_format;
994 i < context->nb_streams;
997 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
999 AVCodecContext *codec_context = context->streams[i]->codec;
1000 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1002 // If we don't have a codec and we can't initialise it, we can't do much more...
1004 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1006 self->audio_streams++;
1007 self->audio_max_stream = i;
1008 self->total_channels += codec_context->channels;
1009 if ( codec_context->channels > self->max_channel )
1010 self->max_channel = codec_context->channels;
1011 if ( codec_context->sample_rate > self->max_frequency )
1012 self->max_frequency = codec_context->sample_rate;
1013 avcodec_close( codec_context );
1018 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1019 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1021 // Other audio-specific initializations
1022 self->resample_factor = 1.0;
1025 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1027 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1029 const int *new_coefficients;
1031 int brightness, contrast, saturation;
1033 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1034 &brightness, &contrast, &saturation ) != -1 )
1036 // Don't change these from defaults unless explicitly told to.
1037 if ( use_full_range >= 0 )
1038 full_range = use_full_range;
1039 switch ( colorspace )
1045 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1048 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1051 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1054 new_coefficients = coefficients;
1057 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1058 brightness, contrast, saturation );
1063 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
1064 mlt_image_format *format, int width, int height, int colorspace )
1067 int full_range = -1;
1068 int flags = SWS_BILINEAR | SWS_ACCURATE_RND;
1071 flags |= SWS_CPU_CAPS_MMX;
1074 flags |= SWS_CPU_CAPS_MMX2;
1077 if ( pix_fmt == PIX_FMT_RGB32 )
1079 *format = mlt_image_rgb24a;
1080 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1081 width, height, PIX_FMT_RGBA, flags, NULL, NULL, NULL);
1083 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1084 set_luma_transfer( context, colorspace, full_range );
1085 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1086 output.data, output.linesize);
1087 sws_freeContext( context );
1089 else if ( *format == mlt_image_yuv420p )
1091 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1092 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1094 output.data[0] = buffer;
1095 output.data[1] = buffer + width * height;
1096 output.data[2] = buffer + ( 5 * width * height ) / 4;
1097 output.linesize[0] = width;
1098 output.linesize[1] = width >> 1;
1099 output.linesize[2] = width >> 1;
1100 set_luma_transfer( context, colorspace, full_range );
1101 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1102 output.data, output.linesize);
1103 sws_freeContext( context );
1105 else if ( *format == mlt_image_rgb24 )
1107 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1108 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1110 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1111 set_luma_transfer( context, colorspace, full_range );
1112 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1113 output.data, output.linesize);
1114 sws_freeContext( context );
1116 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1118 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1119 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1121 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1122 set_luma_transfer( context, colorspace, full_range );
1123 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1124 output.data, output.linesize);
1125 sws_freeContext( context );
1129 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1130 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1132 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1133 set_luma_transfer( context, colorspace, full_range );
1134 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1135 output.data, output.linesize);
1136 sws_freeContext( context );
1139 if ( *format == mlt_image_yuv420p )
1142 pict.data[0] = buffer;
1143 pict.data[1] = buffer + width * height;
1144 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1145 pict.linesize[0] = width;
1146 pict.linesize[1] = width >> 1;
1147 pict.linesize[2] = width >> 1;
1148 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1150 else if ( *format == mlt_image_rgb24 )
1153 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1154 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1156 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
1159 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1160 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1165 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1166 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1171 /** Allocate the image buffer and set it on the frame.
1174 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1178 if ( codec_context->width == 0 || codec_context->height == 0 )
1181 *width = codec_context->width;
1182 *height = codec_context->height;
1184 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
1185 size = *width * ( *height + 1 ) * 4;
1187 size = mlt_image_format_size( *format, *width, *height, NULL );
1189 // Construct the output image
1190 *buffer = mlt_pool_alloc( size );
1192 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1199 /** Get an image from a frame.
1202 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1205 producer_avformat self = mlt_frame_pop_service( frame );
1206 mlt_producer producer = self->parent;
1208 // Get the properties from the frame
1209 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1211 // Obtain the frame number of this frame
1212 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1214 // Get the producer properties
1215 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1217 pthread_mutex_lock( &self->video_mutex );
1219 // Fetch the video format context
1220 AVFormatContext *context = self->video_format;
1222 // Get the video stream
1223 AVStream *stream = context->streams[ self->video_index ];
1225 // Get codec context
1226 AVCodecContext *codec_context = stream->codec;
1228 // Get the image cache
1229 if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1230 self->image_cache = mlt_cache_init();
1231 if ( self->image_cache )
1233 mlt_cache_item item = mlt_cache_get( self->image_cache, (void*) position );
1234 uint8_t *original = mlt_cache_item_data( item, (int*) format );
1237 // Set the resolution
1238 *width = codec_context->width;
1239 *height = codec_context->height;
1241 // Workaround 1088 encodings missing cropping info.
1242 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1246 int size = mlt_image_format_size( *format, *width, *height, NULL );
1249 *buffer = mlt_pool_alloc( size );
1250 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1251 memcpy( *buffer, original, size );
1252 mlt_cache_item_close( item );
1257 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1258 mlt_frame_set_image( frame, *buffer, size, NULL );
1260 self->got_picture = 1;
1262 goto exit_get_image;
1271 // Special case ffwd handling
1274 // We may want to use the source fps if available
1275 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1276 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1278 // This is the physical frame position in the source
1279 int req_position = ( int )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1281 // Determines if we have to decode all frames in a sequence
1282 // Temporary hack to improve intra frame only
1283 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
1284 strcmp( codec_context->codec->name, "dvvideo" ) &&
1285 strcmp( codec_context->codec->name, "huffyuv" ) &&
1286 strcmp( codec_context->codec->name, "mjpeg" ) &&
1287 strcmp( codec_context->codec->name, "rawvideo" );
1289 // Turn on usage of new seek API and PTS for seeking
1290 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1291 if ( mlt_properties_get( properties, "new_seek" ) )
1292 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1294 // Seek if necessary
1295 int paused = seek_video( self, position, req_position, must_decode, use_new_seek, &ignore );
1297 // Seek might have reopened the file
1298 context = self->video_format;
1299 stream = context->streams[ self->video_index ];
1300 codec_context = stream->codec;
1302 // Duplicate the last image if necessary
1303 if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture && self->seekable
1305 || self->current_position == req_position
1306 || ( !use_new_seek && self->current_position > req_position ) ) )
1309 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1311 // Workaround 1088 encodings missing cropping info.
1312 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1315 if ( self->vdpau && self->vdpau->buffer )
1318 picture.data[0] = self->vdpau->buffer;
1319 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1320 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1321 picture.linesize[0] = codec_context->width;
1322 picture.linesize[1] = codec_context->width / 2;
1323 picture.linesize[2] = codec_context->width / 2;
1324 convert_image( (AVFrame*) &picture, *buffer,
1325 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1329 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1330 format, *width, *height, self->colorspace );
1333 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1338 int int_position = 0;
1339 int decode_errors = 0;
1340 int got_picture = 0;
1342 av_init_packet( &pkt );
1344 // Construct an AVFrame for YUV422 conversion
1345 if ( !self->av_frame )
1346 self->av_frame = avcodec_alloc_frame( );
1348 while( ret >= 0 && !got_picture )
1351 ret = av_read_frame( context, &pkt );
1353 // We only deal with video from the selected video_index
1354 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1356 // Determine time code of the packet
1359 int64_t pts = pkt.pts;
1360 if ( self->first_pts > 0 )
1361 pts -= self->first_pts;
1362 else if ( context->start_time != AV_NOPTS_VALUE )
1363 pts -= context->start_time;
1364 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1365 if ( pkt.pts == AV_NOPTS_VALUE )
1367 self->invalid_pts_counter++;
1368 if ( self->invalid_pts_counter > 20 )
1370 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1371 mlt_properties_set_int( properties, "new_seek", 0 );
1372 int_position = req_position;
1378 self->invalid_pts_counter = 0;
1380 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1381 pkt.pts, req_position, self->current_position, int_position );
1385 if ( self->seekable && pkt.dts != AV_NOPTS_VALUE )
1387 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1388 if ( context->start_time != AV_NOPTS_VALUE )
1389 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1390 if ( int_position == self->last_position )
1391 int_position = self->last_position + 1;
1395 int_position = req_position;
1397 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1398 pkt.dts, req_position, self->current_position, int_position );
1399 // Make a dumb assumption on streams that contain wild timestamps
1400 if ( abs( req_position - int_position ) > 999 )
1402 int_position = req_position;
1403 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1406 self->last_position = int_position;
1409 if ( must_decode || int_position >= req_position )
1412 if ( g_vdpau && self->vdpau )
1414 if ( g_vdpau->producer != self )
1416 vdpau_decoder_close();
1417 vdpau_decoder_init( self );
1420 self->vdpau->is_decoded = 0;
1423 codec_context->reordered_opaque = pkt.pts;
1424 if ( int_position >= req_position )
1425 codec_context->skip_loop_filter = AVDISCARD_NONE;
1426 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1427 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1429 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1431 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1434 if ( ++decode_errors <= 10 )
1447 // Determine time code of the packet
1448 int64_t pts = self->av_frame->reordered_opaque;
1449 if ( self->first_pts > 0 )
1450 pts -= self->first_pts;
1451 else if ( context->start_time != AV_NOPTS_VALUE )
1452 pts -= context->start_time;
1453 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1454 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, self->av_frame->key_frame );
1457 if ( int_position < req_position )
1462 else if ( int_position >= req_position )
1465 codec_context->skip_loop_filter = AVDISCARD_NONE;
1467 else if ( ignore -- )
1472 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1475 // Now handle the picture if we have one
1478 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1480 // Workaround 1088 encodings missing cropping info.
1481 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1486 if ( self->vdpau->is_decoded )
1488 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1490 uint32_t pitches[3];
1491 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1493 if ( !self->vdpau->buffer )
1494 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1495 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1496 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1497 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1498 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1499 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1500 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1502 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1503 if ( status == VDP_STATUS_OK )
1505 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1506 format, *width, *height, self->colorspace );
1510 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1511 image_size = self->vdpau->is_decoded = 0;
1516 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1517 image_size = got_picture = 0;
1522 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1523 format, *width, *height, self->colorspace );
1524 self->top_field_first |= self->av_frame->top_field_first;
1525 self->current_position = int_position;
1526 self->got_picture = 1;
1534 av_free_packet( &pkt );
1538 if ( self->got_picture && image_size > 0 && self->image_cache )
1540 // Copy buffer to image cache
1541 uint8_t *image = mlt_pool_alloc( image_size );
1542 memcpy( image, *buffer, image_size );
1543 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1545 // Try to duplicate last image if there was a decoding failure
1546 else if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1549 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1551 // Workaround 1088 encodings missing cropping info.
1552 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1555 if ( self->vdpau && self->vdpau->buffer )
1558 picture.data[0] = self->vdpau->buffer;
1559 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1560 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1561 picture.linesize[0] = codec_context->width;
1562 picture.linesize[1] = codec_context->width / 2;
1563 picture.linesize[2] = codec_context->width / 2;
1564 convert_image( (AVFrame*) &picture, *buffer,
1565 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1569 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1570 format, *width, *height, self->colorspace );
1571 self->got_picture = 1;
1574 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1577 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1578 self->video_expected = position + 1;
1582 pthread_mutex_unlock( &self->video_mutex );
1584 // Set the progressive flag
1585 if ( mlt_properties_get( properties, "force_progressive" ) )
1586 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1587 else if ( self->av_frame )
1588 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1590 // Set the field order property for this frame
1591 if ( mlt_properties_get( properties, "force_tff" ) )
1592 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1594 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1596 // Set immutable properties of the selected track's (or overridden) source attributes.
1597 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1598 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1599 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1600 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1602 return !self->got_picture;
1605 /** Process properties as AVOptions and apply to AV context obj
1608 static void apply_properties( void *obj, mlt_properties properties, int flags )
1611 int count = mlt_properties_count( properties );
1612 for ( i = 0; i < count; i++ )
1614 const char *opt_name = mlt_properties_get_name( properties, i );
1615 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1616 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1619 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1620 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1621 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1622 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1624 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1630 /** Initialize the video codec context.
1633 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1635 // Initialise the codec if necessary
1636 if ( !self->video_codec )
1638 // Get the video stream
1639 AVStream *stream = self->video_format->streams[ index ];
1641 // Get codec context
1642 AVCodecContext *codec_context = stream->codec;
1645 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1647 if ( codec_context->codec_id == CODEC_ID_H264 )
1649 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1651 if ( vdpau_init( self ) )
1653 self->video_codec = codec_context;
1654 if ( !vdpau_decoder_init( self ) )
1655 vdpau_decoder_close();
1659 codec = avcodec_find_decoder( codec_context->codec_id );
1663 // Initialise multi-threading
1664 int thread_count = mlt_properties_get_int( properties, "threads" );
1665 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1666 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1667 if ( thread_count > 1 )
1668 codec_context->thread_count = thread_count;
1670 // If we don't have a codec and we can't initialise it, we can't do much more...
1672 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1674 // Now store the codec with its destructor
1675 self->video_codec = codec_context;
1679 // Remember that we can't use this later
1680 self->video_index = -1;
1686 // Process properties as AVOptions
1687 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1688 #if LIBAVCODEC_VERSION_MAJOR > 52
1689 if ( codec->priv_class && codec_context->priv_data )
1690 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1693 // Reset some image properties
1694 mlt_properties_set_int( properties, "width", self->video_codec->width );
1695 mlt_properties_set_int( properties, "height", self->video_codec->height );
1696 // For DV, we'll just use the saved aspect ratio
1697 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1698 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1700 // Determine the fps first from the codec
1701 double source_fps = (double) self->video_codec->time_base.den /
1702 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1704 if ( mlt_properties_get( properties, "force_fps" ) )
1706 source_fps = mlt_properties_get_double( properties, "force_fps" );
1707 stream->time_base = av_d2q( source_fps, 1024 );
1708 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1709 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1713 // If the muxer reports a frame rate different than the codec
1714 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1715 double muxer_fps = av_q2d( stream->avg_frame_rate );
1716 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1717 muxer_fps = av_q2d( stream->r_frame_rate );
1719 double muxer_fps = av_q2d( stream->r_frame_rate );
1721 // Choose the lesser - the wrong tends to be off by some multiple of 10
1722 source_fps = FFMIN( source_fps, muxer_fps );
1723 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1725 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1726 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1728 else if ( muxer_fps > 0 )
1730 AVRational frame_rate = stream->r_frame_rate;
1731 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1732 // avg_frame_rate gives some approximate value that does not well match the media.
1733 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1734 // results in some very choppy output, but some value slightly different works
1736 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1737 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1738 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1740 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1741 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1745 source_fps = mlt_producer_get_fps( self->parent );
1746 AVRational frame_rate = av_d2q( source_fps, 255 );
1747 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1748 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1752 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1753 if ( source_fps > 0 )
1754 mlt_properties_set_double( properties, "source_fps", source_fps );
1756 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
1758 // Set the YUV colorspace from override or detect
1759 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1760 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1761 if ( ! self->colorspace )
1763 switch ( self->video_codec->colorspace )
1765 case AVCOL_SPC_SMPTE240M:
1766 self->colorspace = 240;
1768 case AVCOL_SPC_BT470BG:
1769 case AVCOL_SPC_SMPTE170M:
1770 self->colorspace = 601;
1772 case AVCOL_SPC_BT709:
1773 self->colorspace = 709;
1776 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1777 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1782 // Let apps get chosen colorspace
1783 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1785 return self->video_codec && self->video_index > -1;
1788 /** Set up video handling.
1791 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1794 mlt_producer producer = self->parent;
1796 // Get the properties
1797 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1799 // Fetch the video format context
1800 AVFormatContext *context = self->video_format;
1802 // Get the video_index
1803 int index = mlt_properties_get_int( properties, "video_index" );
1805 // Reopen the file if necessary
1806 if ( !context && index > -1 )
1808 mlt_events_block( properties, producer );
1809 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1810 mlt_properties_get( properties, "resource" ) );
1811 context = self->video_format;
1812 if ( self->dummy_context )
1814 av_close_input_file( self->dummy_context );
1815 self->dummy_context = NULL;
1817 mlt_events_unblock( properties, producer );
1818 if ( self->audio_format && !self->audio_streams )
1819 get_audio_streams_info( self );
1821 // Process properties as AVOptions
1824 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1825 #if LIBAVFORMAT_VERSION_MAJOR > 52
1826 if ( context->iformat && context->iformat->priv_class && context->priv_data )
1827 apply_properties( context->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
1832 // Exception handling for video_index
1833 if ( context && index >= (int) context->nb_streams )
1835 // Get the last video stream
1836 for ( index = context->nb_streams - 1;
1837 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1839 mlt_properties_set_int( properties, "video_index", index );
1841 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1843 // Invalidate the video stream
1845 mlt_properties_set_int( properties, "video_index", index );
1848 // Update the video properties if the index changed
1849 if ( index != self->video_index )
1851 // Reset the video properties if the index changed
1852 self->video_index = index;
1853 if ( self->video_codec )
1856 avcodec_close( self->video_codec );
1859 self->video_codec = NULL;
1862 // Get the frame properties
1863 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1866 if ( context && index > -1 && video_codec_init( self, index, properties ) )
1868 // Set the frame properties
1869 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1870 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1871 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1873 // Set the width and height
1874 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
1875 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
1876 // real_width and real_height are deprecated in favor of meta.media.width and .height
1877 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
1878 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
1879 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
1880 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
1881 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1882 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
1884 // Workaround 1088 encodings missing cropping info.
1885 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1887 mlt_properties_set_int( properties, "meta.media.height", 1080 );
1888 mlt_properties_set_int( frame_properties, "real_height", 1080 );
1891 // Add our image operation
1892 mlt_frame_push_service( frame, self );
1893 mlt_frame_push_get_image( frame, producer_get_image );
1897 // If something failed, use test card image
1898 mlt_properties_set_int( frame_properties, "test_image", 1 );
1902 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
1906 // Seek if necessary
1907 if ( position != self->audio_expected )
1909 if ( position + 1 == self->audio_expected )
1911 // We're paused - silence required
1914 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
1916 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1917 *ignore = position - self->audio_expected;
1919 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
1921 AVFormatContext *context = self->audio_format;
1922 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1923 if ( context->start_time != AV_NOPTS_VALUE )
1924 timestamp += context->start_time;
1925 if ( timestamp < 0 )
1928 // Set to the real timecode
1929 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1932 // Clear the usage in the audio buffer
1933 int i = MAX_AUDIO_STREAMS + 1;
1935 self->audio_used[i - 1] = 0;
1941 static int sample_bytes( AVCodecContext *context )
1943 #if LIBAVCODEC_VERSION_MAJOR > 52
1944 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
1946 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
1950 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
1952 // Fetch the audio_format
1953 AVFormatContext *context = self->audio_format;
1955 // Get the current stream index
1956 int index = pkt.stream_index;
1958 // Get codec context
1959 AVCodecContext *codec_context = self->audio_codec[ index ];
1961 // Obtain the resample context if it exists (not always needed)
1962 ReSampleContext *resample = self->audio_resample[ index ];
1964 // Obtain the audio buffers
1965 uint8_t *audio_buffer = self->audio_buffer[ index ];
1966 uint8_t *decode_buffer = self->decode_buffer[ index ];
1968 int audio_used = self->audio_used[ index ];
1969 uint8_t *ptr = pkt.data;
1973 while ( ptr && ret >= 0 && len > 0 )
1975 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
1976 int data_size = self->audio_buffer_size[ index ];
1979 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1980 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
1981 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1982 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1984 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1988 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
1992 pkt.size = len -= ret;
1993 pkt.data = ptr += ret;
1995 // If decoded successfully
1996 if ( data_size > 0 )
1998 // Figure out how many samples will be needed after resampling
1999 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2000 int samples_needed = self->resample_factor * convert_samples;
2002 // Resize audio buffer to prevent overflow
2003 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2005 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2006 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2010 // Copy to audio buffer while resampling
2011 uint8_t *source = decode_buffer;
2012 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2013 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2017 // Straight copy to audio buffer
2018 memcpy( &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ], decode_buffer, data_size );
2019 audio_used += convert_samples;
2023 while ( *ignore && audio_used > samples )
2026 audio_used -= samples;
2027 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2028 audio_used * sizeof_sample );
2033 // If we're behind, ignore this packet
2036 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
2037 int req_position = ( int )( timecode * fps + 0.5 );
2038 int int_position = ( int )( current_pts * fps + 0.5 );
2039 if ( context->start_time != AV_NOPTS_VALUE )
2040 int_position -= ( int )( fps * context->start_time / AV_TIME_BASE + 0.5 );
2042 if ( self->seekable && *ignore == 0 )
2044 if ( int_position < req_position )
2045 // We are behind, so skip some
2047 else if ( int_position > req_position + 2 )
2048 // We are ahead, so seek backwards some more
2049 seek_audio( self, req_position, timecode - 1.0, ignore );
2053 self->audio_used[ index ] = audio_used;
2058 /** Get the audio from a frame.
2060 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2063 producer_avformat self = mlt_frame_pop_audio( frame );
2065 pthread_mutex_lock( &self->audio_mutex );
2067 // Obtain the frame number of this frame
2068 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
2070 // Calculate the real time code
2071 double real_timecode = producer_time_of_frame( self->parent, position );
2073 // Get the producer fps
2074 double fps = mlt_producer_get_fps( self->parent );
2076 // Number of frames to ignore (for ffwd)
2079 // Flag for paused (silence)
2080 int paused = seek_audio( self, position, real_timecode, &ignore );
2082 // Fetch the audio_format
2083 AVFormatContext *context = self->audio_format;
2085 int sizeof_sample = sizeof( int16_t );
2087 // Determine the tracks to use
2088 int index = self->audio_index;
2089 int index_max = self->audio_index + 1;
2090 if ( self->audio_index == INT_MAX )
2093 index_max = context->nb_streams;
2094 *channels = self->total_channels;
2095 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2096 *frequency = FFMAX( self->max_frequency, *frequency );
2099 // Initialize the resamplers and buffers
2100 for ( ; index < index_max; index++ )
2102 // Get codec context
2103 AVCodecContext *codec_context = self->audio_codec[ index ];
2105 if ( codec_context && !self->audio_buffer[ index ] )
2107 // Check for resample and create if necessary
2108 if ( codec_context->channels <= 2 )
2110 // Determine by how much resampling will increase number of samples
2111 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2112 resample_factor *= (double) *frequency / codec_context->sample_rate;
2113 if ( resample_factor > self->resample_factor )
2114 self->resample_factor = resample_factor;
2116 // Create the resampler
2117 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2118 self->audio_resample[ index ] = av_audio_resample_init(
2119 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2120 codec_context->channels, *frequency, codec_context->sample_rate,
2121 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2123 self->audio_resample[ index ] = audio_resample_init(
2124 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2125 codec_context->channels, *frequency, codec_context->sample_rate );
2130 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2131 sizeof_sample = sample_bytes( codec_context );
2134 // Check for audio buffer and create if necessary
2135 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2136 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2138 // Check for decoder buffer and create if necessary
2139 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2143 // Get the audio if required
2150 av_init_packet( &pkt );
2152 // If not resampling, give consumer more than requested.
2153 // It requested number samples based on requested frame rate.
2154 // Do not clean this up with a samples *= ...!
2155 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2156 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2158 while ( ret >= 0 && !got_audio )
2160 // Check if the buffer already contains the samples required
2161 if ( self->audio_index != INT_MAX && self->audio_used[ self->audio_index ] >= *samples && ignore == 0 )
2168 ret = av_read_frame( context, &pkt );
2170 // We only deal with audio from the selected audio index
2171 index = pkt.stream_index;
2172 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2173 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2175 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2176 self->audio_codec[index]->channels : *channels;
2177 ret = decode_audio( self, &ignore, pkt, channels2, *samples, real_timecode, fps );
2179 av_free_packet( &pkt );
2181 if ( self->audio_index == INT_MAX && ret >= 0 )
2183 // Determine if there is enough audio for all streams
2185 for ( index = 0; index < context->nb_streams; index++ )
2187 if ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples )
2193 // Set some additional return values
2194 *format = mlt_audio_s16;
2195 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2197 index = self->audio_index;
2198 *channels = self->audio_codec[ index ]->channels;
2199 *frequency = self->audio_codec[ index ]->sample_rate;
2200 *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2201 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2203 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2205 else if ( self->audio_index == INT_MAX )
2207 // This only works if all audio tracks have the same sample format.
2208 for ( index = 0; index < index_max; index++ )
2209 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2211 *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2212 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2214 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2219 // Allocate and set the frame's audio buffer
2220 int size = mlt_audio_format_size( *format, *samples, *channels );
2221 *buffer = mlt_pool_alloc( size );
2222 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2224 // Interleave tracks if audio_index=all
2225 if ( self->audio_index == INT_MAX )
2227 uint8_t *dest = *buffer;
2229 for ( i = 0; i < *samples; i++ )
2231 for ( index = 0; index < index_max; index++ )
2232 if ( self->audio_codec[ index ] )
2234 int current_channels = self->audio_codec[ index ]->channels;
2235 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2236 memcpy( dest, src, current_channels * sizeof_sample );
2237 dest += current_channels * sizeof_sample;
2240 for ( index = 0; index < index_max; index++ )
2241 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2243 int current_channels = self->audio_codec[ index ]->channels;
2244 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2245 self->audio_used[index] -= *samples;
2246 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2249 // Copy a single track to the output buffer
2252 index = self->audio_index;
2254 // Now handle the audio if we have enough
2255 if ( self->audio_used[ index ] > 0 )
2257 uint8_t *src = self->audio_buffer[ index ];
2258 // copy samples from audio_buffer
2259 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2260 memcpy( *buffer, src, size * *channels * sizeof_sample );
2261 // supply the remaining requested samples as silence
2262 if ( *samples > self->audio_used[ index ] )
2263 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2264 // reposition the samples within audio_buffer
2265 self->audio_used[ index ] -= size;
2266 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2270 // Otherwise fill with silence
2271 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2277 // Get silence and don't touch the context
2278 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2281 // Regardless of speed (other than paused), we expect to get the next frame
2283 self->audio_expected = position + 1;
2285 pthread_mutex_unlock( &self->audio_mutex );
2290 /** Initialize the audio codec context.
2293 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2295 // Initialise the codec if necessary
2296 if ( !self->audio_codec[ index ] )
2298 // Get codec context
2299 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2302 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2304 // If we don't have a codec and we can't initialise it, we can't do much more...
2306 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2308 // Now store the codec with its destructor
2309 if ( self->audio_codec[ index ] )
2310 avcodec_close( self->audio_codec[ index ] );
2311 self->audio_codec[ index ] = codec_context;
2315 // Remember that we can't use self later
2316 self->audio_index = -1;
2320 // Process properties as AVOptions
2321 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2322 #if LIBAVCODEC_VERSION_MAJOR > 52
2323 if ( codec && codec->priv_class && codec_context->priv_data )
2324 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2327 return self->audio_codec[ index ] && self->audio_index > -1;
2330 /** Set up audio handling.
2333 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2336 mlt_producer producer = self->parent;
2338 // Get the properties
2339 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2341 // Fetch the audio format context
2342 AVFormatContext *context = self->audio_format;
2344 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2346 // Get the audio_index
2347 int index = mlt_properties_get_int( properties, "audio_index" );
2349 // Handle all audio tracks
2350 if ( self->audio_index > -1 &&
2351 mlt_properties_get( properties, "audio_index" ) &&
2352 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2355 // Reopen the file if necessary
2356 if ( !context && self->audio_index > -1 && index > -1 )
2358 mlt_events_block( properties, producer );
2359 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2360 mlt_properties_get( properties, "resource" ) );
2361 context = self->audio_format;
2362 if ( self->dummy_context )
2364 av_close_input_file( self->dummy_context );
2365 self->dummy_context = NULL;
2367 mlt_events_unblock( properties, producer );
2368 if ( self->audio_format )
2369 get_audio_streams_info( self );
2372 // Exception handling for audio_index
2373 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2375 for ( index = context->nb_streams - 1;
2376 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2378 mlt_properties_set_int( properties, "audio_index", index );
2380 if ( context && index > -1 && index < INT_MAX &&
2381 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2383 index = self->audio_index;
2384 mlt_properties_set_int( properties, "audio_index", index );
2387 // Update the audio properties if the index changed
2388 if ( context && index > -1 && index != self->audio_index )
2390 if ( self->audio_codec[ self->audio_index ] )
2393 avcodec_close( self->audio_codec[ self->audio_index ] );
2396 self->audio_codec[ self->audio_index ] = NULL;
2398 if ( self->audio_index != -1 )
2399 self->audio_index = index;
2404 if ( context && index == INT_MAX )
2406 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2407 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2408 for ( index = 0; index < context->nb_streams; index++ )
2410 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2411 audio_codec_init( self, index, properties );
2414 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2416 // Set the frame properties
2417 if ( index < INT_MAX )
2419 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2420 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2423 if ( context && index > -1 )
2425 // Add our audio operation
2426 mlt_frame_push_audio( frame, self );
2427 mlt_frame_push_audio( frame, producer_get_audio );
2431 /** Our get frame implementation.
2434 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2436 // Access the private data
2437 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2438 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2439 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2444 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2445 producer->child = self;
2446 self->parent = producer;
2447 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2448 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2451 // Create an empty frame
2452 *frame = mlt_frame_init( service);
2456 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2460 mlt_cache_item_close( cache_item );
2464 // Update timecode on the frame we're creating
2465 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2467 // Set the position of this producer
2468 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
2471 producer_set_up_video( self, *frame );
2474 producer_set_up_audio( self, *frame );
2476 // Calculate the next timecode
2477 mlt_producer_prepare_next( producer );
2482 static void producer_avformat_close( producer_avformat self )
2484 mlt_log_debug( NULL, "producer_avformat_close\n" );
2486 av_free( self->av_frame );
2489 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2491 if ( self->audio_resample[i] )
2492 audio_resample_close( self->audio_resample[i] );
2493 mlt_pool_release( self->audio_buffer[i] );
2494 av_free( self->decode_buffer[i] );
2495 if ( self->audio_codec[i] )
2496 avcodec_close( self->audio_codec[i] );
2498 if ( self->video_codec )
2499 avcodec_close( self->video_codec );
2500 if ( self->dummy_context )
2501 av_close_input_file( self->dummy_context );
2502 if ( self->audio_format )
2503 av_close_input_file( self->audio_format );
2504 if ( self->video_format )
2505 av_close_input_file( self->video_format );
2508 vdpau_producer_close( self );
2510 if ( self->image_cache )
2511 mlt_cache_close( self->image_cache );
2512 pthread_mutex_destroy( &self->audio_mutex );
2513 pthread_mutex_destroy( &self->video_mutex );
2517 static void producer_close( mlt_producer parent )
2519 // Remove this instance from the cache
2520 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2523 parent->close = NULL;
2524 mlt_producer_close( parent );