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 >= 53
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 >= 53
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;
94 int64_t last_position;
96 int64_t current_position;
97 mlt_position nonseek_position;
100 uint8_t *audio_buffer[ MAX_AUDIO_STREAMS ];
101 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
102 uint8_t *decode_buffer[ MAX_AUDIO_STREAMS ];
103 int audio_used[ MAX_AUDIO_STREAMS ];
105 int audio_max_stream;
109 unsigned int invalid_pts_counter;
110 double resample_factor;
111 mlt_cache image_cache;
113 pthread_mutex_t video_mutex;
114 pthread_mutex_t audio_mutex;
117 pthread_mutex_t packets_mutex;
122 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
133 typedef struct producer_avformat_s *producer_avformat;
135 // Forward references.
136 static int list_components( char* file );
137 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock );
138 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
139 static void producer_avformat_close( producer_avformat );
140 static void producer_close( mlt_producer parent );
141 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
142 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
143 static void apply_properties( void *obj, mlt_properties properties, int flags );
144 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
145 static void get_audio_streams_info( producer_avformat self );
151 /** Constructor for libavformat.
154 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
156 if ( list_components( file ) )
159 mlt_producer producer = NULL;
161 // Check that we have a non-NULL argument
164 // Construct the producer
165 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
166 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
169 if ( mlt_producer_init( producer, self ) == 0 )
171 self->parent = producer;
173 // Get the properties
174 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
176 // Set the resource property (required for all producers)
177 mlt_properties_set( properties, "resource", file );
179 // Register transport implementation with the producer
180 producer->close = (mlt_destructor) producer_close;
182 // Register our get_frame implementation
183 producer->get_frame = producer_get_frame;
185 if ( strcmp( service, "avformat-novalidate" ) )
188 if ( producer_open( self, profile, file, 1 ) != 0 )
191 mlt_producer_close( producer );
194 else if ( self->seekable )
196 // Close the file to release resources for large playlists - reopen later as needed
198 if ( self->audio_format )
199 av_close_input_file( self->audio_format );
200 self->audio_format = NULL;
201 if ( self->video_format )
202 av_close_input_file( self->video_format );
203 self->video_format = NULL;
209 // Default the user-selectable indices from the auto-detected indices
210 mlt_properties_set_int( properties, "audio_index", self->audio_index );
211 mlt_properties_set_int( properties, "video_index", self->video_index );
213 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
215 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
222 int list_components( char* file )
226 // Report information about available demuxers and codecs as YAML Tiny
227 if ( file && strstr( file, "f-list" ) )
229 fprintf( stderr, "---\nformats:\n" );
230 AVInputFormat *format = NULL;
231 while ( ( format = av_iformat_next( format ) ) )
232 fprintf( stderr, " - %s\n", format->name );
233 fprintf( stderr, "...\n" );
236 if ( file && strstr( file, "acodec-list" ) )
238 fprintf( stderr, "---\naudio_codecs:\n" );
239 AVCodec *codec = NULL;
240 while ( ( codec = av_codec_next( codec ) ) )
241 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
242 fprintf( stderr, " - %s\n", codec->name );
243 fprintf( stderr, "...\n" );
246 if ( file && strstr( file, "vcodec-list" ) )
248 fprintf( stderr, "---\nvideo_codecs:\n" );
249 AVCodec *codec = NULL;
250 while ( ( codec = av_codec_next( codec ) ) )
251 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
252 fprintf( stderr, " - %s\n", codec->name );
253 fprintf( stderr, "...\n" );
260 /** Find the default streams.
263 static mlt_properties find_default_streams( producer_avformat self )
267 AVMetadataTag *tag = NULL;
268 AVFormatContext *context = self->video_format;
269 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
271 // Default to the first audio and video streams found
272 self->audio_index = -1;
273 self->video_index = -1;
275 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
277 // Allow for multiple audio and video streams in the file and select first of each (if available)
278 for( i = 0; i < context->nb_streams; i++ )
280 // Get the codec context
281 AVStream *stream = context->streams[ i ];
282 if ( ! stream ) continue;
283 AVCodecContext *codec_context = stream->codec;
284 if ( ! codec_context ) continue;
285 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
286 if ( ! codec ) continue;
288 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
290 // Determine the type and obtain the first index of each type
291 switch( codec_context->codec_type )
293 case CODEC_TYPE_VIDEO:
294 // Use first video stream
295 if ( self->video_index < 0 )
296 self->video_index = i;
297 mlt_properties_set( meta_media, key, "video" );
298 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
299 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
300 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
301 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
302 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
303 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
305 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
308 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
309 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
310 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
312 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
313 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
314 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
315 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
316 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
317 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
318 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
319 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
320 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
321 switch ( codec_context->colorspace )
323 case AVCOL_SPC_SMPTE240M:
324 mlt_properties_set_int( meta_media, key, 240 );
326 case AVCOL_SPC_BT470BG:
327 case AVCOL_SPC_SMPTE170M:
328 mlt_properties_set_int( meta_media, key, 601 );
330 case AVCOL_SPC_BT709:
331 mlt_properties_set_int( meta_media, key, 709 );
334 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
335 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
340 case CODEC_TYPE_AUDIO:
341 // Use first audio stream
342 if ( self->audio_index < 0 )
343 self->audio_index = i;
344 mlt_properties_set( meta_media, key, "audio" );
345 #if LIBAVCODEC_VERSION_MAJOR >= 53
346 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
347 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
348 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
349 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
350 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
352 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
353 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
354 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
355 mlt_properties_set_int( meta_media, key, codec_context->channels );
360 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
361 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
362 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
363 mlt_properties_set( meta_media, key, codec->name );
364 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
365 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
366 mlt_properties_set( meta_media, key, codec->long_name );
368 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
369 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
370 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
371 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
372 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
373 // mlt_properties_set_int( meta_media, key, codec_context->profile );
374 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
375 // mlt_properties_set_int( meta_media, key, codec_context->level );
378 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
379 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
381 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
383 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
384 mlt_properties_set( meta_media, key, tag->value );
389 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
390 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
392 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
394 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
395 mlt_properties_set( meta_media, key, tag->value );
399 if ( context->title && strcmp( context->title, "" ) )
400 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
401 if ( context->author && strcmp( context->author, "" ) )
402 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
403 if ( context->copyright && strcmp( context->copyright, "" ) )
404 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
405 if ( context->comment )
406 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
407 if ( context->album )
408 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
410 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
411 if ( context->track )
412 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
418 static inline int dv_is_pal( AVPacket *pkt )
420 return pkt->data[3] & 0x80;
423 static int dv_is_wide( AVPacket *pkt )
425 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
427 for ( ; i < pkt->size; i += 5 /* packet size */ )
429 if ( pkt->data[ i ] == 0x61 )
431 uint8_t x = pkt->data[ i + 2 ] & 0x7;
432 return ( x == 2 ) || ( x == 7 );
438 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
440 double aspect_ratio = 1.0;
442 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
446 if ( dv_is_pal( pkt ) )
448 if ( dv_is_wide( pkt ) )
450 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
451 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
455 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
456 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
461 if ( dv_is_wide( pkt ) )
463 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
464 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
468 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
469 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
476 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
477 stream->sample_aspect_ratio;
479 codec_context->sample_aspect_ratio;
481 // Override FFmpeg's notion of DV aspect ratios, which are
482 // based upon a width of 704. Since we do not have a normaliser
483 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
484 // we just coerce the values to facilitate a passive behaviour through
485 // the rescale normaliser when using equivalent producers and consumers.
486 // = display_aspect / (width * height)
487 if ( ar.num == 10 && ar.den == 11 )
490 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
491 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
493 else if ( ar.num == 59 && ar.den == 54 )
496 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
497 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
499 else if ( ar.num == 40 && ar.den == 33 )
502 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
503 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
505 else if ( ar.num == 118 && ar.den == 81 )
508 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
509 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
515 AVRational codec_sar = codec_context->sample_aspect_ratio;
516 AVRational stream_sar =
517 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
518 stream->sample_aspect_ratio;
522 if ( codec_sar.num > 0 )
524 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
525 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
527 else if ( stream_sar.num > 0 )
529 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
530 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
534 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
535 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
538 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
539 aspect_ratio = av_q2d( ar );
540 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
545 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
547 if ( !URL ) return NULL;
549 const char *result = URL;
550 char *protocol = strdup( URL );
551 char *url = strchr( protocol, ':' );
553 // Only if there is not a protocol specification that avformat can handle
554 #if LIBAVFORMAT_VERSION_MAJOR >= 53
555 if ( url && avio_check( URL, 0 ) < 0 )
557 if ( url && !url_exist( URL ) )
560 // Truncate protocol string
562 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
565 *format = av_find_input_format( protocol );
567 // Eat the format designator
572 // These are required by video4linux2 (defaults)
573 params->width = profile->width;
574 params->height = profile->height;
575 if ( !strstr( URL, "&frame_rate" ) )
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, '=' );
588 // Also accept : as delimiter for backwards compatibility.
589 value = strchr( name, ':' );
594 char *t = strchr( value, '&' );
597 if ( !strcmp( name, "frame_rate" ) )
598 params->time_base.den = atoi( value );
599 else if ( !strcmp( name, "frame_rate_base" ) )
600 params->time_base.num = atoi( value );
601 else if ( !strcmp( name, "sample_rate" ) )
602 params->sample_rate = atoi( value );
603 else if ( !strcmp( name, "channel" ) )
604 params->channel = atoi( value );
605 else if ( !strcmp( name, "channels" ) )
606 params->channels = atoi( value );
607 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
608 else if ( !strcmp( name, "pix_fmt" ) )
609 params->pix_fmt = av_get_pix_fmt( value );
611 else if ( !strcmp( name, "width" ) )
612 params->width = atoi( value );
613 else if ( !strcmp( name, "height" ) )
614 params->height = atoi( value );
615 else if ( !strcmp( name, "standard" ) )
616 params->standard = strdup( value );
619 url = strchr( url, '&' );
623 result = strdup( result );
628 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
632 // Get the properties
633 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
635 AVFormatContext *format = self->video_format;
637 // We will treat everything with the producer fps.
638 // TODO: make this more flexible.
639 double fps = mlt_profile_fps( profile );
642 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
644 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
645 // when producer_open is called after initial call when restoring or reseting the producer.
646 if ( format->duration != AV_NOPTS_VALUE )
648 // This isn't going to be accurate for all formats
649 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
650 mlt_properties_set_position( properties, "out", frames - 1 );
651 mlt_properties_set_position( properties, "length", frames );
652 mlt_properties_set_int( properties, "_length_computed", 1 );
656 // Set live sources to run forever
657 mlt_properties_set_position( properties, "length", INT_MAX );
658 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
659 mlt_properties_set( properties, "eof", "loop" );
660 mlt_properties_set_int( properties, "_length_computed", 1 );
664 if ( format->start_time != AV_NOPTS_VALUE )
665 self->start_time = format->start_time;
667 // Check if we're seekable
668 // avdevices are typically AVFMT_NOFILE and not seekable
669 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
672 // protocols can indicate if they support seeking
673 #if LIBAVFORMAT_VERSION_MAJOR >= 53
674 self->seekable = format->pb->seekable;
676 URLContext *uc = url_fileno( format->pb );
678 self->seekable = !uc->is_streamed;
681 if ( self->seekable )
683 // Do a more rigourous test of seekable on a disposable context
684 self->seekable = av_seek_frame( format, -1, self->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
685 mlt_properties_set_int( properties, "seekable", self->seekable );
686 self->dummy_context = format;
687 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
688 format = self->video_format;
689 av_find_stream_info( format );
692 // Fetch the width, height and aspect ratio
693 if ( self->video_index != -1 )
695 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
696 mlt_properties_set_int( properties, "width", codec_context->width );
697 mlt_properties_set_int( properties, "height", codec_context->height );
699 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
701 // Fetch the first frame of DV so we can read it directly
706 ret = av_read_frame( format, &pkt );
707 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
709 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
716 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
720 // Verify that we can convert this to YUV 4:2:2
721 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
722 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
723 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
725 sws_freeContext( context );
736 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
738 // Return an error code (0 == no error)
740 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
745 pthread_mutex_init( &self->audio_mutex, NULL );
746 pthread_mutex_init( &self->video_mutex, NULL );
747 pthread_mutex_init( &self->packets_mutex, NULL );
748 pthread_mutex_lock( &self->audio_mutex );
749 pthread_mutex_lock( &self->video_mutex );
751 mlt_events_block( properties, self->parent );
754 AVInputFormat *format = NULL;
755 AVFormatParameters params;
756 memset( ¶ms, 0, sizeof(params) );
757 char *filename = parse_url( profile, URL, &format, ¶ms );
759 // Now attempt to open the file or device with filename
760 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
762 // If the URL is a network stream URL, then we probably need to open with full URL
763 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
765 // Set MLT properties onto video AVFormatContext
766 if ( !error && self->video_format )
768 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
769 #if LIBAVFORMAT_VERSION_MAJOR >= 53
770 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
771 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
775 // Cleanup AVFormatParameters
776 if ( params.standard )
777 free( (void*) params.standard );
779 // If successful, then try to get additional info
780 if ( !error && self->video_format )
782 // Get the stream info
783 error = av_find_stream_info( self->video_format ) < 0;
785 // Continue if no error
786 if ( !error && self->video_format )
788 // Find default audio and video streams
789 find_default_streams( self );
790 error = get_basic_info( self, profile, filename );
792 // Initialize position info
793 self->first_pts = -1;
794 self->last_position = POSITION_INITIAL;
796 if ( !self->audio_format )
798 // We're going to cheat here - for seekable A/V files, we will have separate contexts
799 // to support independent seeking of audio from video.
800 // TODO: Is this really necessary?
801 if ( self->audio_index != -1 && self->video_index != -1 )
803 if ( self->seekable )
805 // And open again for our audio context
806 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
807 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
808 #if LIBAVFORMAT_VERSION_MAJOR >= 53
809 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
810 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
812 av_find_stream_info( self->audio_format );
816 self->audio_format = self->video_format;
819 else if ( self->audio_index != -1 )
821 // We only have an audio context
822 self->audio_format = self->video_format;
823 self->video_format = NULL;
825 else if ( self->video_index == -1 )
827 // Something has gone wrong
830 if ( self->audio_format && !self->audio_streams )
831 get_audio_streams_info( self );
839 self->apackets = mlt_deque_init();
840 self->vpackets = mlt_deque_init();
843 if ( self->dummy_context )
846 av_close_input_file( self->dummy_context );
848 self->dummy_context = NULL;
851 // Unlock the service
854 pthread_mutex_unlock( &self->audio_mutex );
855 pthread_mutex_unlock( &self->video_mutex );
857 mlt_events_unblock( properties, self->parent );
862 static void reopen_video( producer_avformat self, mlt_producer producer )
864 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
865 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
866 pthread_mutex_lock( &self->audio_mutex );
869 if ( self->video_codec )
870 avcodec_close( self->video_codec );
871 self->video_codec = NULL;
872 if ( self->dummy_context )
873 av_close_input_file( self->dummy_context );
874 self->dummy_context = NULL;
875 if ( self->video_format )
876 av_close_input_file( self->video_format );
877 self->video_format = NULL;
880 int audio_index = self->audio_index;
881 int video_index = self->video_index;
883 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
884 mlt_properties_get( properties, "resource" ), 0 );
886 self->audio_index = audio_index;
887 if ( self->video_format && video_index > -1 )
889 self->video_index = video_index;
890 video_codec_init( self, video_index, properties );
893 pthread_mutex_unlock( &self->audio_mutex );
894 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
897 static int seek_video( producer_avformat self, mlt_position position,
898 int64_t req_position, int must_decode, int use_new_seek, int *ignore )
900 mlt_producer producer = self->parent;
903 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
905 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
907 // Fetch the video format context
908 AVFormatContext *context = self->video_format;
910 // Get the video stream
911 AVStream *stream = context->streams[ self->video_index ];
914 AVCodecContext *codec_context = stream->codec;
916 // We may want to use the source fps if available
917 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
918 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
920 if ( self->av_frame && position + 1 == self->video_expected )
922 // We're paused - use last image
925 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
927 // Fast forward - seeking is inefficient for small distances - just ignore following frames
928 *ignore = ( int )( ( position - self->video_expected ) / mlt_producer_get_fps( producer ) * source_fps );
929 codec_context->skip_loop_filter = AVDISCARD_NONREF;
931 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
933 if ( use_new_seek && self->last_position == POSITION_INITIAL )
935 // find first key frame
940 while ( ret >= 0 && toscan-- > 0 )
942 ret = av_read_frame( context, &pkt );
943 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
945 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n", pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
946 self->first_pts = pkt.pts;
949 av_free_packet( &pkt );
952 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
955 // Calculate the timestamp for the requested frame
959 timestamp = ( req_position - 0.1 / source_fps ) /
960 ( av_q2d( stream->time_base ) * source_fps );
961 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pos %"PRId64" pts %"PRId64"\n", req_position, timestamp );
962 if ( self->first_pts > 0 )
963 timestamp += self->first_pts;
964 else if ( context->start_time != AV_NOPTS_VALUE )
965 timestamp += context->start_time;
969 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
970 if ( context->start_time != AV_NOPTS_VALUE )
971 timestamp += context->start_time;
974 timestamp -= AV_TIME_BASE;
977 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
978 timestamp, position, self->video_expected, self->last_position );
980 // Seek to the timestamp
983 codec_context->skip_loop_filter = AVDISCARD_NONREF;
984 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
986 else if ( req_position > 0 || self->last_position <= 0 )
988 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
992 // Re-open video stream when rewinding to beginning from somewhere else.
993 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
994 // not reliably seeking to the first frame across formats.
995 reopen_video( self, producer );
998 // Remove the cached info relating to the previous position
999 self->current_position = POSITION_INVALID;
1000 self->last_position = POSITION_INVALID;
1001 av_freep( &self->av_frame );
1005 // flush any pictures still in decode buffer
1006 avcodec_flush_buffers( codec_context );
1013 /** Convert a frame position to a time code.
1016 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1018 return ( double )position / mlt_producer_get_fps( producer );
1021 // Collect information about all audio streams
1023 static void get_audio_streams_info( producer_avformat self )
1025 // Fetch the audio format context
1026 AVFormatContext *context = self->audio_format;
1030 i < context->nb_streams;
1033 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1035 AVCodecContext *codec_context = context->streams[i]->codec;
1036 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1038 // If we don't have a codec and we can't initialise it, we can't do much more...
1040 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1042 self->audio_streams++;
1043 self->audio_max_stream = i;
1044 self->total_channels += codec_context->channels;
1045 if ( codec_context->channels > self->max_channel )
1046 self->max_channel = codec_context->channels;
1047 if ( codec_context->sample_rate > self->max_frequency )
1048 self->max_frequency = codec_context->sample_rate;
1049 avcodec_close( codec_context );
1054 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1055 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1057 // Other audio-specific initializations
1058 self->resample_factor = 1.0;
1061 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1063 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1065 const int *new_coefficients;
1067 int brightness, contrast, saturation;
1069 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1070 &brightness, &contrast, &saturation ) != -1 )
1072 // Don't change these from defaults unless explicitly told to.
1073 if ( use_full_range >= 0 )
1074 full_range = use_full_range;
1075 switch ( colorspace )
1081 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1084 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1087 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1090 new_coefficients = coefficients;
1093 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1094 brightness, contrast, saturation );
1099 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
1100 mlt_image_format *format, int width, int height, int colorspace )
1103 int full_range = -1;
1104 int flags = SWS_BILINEAR | SWS_ACCURATE_RND;
1107 flags |= SWS_CPU_CAPS_MMX;
1110 flags |= SWS_CPU_CAPS_MMX2;
1113 if ( pix_fmt == PIX_FMT_RGB32 )
1115 *format = mlt_image_rgb24a;
1116 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1117 width, height, PIX_FMT_RGBA, flags, NULL, NULL, NULL);
1119 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1120 set_luma_transfer( context, colorspace, full_range );
1121 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1122 output.data, output.linesize);
1123 sws_freeContext( context );
1125 else if ( *format == mlt_image_yuv420p )
1127 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1128 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1130 output.data[0] = buffer;
1131 output.data[1] = buffer + width * height;
1132 output.data[2] = buffer + ( 5 * width * height ) / 4;
1133 output.linesize[0] = width;
1134 output.linesize[1] = width >> 1;
1135 output.linesize[2] = width >> 1;
1136 set_luma_transfer( context, colorspace, full_range );
1137 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1138 output.data, output.linesize);
1139 sws_freeContext( context );
1141 else if ( *format == mlt_image_rgb24 )
1143 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1144 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1146 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1147 set_luma_transfer( context, colorspace, full_range );
1148 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1149 output.data, output.linesize);
1150 sws_freeContext( context );
1152 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1154 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1155 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1157 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1158 set_luma_transfer( context, colorspace, full_range );
1159 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1160 output.data, output.linesize);
1161 sws_freeContext( context );
1165 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1166 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1168 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1169 set_luma_transfer( context, colorspace, full_range );
1170 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1171 output.data, output.linesize);
1172 sws_freeContext( context );
1175 if ( *format == mlt_image_yuv420p )
1178 pict.data[0] = buffer;
1179 pict.data[1] = buffer + width * height;
1180 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1181 pict.linesize[0] = width;
1182 pict.linesize[1] = width >> 1;
1183 pict.linesize[2] = width >> 1;
1184 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1186 else if ( *format == mlt_image_rgb24 )
1189 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1190 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1192 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
1195 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1196 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1201 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1202 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1207 /** Allocate the image buffer and set it on the frame.
1210 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1214 if ( codec_context->width == 0 || codec_context->height == 0 )
1217 *width = codec_context->width;
1218 *height = codec_context->height;
1220 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
1221 size = *width * ( *height + 1 ) * 4;
1223 size = mlt_image_format_size( *format, *width, *height, NULL );
1225 // Construct the output image
1226 *buffer = mlt_pool_alloc( size );
1228 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1235 /** Get an image from a frame.
1238 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1241 producer_avformat self = mlt_frame_pop_service( frame );
1242 mlt_producer producer = self->parent;
1244 // Get the properties from the frame
1245 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1247 // Obtain the frame number of this frame
1248 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1250 // Get the producer properties
1251 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1253 pthread_mutex_lock( &self->video_mutex );
1255 // Fetch the video format context
1256 AVFormatContext *context = self->video_format;
1258 // Get the video stream
1259 AVStream *stream = context->streams[ self->video_index ];
1261 // Get codec context
1262 AVCodecContext *codec_context = stream->codec;
1264 // Get the image cache
1265 if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1266 self->image_cache = mlt_cache_init();
1267 if ( self->image_cache )
1269 mlt_cache_item item = mlt_cache_get( self->image_cache, (void*) position );
1270 uint8_t *original = mlt_cache_item_data( item, (int*) format );
1273 // Set the resolution
1274 *width = codec_context->width;
1275 *height = codec_context->height;
1277 // Workaround 1088 encodings missing cropping info.
1278 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1282 int size = mlt_image_format_size( *format, *width, *height, NULL );
1285 *buffer = mlt_pool_alloc( size );
1286 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1287 memcpy( *buffer, original, size );
1288 mlt_cache_item_close( item );
1293 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1294 mlt_frame_set_image( frame, *buffer, size, NULL );
1296 self->got_picture = 1;
1298 goto exit_get_image;
1307 // Special case ffwd handling
1310 // We may want to use the source fps if available
1311 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1312 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1314 // This is the physical frame position in the source
1315 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1317 // Determines if we have to decode all frames in a sequence
1318 // Temporary hack to improve intra frame only
1319 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1320 strcmp( codec_context->codec->name, "dnxhd" ) &&
1321 strcmp( codec_context->codec->name, "dvvideo" ) &&
1322 strcmp( codec_context->codec->name, "huffyuv" ) &&
1323 strcmp( codec_context->codec->name, "mjpeg" ) &&
1324 strcmp( codec_context->codec->name, "rawvideo" ) );
1326 // Turn on usage of new seek API and PTS for seeking
1327 int use_new_seek = self->seekable &&
1328 codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1329 if ( mlt_properties_get( properties, "new_seek" ) )
1330 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1332 // Seek if necessary
1333 int paused = seek_video( self, position, req_position, must_decode, use_new_seek, &ignore );
1335 // Seek might have reopened the file
1336 context = self->video_format;
1337 stream = context->streams[ self->video_index ];
1338 codec_context = stream->codec;
1340 // Duplicate the last image if necessary
1341 if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture
1343 || self->current_position == req_position
1344 || ( !use_new_seek && self->current_position > req_position ) ) )
1347 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1349 // Workaround 1088 encodings missing cropping info.
1350 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1353 if ( self->vdpau && self->vdpau->buffer )
1356 picture.data[0] = self->vdpau->buffer;
1357 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1358 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1359 picture.linesize[0] = codec_context->width;
1360 picture.linesize[1] = codec_context->width / 2;
1361 picture.linesize[2] = codec_context->width / 2;
1362 convert_image( (AVFrame*) &picture, *buffer,
1363 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1367 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1368 format, *width, *height, self->colorspace );
1371 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1376 int64_t int_position = 0;
1377 int decode_errors = 0;
1378 int got_picture = 0;
1380 av_init_packet( &pkt );
1382 // Construct an AVFrame for YUV422 conversion
1383 if ( !self->av_frame )
1384 self->av_frame = avcodec_alloc_frame( );
1386 while( ret >= 0 && !got_picture )
1389 pthread_mutex_lock( &self->packets_mutex );
1390 if ( mlt_deque_count( self->vpackets ) )
1392 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1398 ret = av_read_frame( context, &pkt );
1399 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->audio_index )
1401 if ( !av_dup_packet( &pkt ) )
1403 AVPacket *tmp = malloc( sizeof(AVPacket) );
1405 mlt_deque_push_back( self->apackets, tmp );
1409 pthread_mutex_unlock( &self->packets_mutex );
1411 // We only deal with video from the selected video_index
1412 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1414 // Determine time code of the packet
1417 int64_t pts = pkt.pts;
1418 if ( self->first_pts > 0 )
1419 pts -= self->first_pts;
1420 else if ( context->start_time != AV_NOPTS_VALUE )
1421 pts -= context->start_time;
1422 int_position = ( int64_t )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1423 if ( pkt.pts == AV_NOPTS_VALUE )
1425 self->invalid_pts_counter++;
1426 if ( self->invalid_pts_counter > 20 )
1428 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1429 mlt_properties_set_int( properties, "new_seek", 0 );
1430 int_position = req_position;
1436 self->invalid_pts_counter = 0;
1438 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1439 pkt.pts, req_position, self->current_position, int_position );
1443 if ( pkt.dts != AV_NOPTS_VALUE )
1445 double delay = mlt_properties_get_double( properties, "video_delay" );
1446 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pkt.dts + delay ) * source_fps + 0.5 );
1447 if ( context->start_time != AV_NOPTS_VALUE )
1448 int_position -= ( int64_t )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1449 if ( int_position == self->last_position )
1450 int_position = self->last_position + 1;
1452 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1453 pkt.dts, req_position, self->current_position, int_position );
1454 // Make a dumb assumption on streams that contain wild timestamps
1455 if ( abs( req_position - int_position ) > 999 )
1457 int_position = req_position;
1458 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1461 self->last_position = int_position;
1464 if ( must_decode || int_position >= req_position )
1467 if ( g_vdpau && self->vdpau )
1469 if ( g_vdpau->producer != self )
1471 vdpau_decoder_close();
1472 vdpau_decoder_init( self );
1475 self->vdpau->is_decoded = 0;
1478 codec_context->reordered_opaque = pkt.pts;
1479 if ( int_position >= req_position )
1480 codec_context->skip_loop_filter = AVDISCARD_NONE;
1481 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1482 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1484 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1486 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1489 if ( ++decode_errors <= 10 )
1502 // Determine time code of the packet
1503 int64_t pts = self->av_frame->reordered_opaque;
1504 if ( self->first_pts > 0 )
1505 pts -= self->first_pts;
1506 else if ( context->start_time != AV_NOPTS_VALUE )
1507 pts -= context->start_time;
1508 int_position = ( int64_t )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1509 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %"PRId64", key %d\n", int_position, self->av_frame->key_frame );
1512 if ( int_position < req_position )
1517 else if ( int_position >= req_position )
1520 codec_context->skip_loop_filter = AVDISCARD_NONE;
1522 else if ( ignore -- )
1527 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1530 // Now handle the picture if we have one
1533 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1535 // Workaround 1088 encodings missing cropping info.
1536 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1541 if ( self->vdpau->is_decoded )
1543 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1545 uint32_t pitches[3];
1546 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1548 if ( !self->vdpau->buffer )
1549 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1550 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1551 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1552 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1553 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1554 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1555 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1557 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1558 if ( status == VDP_STATUS_OK )
1560 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1561 format, *width, *height, self->colorspace );
1565 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1566 image_size = self->vdpau->is_decoded = 0;
1571 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1572 image_size = got_picture = 0;
1577 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1578 format, *width, *height, self->colorspace );
1579 self->top_field_first |= self->av_frame->top_field_first;
1580 self->current_position = int_position;
1581 self->got_picture = 1;
1588 if ( self->seekable || pkt.stream_index != self->audio_index )
1589 av_free_packet( &pkt );
1593 if ( self->got_picture && image_size > 0 && self->image_cache )
1595 // Copy buffer to image cache
1596 uint8_t *image = mlt_pool_alloc( image_size );
1597 memcpy( image, *buffer, image_size );
1598 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1600 // Try to duplicate last image if there was a decoding failure
1601 else if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1604 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1606 // Workaround 1088 encodings missing cropping info.
1607 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1610 if ( self->vdpau && self->vdpau->buffer )
1613 picture.data[0] = self->vdpau->buffer;
1614 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1615 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1616 picture.linesize[0] = codec_context->width;
1617 picture.linesize[1] = codec_context->width / 2;
1618 picture.linesize[2] = codec_context->width / 2;
1619 convert_image( (AVFrame*) &picture, *buffer,
1620 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1624 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1625 format, *width, *height, self->colorspace );
1626 self->got_picture = 1;
1629 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1632 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1633 self->video_expected = position + 1;
1637 pthread_mutex_unlock( &self->video_mutex );
1639 // Set the progressive flag
1640 if ( mlt_properties_get( properties, "force_progressive" ) )
1641 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1642 else if ( self->av_frame )
1643 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1645 // Set the field order property for this frame
1646 if ( mlt_properties_get( properties, "force_tff" ) )
1647 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1649 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1651 // Set immutable properties of the selected track's (or overridden) source attributes.
1652 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1653 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1654 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1655 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1657 return !self->got_picture;
1660 /** Process properties as AVOptions and apply to AV context obj
1663 static void apply_properties( void *obj, mlt_properties properties, int flags )
1666 int count = mlt_properties_count( properties );
1667 for ( i = 0; i < count; i++ )
1669 const char *opt_name = mlt_properties_get_name( properties, i );
1670 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1671 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1674 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1675 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1676 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1677 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1679 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1685 /** Initialize the video codec context.
1688 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1690 // Initialise the codec if necessary
1691 if ( !self->video_codec )
1693 // Get the video stream
1694 AVStream *stream = self->video_format->streams[ index ];
1696 // Get codec context
1697 AVCodecContext *codec_context = stream->codec;
1700 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1702 if ( codec_context->codec_id == CODEC_ID_H264 )
1704 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1706 if ( vdpau_init( self ) )
1708 self->video_codec = codec_context;
1709 if ( !vdpau_decoder_init( self ) )
1710 vdpau_decoder_close();
1714 codec = avcodec_find_decoder( codec_context->codec_id );
1718 // Initialise multi-threading
1719 int thread_count = mlt_properties_get_int( properties, "threads" );
1720 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1721 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1722 if ( thread_count > 1 )
1723 codec_context->thread_count = thread_count;
1725 // If we don't have a codec and we can't initialise it, we can't do much more...
1727 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1729 // Now store the codec with its destructor
1730 self->video_codec = codec_context;
1734 // Remember that we can't use this later
1735 self->video_index = -1;
1741 // Process properties as AVOptions
1742 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1743 #if LIBAVCODEC_VERSION_MAJOR >= 53
1744 if ( codec->priv_class && codec_context->priv_data )
1745 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1748 // Reset some image properties
1749 mlt_properties_set_int( properties, "width", self->video_codec->width );
1750 mlt_properties_set_int( properties, "height", self->video_codec->height );
1751 // For DV, we'll just use the saved aspect ratio
1752 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1753 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1755 // Determine the fps first from the codec
1756 double source_fps = (double) self->video_codec->time_base.den /
1757 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1759 if ( mlt_properties_get( properties, "force_fps" ) )
1761 source_fps = mlt_properties_get_double( properties, "force_fps" );
1762 stream->time_base = av_d2q( source_fps, 1024 );
1763 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1764 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1768 // If the muxer reports a frame rate different than the codec
1769 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1770 double muxer_fps = av_q2d( stream->avg_frame_rate );
1771 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1772 muxer_fps = av_q2d( stream->r_frame_rate );
1774 double muxer_fps = av_q2d( stream->r_frame_rate );
1776 // Choose the lesser - the wrong tends to be off by some multiple of 10
1777 source_fps = FFMIN( source_fps, muxer_fps );
1778 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1780 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1781 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1783 else if ( muxer_fps > 0 )
1785 AVRational frame_rate = stream->r_frame_rate;
1786 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1787 // avg_frame_rate gives some approximate value that does not well match the media.
1788 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1789 // results in some very choppy output, but some value slightly different works
1791 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1792 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1793 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1795 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1796 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1800 source_fps = mlt_producer_get_fps( self->parent );
1801 AVRational frame_rate = av_d2q( source_fps, 255 );
1802 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1803 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1807 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1808 if ( source_fps > 0 )
1809 mlt_properties_set_double( properties, "source_fps", source_fps );
1811 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
1813 // Set the YUV colorspace from override or detect
1814 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1815 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1816 if ( ! self->colorspace )
1818 switch ( self->video_codec->colorspace )
1820 case AVCOL_SPC_SMPTE240M:
1821 self->colorspace = 240;
1823 case AVCOL_SPC_BT470BG:
1824 case AVCOL_SPC_SMPTE170M:
1825 self->colorspace = 601;
1827 case AVCOL_SPC_BT709:
1828 self->colorspace = 709;
1831 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1832 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1837 // Let apps get chosen colorspace
1838 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1840 return self->video_codec && self->video_index > -1;
1843 /** Set up video handling.
1846 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1849 mlt_producer producer = self->parent;
1851 // Get the properties
1852 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1854 // Fetch the video format context
1855 AVFormatContext *context = self->video_format;
1857 // Get the video_index
1858 int index = mlt_properties_get_int( properties, "video_index" );
1860 // Reopen the file if necessary
1861 if ( !context && index > -1 )
1863 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1864 mlt_properties_get( properties, "resource" ), 1 );
1865 context = self->video_format;
1868 // Exception handling for video_index
1869 if ( context && index >= (int) context->nb_streams )
1871 // Get the last video stream
1872 for ( index = context->nb_streams - 1;
1873 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1875 mlt_properties_set_int( properties, "video_index", index );
1877 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1879 // Invalidate the video stream
1881 mlt_properties_set_int( properties, "video_index", index );
1884 // Update the video properties if the index changed
1885 if ( index != self->video_index )
1887 // Reset the video properties if the index changed
1888 self->video_index = index;
1890 if ( self->video_codec )
1891 avcodec_close( self->video_codec );
1892 self->video_codec = NULL;
1896 // Get the frame properties
1897 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1900 if ( context && index > -1 && video_codec_init( self, index, properties ) )
1902 // Set the frame properties
1903 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1904 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1905 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1907 // Set the width and height
1908 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
1909 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
1910 // real_width and real_height are deprecated in favor of meta.media.width and .height
1911 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
1912 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
1913 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
1914 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
1915 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1916 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
1918 // Workaround 1088 encodings missing cropping info.
1919 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1921 mlt_properties_set_int( properties, "meta.media.height", 1080 );
1922 mlt_properties_set_int( frame_properties, "real_height", 1080 );
1925 // Add our image operation
1926 mlt_frame_push_service( frame, self );
1927 mlt_frame_push_get_image( frame, producer_get_image );
1931 // If something failed, use test card image
1932 mlt_properties_set_int( frame_properties, "test_image", 1 );
1936 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
1940 // Seek if necessary
1941 if ( self->seekable && position != self->audio_expected )
1943 if ( position + 1 == self->audio_expected )
1945 // We're paused - silence required
1948 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
1950 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1951 *ignore = position - self->audio_expected;
1953 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
1955 AVFormatContext *context = self->audio_format;
1956 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1957 if ( context->start_time != AV_NOPTS_VALUE )
1958 timestamp += context->start_time;
1959 if ( timestamp < 0 )
1962 // Set to the real timecode
1963 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1966 // Clear the usage in the audio buffer
1967 int i = MAX_AUDIO_STREAMS + 1;
1969 self->audio_used[i - 1] = 0;
1975 static int sample_bytes( AVCodecContext *context )
1977 #if LIBAVCODEC_VERSION_MAJOR >= 53
1978 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
1980 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
1984 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
1986 // Fetch the audio_format
1987 AVFormatContext *context = self->audio_format;
1989 // Get the current stream index
1990 int index = pkt.stream_index;
1992 // Get codec context
1993 AVCodecContext *codec_context = self->audio_codec[ index ];
1995 // Obtain the resample context if it exists (not always needed)
1996 ReSampleContext *resample = self->audio_resample[ index ];
1998 // Obtain the audio buffers
1999 uint8_t *audio_buffer = self->audio_buffer[ index ];
2000 uint8_t *decode_buffer = self->decode_buffer[ index ];
2002 int audio_used = self->audio_used[ index ];
2003 uint8_t *ptr = pkt.data;
2007 while ( ptr && ret >= 0 && len > 0 )
2009 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2010 int data_size = self->audio_buffer_size[ index ];
2013 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2014 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2015 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2016 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2018 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2022 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2026 pkt.size = len -= ret;
2027 pkt.data = ptr += ret;
2029 // If decoded successfully
2030 if ( data_size > 0 )
2032 // Figure out how many samples will be needed after resampling
2033 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2034 int samples_needed = self->resample_factor * convert_samples;
2036 // Resize audio buffer to prevent overflow
2037 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2039 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2040 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2044 // Copy to audio buffer while resampling
2045 uint8_t *source = decode_buffer;
2046 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2047 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2051 // Straight copy to audio buffer
2052 memcpy( &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ], decode_buffer, data_size );
2053 audio_used += convert_samples;
2057 while ( *ignore && audio_used )
2060 audio_used -= audio_used > samples ? samples : audio_used;
2061 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2062 audio_used * sizeof_sample );
2067 // If we're behind, ignore this packet
2068 // Skip this on non-seekable, audio-only inputs.
2069 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2071 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
2072 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2073 int64_t int_position = ( int64_t )( current_pts * fps + 0.5 );
2074 if ( context->start_time != AV_NOPTS_VALUE )
2075 int_position -= ( int64_t )( fps * context->start_time / AV_TIME_BASE + 0.5 );
2077 if ( int_position > 0 )
2079 if ( int_position < req_position )
2080 // We are behind, so skip some
2081 *ignore = req_position - int_position;
2082 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2083 // We are ahead, so seek backwards some more
2084 seek_audio( self, req_position, timecode - 1.0, ignore );
2088 self->audio_used[ index ] = audio_used;
2093 /** Get the audio from a frame.
2095 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2098 producer_avformat self = mlt_frame_pop_audio( frame );
2100 pthread_mutex_lock( &self->audio_mutex );
2102 // Obtain the frame number of this frame
2103 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
2105 // Calculate the real time code
2106 double real_timecode = producer_time_of_frame( self->parent, position );
2108 // Get the producer fps
2109 double fps = mlt_producer_get_fps( self->parent );
2111 // Number of frames to ignore (for ffwd)
2112 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2114 // Flag for paused (silence)
2115 int paused = seek_audio( self, position, real_timecode, &ignore[0] );
2117 // Initialize ignore for all streams from the seek return value
2118 int i = MAX_AUDIO_STREAMS;
2120 ignore[i] = ignore[0];
2122 // Fetch the audio_format
2123 AVFormatContext *context = self->audio_format;
2125 int sizeof_sample = sizeof( int16_t );
2127 // Determine the tracks to use
2128 int index = self->audio_index;
2129 int index_max = self->audio_index + 1;
2130 if ( self->audio_index == INT_MAX )
2133 index_max = context->nb_streams;
2134 *channels = self->total_channels;
2135 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2136 *frequency = FFMAX( self->max_frequency, *frequency );
2139 // Initialize the resamplers and buffers
2140 for ( ; index < index_max; index++ )
2142 // Get codec context
2143 AVCodecContext *codec_context = self->audio_codec[ index ];
2145 if ( codec_context && !self->audio_buffer[ index ] )
2147 // Check for resample and create if necessary
2148 if ( codec_context->channels <= 2 )
2150 // Determine by how much resampling will increase number of samples
2151 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2152 resample_factor *= (double) *frequency / codec_context->sample_rate;
2153 if ( resample_factor > self->resample_factor )
2154 self->resample_factor = resample_factor;
2156 // Create the resampler
2157 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2158 self->audio_resample[ index ] = av_audio_resample_init(
2159 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2160 codec_context->channels, *frequency, codec_context->sample_rate,
2161 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2163 self->audio_resample[ index ] = audio_resample_init(
2164 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2165 codec_context->channels, *frequency, codec_context->sample_rate );
2170 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2171 sizeof_sample = sample_bytes( codec_context );
2174 // Check for audio buffer and create if necessary
2175 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2176 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2178 // Check for decoder buffer and create if necessary
2179 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2183 // Get the audio if required
2190 av_init_packet( &pkt );
2192 // If not resampling, give consumer more than requested.
2193 // It requested number samples based on requested frame rate.
2194 // Do not clean this up with a samples *= ...!
2195 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2196 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2198 while ( ret >= 0 && !got_audio )
2200 // Check if the buffer already contains the samples required
2201 if ( self->audio_index != INT_MAX &&
2202 self->audio_used[ self->audio_index ] >= *samples &&
2203 ignore[ self->audio_index ] == 0 )
2208 else if ( self->audio_index == INT_MAX )
2210 // Check if there is enough audio for all streams
2212 for ( index = 0; got_audio && index < context->nb_streams; index++ )
2213 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2220 pthread_mutex_lock( &self->packets_mutex );
2221 if ( mlt_deque_count( self->apackets ) )
2223 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2229 ret = av_read_frame( context, &pkt );
2230 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2232 if ( !av_dup_packet( &pkt ) )
2234 AVPacket *tmp = malloc( sizeof(AVPacket) );
2236 mlt_deque_push_back( self->vpackets, tmp );
2240 pthread_mutex_unlock( &self->packets_mutex );
2242 // We only deal with audio from the selected audio index
2243 index = pkt.stream_index;
2244 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2245 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2247 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2248 self->audio_codec[index]->channels : *channels;
2249 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2252 if ( self->seekable || index != self->video_index )
2253 av_free_packet( &pkt );
2257 // Set some additional return values
2258 *format = mlt_audio_s16;
2259 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2261 index = self->audio_index;
2262 *channels = self->audio_codec[ index ]->channels;
2263 *frequency = self->audio_codec[ index ]->sample_rate;
2264 *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2265 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2267 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2269 else if ( self->audio_index == INT_MAX )
2271 // This only works if all audio tracks have the same sample format.
2272 for ( index = 0; index < index_max; index++ )
2273 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2275 *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2276 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2278 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2283 // Allocate and set the frame's audio buffer
2284 int size = mlt_audio_format_size( *format, *samples, *channels );
2285 *buffer = mlt_pool_alloc( size );
2286 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2288 // Interleave tracks if audio_index=all
2289 if ( self->audio_index == INT_MAX )
2291 uint8_t *dest = *buffer;
2293 for ( i = 0; i < *samples; i++ )
2295 for ( index = 0; index < index_max; index++ )
2296 if ( self->audio_codec[ index ] )
2298 int current_channels = self->audio_codec[ index ]->channels;
2299 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2300 memcpy( dest, src, current_channels * sizeof_sample );
2301 dest += current_channels * sizeof_sample;
2304 for ( index = 0; index < index_max; index++ )
2305 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2307 int current_channels = self->audio_codec[ index ]->channels;
2308 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2309 self->audio_used[index] -= *samples;
2310 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2313 // Copy a single track to the output buffer
2316 index = self->audio_index;
2318 // Now handle the audio if we have enough
2319 if ( self->audio_used[ index ] > 0 )
2321 uint8_t *src = self->audio_buffer[ index ];
2322 // copy samples from audio_buffer
2323 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2324 memcpy( *buffer, src, size * *channels * sizeof_sample );
2325 // supply the remaining requested samples as silence
2326 if ( *samples > self->audio_used[ index ] )
2327 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2328 // reposition the samples within audio_buffer
2329 self->audio_used[ index ] -= size;
2330 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2334 // Otherwise fill with silence
2335 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2341 // Get silence and don't touch the context
2342 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2345 // Regardless of speed (other than paused), we expect to get the next frame
2347 self->audio_expected = position + 1;
2349 pthread_mutex_unlock( &self->audio_mutex );
2354 /** Initialize the audio codec context.
2357 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2359 // Initialise the codec if necessary
2360 if ( !self->audio_codec[ index ] )
2362 // Get codec context
2363 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2366 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2368 // If we don't have a codec and we can't initialise it, we can't do much more...
2370 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2372 // Now store the codec with its destructor
2373 if ( self->audio_codec[ index ] )
2374 avcodec_close( self->audio_codec[ index ] );
2375 self->audio_codec[ index ] = codec_context;
2379 // Remember that we can't use self later
2380 self->audio_index = -1;
2384 // Process properties as AVOptions
2385 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2386 #if LIBAVCODEC_VERSION_MAJOR >= 53
2387 if ( codec && codec->priv_class && codec_context->priv_data )
2388 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2391 return self->audio_codec[ index ] && self->audio_index > -1;
2394 /** Set up audio handling.
2397 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2400 mlt_producer producer = self->parent;
2402 // Get the properties
2403 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2405 // Fetch the audio format context
2406 AVFormatContext *context = self->audio_format;
2408 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2410 // Get the audio_index
2411 int index = mlt_properties_get_int( properties, "audio_index" );
2413 // Handle all audio tracks
2414 if ( self->audio_index > -1 &&
2415 mlt_properties_get( properties, "audio_index" ) &&
2416 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2419 // Reopen the file if necessary
2420 if ( !context && self->audio_index > -1 && index > -1 )
2422 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2423 mlt_properties_get( properties, "resource" ), 1 );
2424 context = self->audio_format;
2427 // Exception handling for audio_index
2428 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2430 for ( index = context->nb_streams - 1;
2431 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2433 mlt_properties_set_int( properties, "audio_index", index );
2435 if ( context && index > -1 && index < INT_MAX &&
2436 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2438 index = self->audio_index;
2439 mlt_properties_set_int( properties, "audio_index", index );
2442 // Update the audio properties if the index changed
2443 if ( context && index > -1 && index != self->audio_index )
2446 if ( self->audio_codec[ self->audio_index ] )
2447 avcodec_close( self->audio_codec[ self->audio_index ] );
2448 self->audio_codec[ self->audio_index ] = NULL;
2451 if ( self->audio_index != -1 )
2452 self->audio_index = index;
2457 if ( context && index == INT_MAX )
2459 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2460 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2461 for ( index = 0; index < context->nb_streams; index++ )
2463 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2464 audio_codec_init( self, index, properties );
2467 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2469 // Set the frame properties
2470 if ( index < INT_MAX )
2472 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2473 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2476 if ( context && index > -1 )
2478 // Add our audio operation
2479 mlt_frame_push_audio( frame, self );
2480 mlt_frame_push_audio( frame, producer_get_audio );
2484 /** Our get frame implementation.
2487 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2489 // Access the private data
2490 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2491 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2492 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2497 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2498 producer->child = self;
2499 self->parent = producer;
2500 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2501 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2504 // Create an empty frame
2505 *frame = mlt_frame_init( service);
2509 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2513 mlt_cache_item_close( cache_item );
2517 // Update timecode on the frame we're creating
2518 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2521 producer_set_up_video( self, *frame );
2524 producer_set_up_audio( self, *frame );
2526 // Set the position of this producer
2527 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2528 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", position );
2530 // Calculate the next timecode
2531 mlt_producer_prepare_next( producer );
2536 static void producer_avformat_close( producer_avformat self )
2538 mlt_log_debug( NULL, "producer_avformat_close\n" );
2540 // Cleanup av contexts
2541 av_free( self->av_frame );
2544 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2546 if ( self->audio_resample[i] )
2547 audio_resample_close( self->audio_resample[i] );
2548 mlt_pool_release( self->audio_buffer[i] );
2549 av_free( self->decode_buffer[i] );
2550 if ( self->audio_codec[i] )
2551 avcodec_close( self->audio_codec[i] );
2552 self->audio_codec[i] = NULL;
2554 if ( self->video_codec )
2555 avcodec_close( self->video_codec );
2556 self->video_codec = NULL;
2558 if ( self->dummy_context )
2559 av_close_input_file( self->dummy_context );
2560 if ( self->seekable && self->audio_format )
2561 av_close_input_file( self->audio_format );
2562 if ( self->video_format )
2563 av_close_input_file( self->video_format );
2566 vdpau_producer_close( self );
2568 if ( self->image_cache )
2569 mlt_cache_close( self->image_cache );
2571 // Cleanup the mutexes
2572 pthread_mutex_destroy( &self->audio_mutex );
2573 pthread_mutex_destroy( &self->video_mutex );
2574 pthread_mutex_destroy( &self->packets_mutex );
2576 // Cleanup the packet queues
2578 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2580 av_free_packet( pkt );
2583 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2585 av_free_packet( pkt );
2592 static void producer_close( mlt_producer parent )
2594 // Remove this instance from the cache
2595 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2598 parent->close = NULL;
2599 mlt_producer_close( parent );