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;
116 pthread_mutex_t packets_mutex;
121 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
132 typedef struct producer_avformat_s *producer_avformat;
134 // Forward references.
135 static int list_components( char* file );
136 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL );
137 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
138 static void producer_avformat_close( producer_avformat );
139 static void producer_close( mlt_producer parent );
140 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
141 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
142 static void apply_properties( void *obj, mlt_properties properties, int flags );
143 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
144 static void get_audio_streams_info( producer_avformat self );
150 /** Constructor for libavformat.
153 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
155 if ( list_components( file ) )
158 mlt_producer producer = NULL;
160 // Check that we have a non-NULL argument
163 // Construct the producer
164 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
165 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
168 if ( mlt_producer_init( producer, self ) == 0 )
170 self->parent = producer;
172 // Get the properties
173 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
175 // Set the resource property (required for all producers)
176 mlt_properties_set( properties, "resource", file );
178 // Register transport implementation with the producer
179 producer->close = (mlt_destructor) producer_close;
181 // Register our get_frame implementation
182 producer->get_frame = producer_get_frame;
184 if ( strcmp( service, "avformat-novalidate" ) )
187 if ( producer_open( self, profile, file ) != 0 )
190 mlt_producer_close( producer );
193 else if ( self->seekable )
195 // Close the file to release resources for large playlists - reopen later as needed
197 if ( self->audio_format )
198 av_close_input_file( self->audio_format );
199 self->audio_format = NULL;
200 if ( self->video_format )
201 av_close_input_file( self->video_format );
202 self->video_format = NULL;
208 // Default the user-selectable indices from the auto-detected indices
209 mlt_properties_set_int( properties, "audio_index", self->audio_index );
210 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 *params )
546 if ( !URL ) return NULL;
548 const char *result = URL;
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
561 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
564 *format = av_find_input_format( protocol );
566 // Eat the format designator
571 // These are required by video4linux2 (defaults)
572 params->width = profile->width;
573 params->height = profile->height;
574 params->time_base= (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
575 params->channels = 2;
576 params->sample_rate = 48000;
579 url = strchr( url, '?' );
583 char *name = strdup( ++url );
584 char *value = strchr( name, ':' );
589 char *t = strchr( value, '&' );
592 if ( !strcmp( name, "frame_rate" ) )
593 params->time_base.den = atoi( value );
594 else if ( !strcmp( name, "frame_rate_base" ) )
595 params->time_base.num = atoi( value );
596 else if ( !strcmp( name, "sample_rate" ) )
597 params->sample_rate = atoi( value );
598 else if ( !strcmp( name, "channel" ) )
599 params->channel = atoi( value );
600 else if ( !strcmp( name, "channels" ) )
601 params->channels = atoi( value );
602 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
603 else if ( !strcmp( name, "pix_fmt" ) )
604 params->pix_fmt = av_get_pix_fmt( value );
606 else if ( !strcmp( name, "width" ) )
607 params->width = atoi( value );
608 else if ( !strcmp( name, "height" ) )
609 params->height = atoi( value );
610 else if ( !strcmp( name, "standard" ) )
611 params->standard = strdup( value );
614 url = strchr( url, '&' );
619 return strdup( result );
622 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
626 // Get the properties
627 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
629 AVFormatContext *format = self->video_format;
631 // We will treat everything with the producer fps.
632 // TODO: make this more flexible.
633 double fps = mlt_profile_fps( profile );
636 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
638 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
639 // when producer_open is called after initial call when restoring or reseting the producer.
640 if ( format->duration != AV_NOPTS_VALUE )
642 // This isn't going to be accurate for all formats
643 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
644 mlt_properties_set_position( properties, "out", frames - 1 );
645 mlt_properties_set_position( properties, "length", frames );
646 mlt_properties_set_int( properties, "_length_computed", 1 );
650 // Set live sources to run forever
651 mlt_properties_set_position( properties, "length", INT_MAX );
652 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
653 mlt_properties_set( properties, "eof", "loop" );
654 mlt_properties_set_int( properties, "_length_computed", 1 );
658 if ( format->start_time != AV_NOPTS_VALUE )
659 self->start_time = format->start_time;
661 // Check if we're seekable
662 // avdevices are typically AVFMT_NOFILE and not seekable
663 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
666 // protocols can indicate if they support seeking
667 #if LIBAVFORMAT_VERSION_MAJOR > 52
668 self->seekable = context->pb->seekable;
670 URLContext *uc = url_fileno( format->pb );
672 self->seekable = !uc->is_streamed;
675 if ( self->seekable )
677 // Do a more rigourous test of seekable on a disposable context
678 self->seekable = av_seek_frame( format, -1, self->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
679 mlt_properties_set_int( properties, "seekable", self->seekable );
680 self->dummy_context = format;
681 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
682 format = self->video_format;
683 av_find_stream_info( format );
686 // Fetch the width, height and aspect ratio
687 if ( self->video_index != -1 )
689 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
690 mlt_properties_set_int( properties, "width", codec_context->width );
691 mlt_properties_set_int( properties, "height", codec_context->height );
693 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
695 // Fetch the first frame of DV so we can read it directly
700 ret = av_read_frame( format, &pkt );
701 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
703 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
710 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
714 // Verify that we can convert this to YUV 4:2:2
715 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
716 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
717 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
719 sws_freeContext( context );
730 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL )
732 // Return an error code (0 == no error)
734 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
737 pthread_mutex_init( &self->audio_mutex, NULL );
738 pthread_mutex_init( &self->video_mutex, NULL );
739 pthread_mutex_init( &self->packets_mutex, NULL );
740 mlt_events_block( properties, self->parent );
741 pthread_mutex_lock( &self->audio_mutex );
742 pthread_mutex_lock( &self->video_mutex );
745 AVInputFormat *format = NULL;
746 AVFormatParameters params;
747 memset( ¶ms, 0, sizeof(params) );
748 char *filename = parse_url( profile, URL, &format, ¶ms );
750 // Now attempt to open the file or device with filename
751 #if LIBAVFORMAT_VERSION_MAJOR > 52
752 self->video_format->flags |= AVFMT_FLAG_PRIV_OPT;
754 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
756 // If the URL is a network stream URL, then we probably need to open with full URL
757 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
759 // Set MLT properties onto video AVFormatContext
760 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
761 #if LIBAVFORMAT_VERSION_MAJOR > 52
762 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
763 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
764 av_demuxer_open( self->video_format, ¶ms );
767 // Cleanup AVFormatParameters
768 if ( params.standard )
769 free( (void*) params.standard );
771 // If successful, then try to get additional info
774 // Get the stream info
775 error = av_find_stream_info( self->video_format ) < 0;
777 // Continue if no error
780 // Find default audio and video streams
781 find_default_streams( self );
782 error = get_basic_info( self, profile, filename );
784 // Initialize position info
785 self->first_pts = -1;
786 self->last_position = POSITION_INITIAL;
788 // We're going to cheat here - for seekable A/V files, we will have separate contexts
789 // to support independent seeking of audio from video.
790 // TODO: Is this really necessary?
791 if ( self->audio_index != -1 && self->video_index != -1 )
793 if ( self->seekable )
795 // And open again for our audio context
796 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
797 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
798 #if LIBAVFORMAT_VERSION_MAJOR > 52
799 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
800 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
802 av_find_stream_info( self->audio_format );
806 self->audio_format = self->video_format;
809 else if ( self->audio_index != -1 )
811 // We only have an audio context
812 self->audio_format = self->video_format;
813 self->video_format = NULL;
815 else if ( self->video_index == -1 )
817 // Something has gone wrong
820 if ( self->audio_format && !self->audio_streams )
821 get_audio_streams_info( self );
828 self->apackets = mlt_deque_init();
829 self->vpackets = mlt_deque_init();
832 if ( self->dummy_context )
834 av_close_input_file( self->dummy_context );
835 self->dummy_context = NULL;
838 // Unlock the service
839 pthread_mutex_unlock( &self->audio_mutex );
840 pthread_mutex_unlock( &self->video_mutex );
841 mlt_events_unblock( properties, self->parent );
846 static void reopen_video( producer_avformat self, mlt_producer producer )
848 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
849 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
850 pthread_mutex_lock( &self->audio_mutex );
852 if ( self->video_codec )
855 avcodec_close( self->video_codec );
858 self->video_codec = NULL;
859 if ( self->dummy_context )
860 av_close_input_file( self->dummy_context );
861 self->dummy_context = NULL;
862 if ( self->video_format )
863 av_close_input_file( self->video_format );
864 self->video_format = NULL;
866 int audio_index = self->audio_index;
867 int video_index = self->video_index;
869 pthread_mutex_unlock( &self->audio_mutex );
870 pthread_mutex_unlock( &self->video_mutex );
871 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
872 mlt_properties_get( properties, "resource" ) );
873 pthread_mutex_lock( &self->video_mutex );
874 pthread_mutex_lock( &self->audio_mutex );
876 self->audio_index = audio_index;
877 if ( self->video_format && video_index > -1 )
879 self->video_index = video_index;
880 video_codec_init( self, video_index, properties );
883 pthread_mutex_unlock( &self->audio_mutex );
884 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
887 static int seek_video( producer_avformat self, mlt_position position,
888 int req_position, int must_decode, int use_new_seek, int *ignore )
890 mlt_producer producer = self->parent;
893 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
895 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
897 // Fetch the video format context
898 AVFormatContext *context = self->video_format;
900 // Get the video stream
901 AVStream *stream = context->streams[ self->video_index ];
904 AVCodecContext *codec_context = stream->codec;
906 // We may want to use the source fps if available
907 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
908 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
910 if ( self->av_frame && position + 1 == self->video_expected )
912 // We're paused - use last image
915 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
917 // Fast forward - seeking is inefficient for small distances - just ignore following frames
918 *ignore = ( int )( ( position - self->video_expected ) / mlt_producer_get_fps( producer ) * source_fps );
919 codec_context->skip_loop_filter = AVDISCARD_NONREF;
921 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
923 if ( use_new_seek && self->last_position == POSITION_INITIAL )
925 // find first key frame
930 while ( ret >= 0 && toscan-- > 0 )
932 ret = av_read_frame( context, &pkt );
933 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
935 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) );
936 self->first_pts = pkt.pts;
939 av_free_packet( &pkt );
942 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
945 // Calculate the timestamp for the requested frame
949 timestamp = ( req_position - 0.1 / source_fps ) /
950 ( av_q2d( stream->time_base ) * source_fps );
951 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %"PRId64" ", req_position, timestamp );
952 if ( self->first_pts > 0 )
953 timestamp += self->first_pts;
954 else if ( context->start_time != AV_NOPTS_VALUE )
955 timestamp += context->start_time;
959 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
960 if ( context->start_time != AV_NOPTS_VALUE )
961 timestamp += context->start_time;
964 timestamp -= AV_TIME_BASE;
967 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %d\n",
968 timestamp, position, self->video_expected, self->last_position );
970 // Seek to the timestamp
973 codec_context->skip_loop_filter = AVDISCARD_NONREF;
974 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
976 else if ( req_position > 0 || self->last_position <= 0 )
978 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
982 // Re-open video stream when rewinding to beginning from somewhere else.
983 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
984 // not reliably seeking to the first frame across formats.
985 reopen_video( self, producer );
988 // Remove the cached info relating to the previous position
989 self->current_position = POSITION_INVALID;
990 self->last_position = POSITION_INVALID;
991 av_freep( &self->av_frame );
995 // flush any pictures still in decode buffer
996 avcodec_flush_buffers( codec_context );
1003 /** Convert a frame position to a time code.
1006 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1008 return ( double )position / mlt_producer_get_fps( producer );
1011 // Collect information about all audio streams
1013 static void get_audio_streams_info( producer_avformat self )
1015 // Fetch the audio format context
1016 AVFormatContext *context = self->audio_format;
1020 i < context->nb_streams;
1023 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1025 AVCodecContext *codec_context = context->streams[i]->codec;
1026 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1028 // If we don't have a codec and we can't initialise it, we can't do much more...
1030 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1032 self->audio_streams++;
1033 self->audio_max_stream = i;
1034 self->total_channels += codec_context->channels;
1035 if ( codec_context->channels > self->max_channel )
1036 self->max_channel = codec_context->channels;
1037 if ( codec_context->sample_rate > self->max_frequency )
1038 self->max_frequency = codec_context->sample_rate;
1039 avcodec_close( codec_context );
1044 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1045 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1047 // Other audio-specific initializations
1048 self->resample_factor = 1.0;
1051 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1053 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1055 const int *new_coefficients;
1057 int brightness, contrast, saturation;
1059 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1060 &brightness, &contrast, &saturation ) != -1 )
1062 // Don't change these from defaults unless explicitly told to.
1063 if ( use_full_range >= 0 )
1064 full_range = use_full_range;
1065 switch ( colorspace )
1071 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1074 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1077 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1080 new_coefficients = coefficients;
1083 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1084 brightness, contrast, saturation );
1089 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
1090 mlt_image_format *format, int width, int height, int colorspace )
1093 int full_range = -1;
1094 int flags = SWS_BILINEAR | SWS_ACCURATE_RND;
1097 flags |= SWS_CPU_CAPS_MMX;
1100 flags |= SWS_CPU_CAPS_MMX2;
1103 if ( pix_fmt == PIX_FMT_RGB32 )
1105 *format = mlt_image_rgb24a;
1106 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1107 width, height, PIX_FMT_RGBA, flags, NULL, NULL, NULL);
1109 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1110 set_luma_transfer( context, colorspace, full_range );
1111 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1112 output.data, output.linesize);
1113 sws_freeContext( context );
1115 else if ( *format == mlt_image_yuv420p )
1117 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1118 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1120 output.data[0] = buffer;
1121 output.data[1] = buffer + width * height;
1122 output.data[2] = buffer + ( 5 * width * height ) / 4;
1123 output.linesize[0] = width;
1124 output.linesize[1] = width >> 1;
1125 output.linesize[2] = width >> 1;
1126 set_luma_transfer( context, colorspace, full_range );
1127 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1128 output.data, output.linesize);
1129 sws_freeContext( context );
1131 else if ( *format == mlt_image_rgb24 )
1133 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1134 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1136 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1137 set_luma_transfer( context, colorspace, full_range );
1138 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1139 output.data, output.linesize);
1140 sws_freeContext( context );
1142 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1144 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1145 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1147 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1148 set_luma_transfer( context, colorspace, full_range );
1149 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1150 output.data, output.linesize);
1151 sws_freeContext( context );
1155 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1156 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1158 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1159 set_luma_transfer( context, colorspace, full_range );
1160 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1161 output.data, output.linesize);
1162 sws_freeContext( context );
1165 if ( *format == mlt_image_yuv420p )
1168 pict.data[0] = buffer;
1169 pict.data[1] = buffer + width * height;
1170 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1171 pict.linesize[0] = width;
1172 pict.linesize[1] = width >> 1;
1173 pict.linesize[2] = width >> 1;
1174 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1176 else if ( *format == mlt_image_rgb24 )
1179 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1180 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1182 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
1185 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1186 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1191 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1192 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1197 /** Allocate the image buffer and set it on the frame.
1200 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1204 if ( codec_context->width == 0 || codec_context->height == 0 )
1207 *width = codec_context->width;
1208 *height = codec_context->height;
1210 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
1211 size = *width * ( *height + 1 ) * 4;
1213 size = mlt_image_format_size( *format, *width, *height, NULL );
1215 // Construct the output image
1216 *buffer = mlt_pool_alloc( size );
1218 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1225 /** Get an image from a frame.
1228 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1231 producer_avformat self = mlt_frame_pop_service( frame );
1232 mlt_producer producer = self->parent;
1234 // Get the properties from the frame
1235 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1237 // Obtain the frame number of this frame
1238 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1240 // Get the producer properties
1241 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1243 pthread_mutex_lock( &self->video_mutex );
1245 // Fetch the video format context
1246 AVFormatContext *context = self->video_format;
1248 // Get the video stream
1249 AVStream *stream = context->streams[ self->video_index ];
1251 // Get codec context
1252 AVCodecContext *codec_context = stream->codec;
1254 // Get the image cache
1255 if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1256 self->image_cache = mlt_cache_init();
1257 if ( self->image_cache )
1259 mlt_cache_item item = mlt_cache_get( self->image_cache, (void*) position );
1260 uint8_t *original = mlt_cache_item_data( item, (int*) format );
1263 // Set the resolution
1264 *width = codec_context->width;
1265 *height = codec_context->height;
1267 // Workaround 1088 encodings missing cropping info.
1268 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1272 int size = mlt_image_format_size( *format, *width, *height, NULL );
1275 *buffer = mlt_pool_alloc( size );
1276 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1277 memcpy( *buffer, original, size );
1278 mlt_cache_item_close( item );
1283 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1284 mlt_frame_set_image( frame, *buffer, size, NULL );
1286 self->got_picture = 1;
1288 goto exit_get_image;
1297 // Special case ffwd handling
1300 // We may want to use the source fps if available
1301 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1302 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1304 // This is the physical frame position in the source
1305 int req_position = ( int )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1307 // Determines if we have to decode all frames in a sequence
1308 // Temporary hack to improve intra frame only
1309 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
1310 strcmp( codec_context->codec->name, "dvvideo" ) &&
1311 strcmp( codec_context->codec->name, "huffyuv" ) &&
1312 strcmp( codec_context->codec->name, "mjpeg" ) &&
1313 strcmp( codec_context->codec->name, "rawvideo" );
1315 // Turn on usage of new seek API and PTS for seeking
1316 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1317 if ( mlt_properties_get( properties, "new_seek" ) )
1318 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1320 // Seek if necessary
1321 int paused = seek_video( self, position, req_position, must_decode, use_new_seek, &ignore );
1323 // Seek might have reopened the file
1324 context = self->video_format;
1325 stream = context->streams[ self->video_index ];
1326 codec_context = stream->codec;
1328 // Duplicate the last image if necessary
1329 if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture && self->seekable
1331 || self->current_position == req_position
1332 || ( !use_new_seek && self->current_position > req_position ) ) )
1335 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1337 // Workaround 1088 encodings missing cropping info.
1338 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1341 if ( self->vdpau && self->vdpau->buffer )
1344 picture.data[0] = self->vdpau->buffer;
1345 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1346 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1347 picture.linesize[0] = codec_context->width;
1348 picture.linesize[1] = codec_context->width / 2;
1349 picture.linesize[2] = codec_context->width / 2;
1350 convert_image( (AVFrame*) &picture, *buffer,
1351 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1355 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1356 format, *width, *height, self->colorspace );
1359 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1364 int int_position = 0;
1365 int decode_errors = 0;
1366 int got_picture = 0;
1368 av_init_packet( &pkt );
1370 // Construct an AVFrame for YUV422 conversion
1371 if ( !self->av_frame )
1372 self->av_frame = avcodec_alloc_frame( );
1374 while( ret >= 0 && !got_picture )
1377 pthread_mutex_lock( &self->packets_mutex );
1378 if ( mlt_deque_count( self->vpackets ) )
1380 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1386 ret = av_read_frame( context, &pkt );
1387 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->audio_index )
1389 if ( !av_dup_packet( &pkt ) )
1391 AVPacket *tmp = malloc( sizeof(AVPacket) );
1393 mlt_deque_push_back( self->apackets, tmp );
1397 pthread_mutex_unlock( &self->packets_mutex );
1399 // We only deal with video from the selected video_index
1400 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1402 // Determine time code of the packet
1405 int64_t pts = pkt.pts;
1406 if ( self->first_pts > 0 )
1407 pts -= self->first_pts;
1408 else if ( context->start_time != AV_NOPTS_VALUE )
1409 pts -= context->start_time;
1410 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1411 if ( pkt.pts == AV_NOPTS_VALUE )
1413 self->invalid_pts_counter++;
1414 if ( self->invalid_pts_counter > 20 )
1416 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1417 mlt_properties_set_int( properties, "new_seek", 0 );
1418 int_position = req_position;
1424 self->invalid_pts_counter = 0;
1426 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1427 pkt.pts, req_position, self->current_position, int_position );
1431 if ( self->seekable && pkt.dts != AV_NOPTS_VALUE )
1433 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1434 if ( context->start_time != AV_NOPTS_VALUE )
1435 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1436 if ( int_position == self->last_position )
1437 int_position = self->last_position + 1;
1441 int_position = req_position;
1443 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1444 pkt.dts, req_position, self->current_position, int_position );
1445 // Make a dumb assumption on streams that contain wild timestamps
1446 if ( abs( req_position - int_position ) > 999 )
1448 int_position = req_position;
1449 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1452 self->last_position = int_position;
1455 if ( must_decode || int_position >= req_position )
1458 if ( g_vdpau && self->vdpau )
1460 if ( g_vdpau->producer != self )
1462 vdpau_decoder_close();
1463 vdpau_decoder_init( self );
1466 self->vdpau->is_decoded = 0;
1469 codec_context->reordered_opaque = pkt.pts;
1470 if ( int_position >= req_position )
1471 codec_context->skip_loop_filter = AVDISCARD_NONE;
1472 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1473 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1475 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1477 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1480 if ( ++decode_errors <= 10 )
1493 // Determine time code of the packet
1494 int64_t pts = self->av_frame->reordered_opaque;
1495 if ( self->first_pts > 0 )
1496 pts -= self->first_pts;
1497 else if ( context->start_time != AV_NOPTS_VALUE )
1498 pts -= context->start_time;
1499 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1500 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, self->av_frame->key_frame );
1503 if ( int_position < req_position )
1508 else if ( int_position >= req_position )
1511 codec_context->skip_loop_filter = AVDISCARD_NONE;
1513 else if ( ignore -- )
1518 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1521 // Now handle the picture if we have one
1524 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1526 // Workaround 1088 encodings missing cropping info.
1527 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1532 if ( self->vdpau->is_decoded )
1534 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1536 uint32_t pitches[3];
1537 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1539 if ( !self->vdpau->buffer )
1540 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1541 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1542 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1543 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1544 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1545 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1546 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1548 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1549 if ( status == VDP_STATUS_OK )
1551 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1552 format, *width, *height, self->colorspace );
1556 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1557 image_size = self->vdpau->is_decoded = 0;
1562 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1563 image_size = got_picture = 0;
1568 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1569 format, *width, *height, self->colorspace );
1570 self->top_field_first |= self->av_frame->top_field_first;
1571 self->current_position = int_position;
1572 self->got_picture = 1;
1579 if ( self->seekable || pkt.stream_index != self->audio_index )
1580 av_free_packet( &pkt );
1584 if ( self->got_picture && image_size > 0 && self->image_cache )
1586 // Copy buffer to image cache
1587 uint8_t *image = mlt_pool_alloc( image_size );
1588 memcpy( image, *buffer, image_size );
1589 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1591 // Try to duplicate last image if there was a decoding failure
1592 else if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1595 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1597 // Workaround 1088 encodings missing cropping info.
1598 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1601 if ( self->vdpau && self->vdpau->buffer )
1604 picture.data[0] = self->vdpau->buffer;
1605 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1606 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1607 picture.linesize[0] = codec_context->width;
1608 picture.linesize[1] = codec_context->width / 2;
1609 picture.linesize[2] = codec_context->width / 2;
1610 convert_image( (AVFrame*) &picture, *buffer,
1611 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1615 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1616 format, *width, *height, self->colorspace );
1617 self->got_picture = 1;
1620 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1623 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1624 self->video_expected = position + 1;
1628 pthread_mutex_unlock( &self->video_mutex );
1630 // Set the progressive flag
1631 if ( mlt_properties_get( properties, "force_progressive" ) )
1632 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1633 else if ( self->av_frame )
1634 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1636 // Set the field order property for this frame
1637 if ( mlt_properties_get( properties, "force_tff" ) )
1638 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1640 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1642 // Set immutable properties of the selected track's (or overridden) source attributes.
1643 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1644 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1645 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1646 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1648 return !self->got_picture;
1651 /** Process properties as AVOptions and apply to AV context obj
1654 static void apply_properties( void *obj, mlt_properties properties, int flags )
1657 int count = mlt_properties_count( properties );
1658 for ( i = 0; i < count; i++ )
1660 const char *opt_name = mlt_properties_get_name( properties, i );
1661 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1662 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1665 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1666 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1667 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1668 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1670 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1676 /** Initialize the video codec context.
1679 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1681 // Initialise the codec if necessary
1682 if ( !self->video_codec )
1684 // Get the video stream
1685 AVStream *stream = self->video_format->streams[ index ];
1687 // Get codec context
1688 AVCodecContext *codec_context = stream->codec;
1691 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1693 if ( codec_context->codec_id == CODEC_ID_H264 )
1695 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1697 if ( vdpau_init( self ) )
1699 self->video_codec = codec_context;
1700 if ( !vdpau_decoder_init( self ) )
1701 vdpau_decoder_close();
1705 codec = avcodec_find_decoder( codec_context->codec_id );
1709 // Initialise multi-threading
1710 int thread_count = mlt_properties_get_int( properties, "threads" );
1711 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1712 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1713 if ( thread_count > 1 )
1714 codec_context->thread_count = thread_count;
1716 // If we don't have a codec and we can't initialise it, we can't do much more...
1718 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1720 // Now store the codec with its destructor
1721 self->video_codec = codec_context;
1725 // Remember that we can't use this later
1726 self->video_index = -1;
1732 // Process properties as AVOptions
1733 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1734 #if LIBAVCODEC_VERSION_MAJOR > 52
1735 if ( codec->priv_class && codec_context->priv_data )
1736 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1739 // Reset some image properties
1740 mlt_properties_set_int( properties, "width", self->video_codec->width );
1741 mlt_properties_set_int( properties, "height", self->video_codec->height );
1742 // For DV, we'll just use the saved aspect ratio
1743 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1744 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1746 // Determine the fps first from the codec
1747 double source_fps = (double) self->video_codec->time_base.den /
1748 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1750 if ( mlt_properties_get( properties, "force_fps" ) )
1752 source_fps = mlt_properties_get_double( properties, "force_fps" );
1753 stream->time_base = av_d2q( source_fps, 1024 );
1754 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1755 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1759 // If the muxer reports a frame rate different than the codec
1760 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1761 double muxer_fps = av_q2d( stream->avg_frame_rate );
1762 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1763 muxer_fps = av_q2d( stream->r_frame_rate );
1765 double muxer_fps = av_q2d( stream->r_frame_rate );
1767 // Choose the lesser - the wrong tends to be off by some multiple of 10
1768 source_fps = FFMIN( source_fps, muxer_fps );
1769 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1771 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1772 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1774 else if ( muxer_fps > 0 )
1776 AVRational frame_rate = stream->r_frame_rate;
1777 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1778 // avg_frame_rate gives some approximate value that does not well match the media.
1779 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1780 // results in some very choppy output, but some value slightly different works
1782 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1783 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1784 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1786 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1787 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1791 source_fps = mlt_producer_get_fps( self->parent );
1792 AVRational frame_rate = av_d2q( source_fps, 255 );
1793 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1794 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1798 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1799 if ( source_fps > 0 )
1800 mlt_properties_set_double( properties, "source_fps", source_fps );
1802 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
1804 // Set the YUV colorspace from override or detect
1805 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1806 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1807 if ( ! self->colorspace )
1809 switch ( self->video_codec->colorspace )
1811 case AVCOL_SPC_SMPTE240M:
1812 self->colorspace = 240;
1814 case AVCOL_SPC_BT470BG:
1815 case AVCOL_SPC_SMPTE170M:
1816 self->colorspace = 601;
1818 case AVCOL_SPC_BT709:
1819 self->colorspace = 709;
1822 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1823 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1828 // Let apps get chosen colorspace
1829 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1831 return self->video_codec && self->video_index > -1;
1834 /** Set up video handling.
1837 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1840 mlt_producer producer = self->parent;
1842 // Get the properties
1843 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1845 // Fetch the video format context
1846 AVFormatContext *context = self->video_format;
1848 // Get the video_index
1849 int index = mlt_properties_get_int( properties, "video_index" );
1851 // Reopen the file if necessary
1852 if ( !context && index > -1 )
1854 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1855 mlt_properties_get( properties, "resource" ) );
1856 context = self->video_format;
1859 // Exception handling for video_index
1860 if ( context && index >= (int) context->nb_streams )
1862 // Get the last video stream
1863 for ( index = context->nb_streams - 1;
1864 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1866 mlt_properties_set_int( properties, "video_index", index );
1868 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1870 // Invalidate the video stream
1872 mlt_properties_set_int( properties, "video_index", index );
1875 // Update the video properties if the index changed
1876 if ( index != self->video_index )
1878 // Reset the video properties if the index changed
1879 self->video_index = index;
1880 if ( self->video_codec )
1883 avcodec_close( self->video_codec );
1886 self->video_codec = NULL;
1889 // Get the frame properties
1890 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1893 if ( context && index > -1 && video_codec_init( self, index, properties ) )
1895 // Set the frame properties
1896 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1897 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1898 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1900 // Set the width and height
1901 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
1902 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
1903 // real_width and real_height are deprecated in favor of meta.media.width and .height
1904 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
1905 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
1906 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
1907 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
1908 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1909 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
1911 // Workaround 1088 encodings missing cropping info.
1912 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1914 mlt_properties_set_int( properties, "meta.media.height", 1080 );
1915 mlt_properties_set_int( frame_properties, "real_height", 1080 );
1918 // Add our image operation
1919 mlt_frame_push_service( frame, self );
1920 mlt_frame_push_get_image( frame, producer_get_image );
1924 // If something failed, use test card image
1925 mlt_properties_set_int( frame_properties, "test_image", 1 );
1929 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
1933 // Seek if necessary
1934 if ( self->seekable && position != self->audio_expected )
1936 if ( position + 1 == self->audio_expected )
1938 // We're paused - silence required
1941 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
1943 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1944 *ignore = position - self->audio_expected;
1946 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
1948 AVFormatContext *context = self->audio_format;
1949 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1950 if ( context->start_time != AV_NOPTS_VALUE )
1951 timestamp += context->start_time;
1952 if ( timestamp < 0 )
1955 // Set to the real timecode
1956 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1959 // Clear the usage in the audio buffer
1960 int i = MAX_AUDIO_STREAMS + 1;
1962 self->audio_used[i - 1] = 0;
1968 static int sample_bytes( AVCodecContext *context )
1970 #if LIBAVCODEC_VERSION_MAJOR > 52
1971 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
1973 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
1977 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
1979 // Fetch the audio_format
1980 AVFormatContext *context = self->audio_format;
1982 // Get the current stream index
1983 int index = pkt.stream_index;
1985 // Get codec context
1986 AVCodecContext *codec_context = self->audio_codec[ index ];
1988 // Obtain the resample context if it exists (not always needed)
1989 ReSampleContext *resample = self->audio_resample[ index ];
1991 // Obtain the audio buffers
1992 uint8_t *audio_buffer = self->audio_buffer[ index ];
1993 uint8_t *decode_buffer = self->decode_buffer[ index ];
1995 int audio_used = self->audio_used[ index ];
1996 uint8_t *ptr = pkt.data;
2000 while ( ptr && ret >= 0 && len > 0 )
2002 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2003 int data_size = self->audio_buffer_size[ index ];
2006 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2007 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2008 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2009 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2011 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2015 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2019 pkt.size = len -= ret;
2020 pkt.data = ptr += ret;
2022 // If decoded successfully
2023 if ( data_size > 0 )
2025 // Figure out how many samples will be needed after resampling
2026 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2027 int samples_needed = self->resample_factor * convert_samples;
2029 // Resize audio buffer to prevent overflow
2030 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2032 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2033 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2037 // Copy to audio buffer while resampling
2038 uint8_t *source = decode_buffer;
2039 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2040 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2044 // Straight copy to audio buffer
2045 memcpy( &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ], decode_buffer, data_size );
2046 audio_used += convert_samples;
2050 while ( *ignore && audio_used > samples )
2053 audio_used -= samples;
2054 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2055 audio_used * sizeof_sample );
2060 // If we're behind, ignore this packet
2063 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
2064 int req_position = ( int )( timecode * fps + 0.5 );
2065 int int_position = ( int )( current_pts * fps + 0.5 );
2066 if ( context->start_time != AV_NOPTS_VALUE )
2067 int_position -= ( int )( fps * context->start_time / AV_TIME_BASE + 0.5 );
2069 if ( self->seekable && *ignore == 0 )
2071 if ( int_position < req_position )
2072 // We are behind, so skip some
2074 else if ( int_position > req_position + 2 )
2075 // We are ahead, so seek backwards some more
2076 seek_audio( self, req_position, timecode - 1.0, ignore );
2080 self->audio_used[ index ] = audio_used;
2085 /** Get the audio from a frame.
2087 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2090 producer_avformat self = mlt_frame_pop_audio( frame );
2092 pthread_mutex_lock( &self->audio_mutex );
2094 // Obtain the frame number of this frame
2095 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
2097 // Calculate the real time code
2098 double real_timecode = producer_time_of_frame( self->parent, position );
2100 // Get the producer fps
2101 double fps = mlt_producer_get_fps( self->parent );
2103 // Number of frames to ignore (for ffwd)
2106 // Flag for paused (silence)
2107 int paused = seek_audio( self, position, real_timecode, &ignore );
2109 // Fetch the audio_format
2110 AVFormatContext *context = self->audio_format;
2112 int sizeof_sample = sizeof( int16_t );
2114 // Determine the tracks to use
2115 int index = self->audio_index;
2116 int index_max = self->audio_index + 1;
2117 if ( self->audio_index == INT_MAX )
2120 index_max = context->nb_streams;
2121 *channels = self->total_channels;
2122 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2123 *frequency = FFMAX( self->max_frequency, *frequency );
2126 // Initialize the resamplers and buffers
2127 for ( ; index < index_max; index++ )
2129 // Get codec context
2130 AVCodecContext *codec_context = self->audio_codec[ index ];
2132 if ( codec_context && !self->audio_buffer[ index ] )
2134 // Check for resample and create if necessary
2135 if ( codec_context->channels <= 2 )
2137 // Determine by how much resampling will increase number of samples
2138 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2139 resample_factor *= (double) *frequency / codec_context->sample_rate;
2140 if ( resample_factor > self->resample_factor )
2141 self->resample_factor = resample_factor;
2143 // Create the resampler
2144 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2145 self->audio_resample[ index ] = av_audio_resample_init(
2146 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2147 codec_context->channels, *frequency, codec_context->sample_rate,
2148 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2150 self->audio_resample[ index ] = audio_resample_init(
2151 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2152 codec_context->channels, *frequency, codec_context->sample_rate );
2157 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2158 sizeof_sample = sample_bytes( codec_context );
2161 // Check for audio buffer and create if necessary
2162 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2163 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2165 // Check for decoder buffer and create if necessary
2166 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2170 // Get the audio if required
2177 av_init_packet( &pkt );
2179 // If not resampling, give consumer more than requested.
2180 // It requested number samples based on requested frame rate.
2181 // Do not clean this up with a samples *= ...!
2182 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2183 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2185 while ( ret >= 0 && !got_audio )
2187 // Check if the buffer already contains the samples required
2188 if ( self->audio_index != INT_MAX && self->audio_used[ self->audio_index ] >= *samples && ignore == 0 )
2195 pthread_mutex_lock( &self->packets_mutex );
2196 if ( mlt_deque_count( self->apackets ) )
2198 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2204 ret = av_read_frame( context, &pkt );
2205 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2207 if ( !av_dup_packet( &pkt ) )
2209 AVPacket *tmp = malloc( sizeof(AVPacket) );
2211 mlt_deque_push_back( self->vpackets, tmp );
2215 pthread_mutex_unlock( &self->packets_mutex );
2217 // We only deal with audio from the selected audio index
2218 index = pkt.stream_index;
2219 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2220 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2222 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2223 self->audio_codec[index]->channels : *channels;
2224 ret = decode_audio( self, &ignore, pkt, channels2, *samples, real_timecode, fps );
2227 if ( self->seekable || index != self->video_index )
2228 av_free_packet( &pkt );
2230 if ( self->audio_index == INT_MAX && ret >= 0 )
2232 // Determine if there is enough audio for all streams
2234 for ( index = 0; index < context->nb_streams; index++ )
2236 if ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples )
2242 // Set some additional return values
2243 *format = mlt_audio_s16;
2244 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2246 index = self->audio_index;
2247 *channels = self->audio_codec[ index ]->channels;
2248 *frequency = self->audio_codec[ index ]->sample_rate;
2249 *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2250 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2252 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2254 else if ( self->audio_index == INT_MAX )
2256 // This only works if all audio tracks have the same sample format.
2257 for ( index = 0; index < index_max; index++ )
2258 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2260 *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2261 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2263 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2268 // Allocate and set the frame's audio buffer
2269 int size = mlt_audio_format_size( *format, *samples, *channels );
2270 *buffer = mlt_pool_alloc( size );
2271 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2273 // Interleave tracks if audio_index=all
2274 if ( self->audio_index == INT_MAX )
2276 uint8_t *dest = *buffer;
2278 for ( i = 0; i < *samples; i++ )
2280 for ( index = 0; index < index_max; index++ )
2281 if ( self->audio_codec[ index ] )
2283 int current_channels = self->audio_codec[ index ]->channels;
2284 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2285 memcpy( dest, src, current_channels * sizeof_sample );
2286 dest += current_channels * sizeof_sample;
2289 for ( index = 0; index < index_max; index++ )
2290 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2292 int current_channels = self->audio_codec[ index ]->channels;
2293 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2294 self->audio_used[index] -= *samples;
2295 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2298 // Copy a single track to the output buffer
2301 index = self->audio_index;
2303 // Now handle the audio if we have enough
2304 if ( self->audio_used[ index ] > 0 )
2306 uint8_t *src = self->audio_buffer[ index ];
2307 // copy samples from audio_buffer
2308 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2309 memcpy( *buffer, src, size * *channels * sizeof_sample );
2310 // supply the remaining requested samples as silence
2311 if ( *samples > self->audio_used[ index ] )
2312 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2313 // reposition the samples within audio_buffer
2314 self->audio_used[ index ] -= size;
2315 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2319 // Otherwise fill with silence
2320 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2326 // Get silence and don't touch the context
2327 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2330 // Regardless of speed (other than paused), we expect to get the next frame
2332 self->audio_expected = position + 1;
2334 pthread_mutex_unlock( &self->audio_mutex );
2339 /** Initialize the audio codec context.
2342 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2344 // Initialise the codec if necessary
2345 if ( !self->audio_codec[ index ] )
2347 // Get codec context
2348 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2351 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2353 // If we don't have a codec and we can't initialise it, we can't do much more...
2355 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2357 // Now store the codec with its destructor
2358 if ( self->audio_codec[ index ] )
2359 avcodec_close( self->audio_codec[ index ] );
2360 self->audio_codec[ index ] = codec_context;
2364 // Remember that we can't use self later
2365 self->audio_index = -1;
2369 // Process properties as AVOptions
2370 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2371 #if LIBAVCODEC_VERSION_MAJOR > 52
2372 if ( codec && codec->priv_class && codec_context->priv_data )
2373 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2376 return self->audio_codec[ index ] && self->audio_index > -1;
2379 /** Set up audio handling.
2382 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2385 mlt_producer producer = self->parent;
2387 // Get the properties
2388 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2390 // Fetch the audio format context
2391 AVFormatContext *context = self->audio_format;
2393 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2395 // Get the audio_index
2396 int index = mlt_properties_get_int( properties, "audio_index" );
2398 // Handle all audio tracks
2399 if ( self->audio_index > -1 &&
2400 mlt_properties_get( properties, "audio_index" ) &&
2401 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2404 // Reopen the file if necessary
2405 if ( !context && self->audio_index > -1 && index > -1 )
2407 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2408 mlt_properties_get( properties, "resource" ) );
2409 context = self->audio_format;
2412 // Exception handling for audio_index
2413 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2415 for ( index = context->nb_streams - 1;
2416 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2418 mlt_properties_set_int( properties, "audio_index", index );
2420 if ( context && index > -1 && index < INT_MAX &&
2421 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2423 index = self->audio_index;
2424 mlt_properties_set_int( properties, "audio_index", index );
2427 // Update the audio properties if the index changed
2428 if ( context && index > -1 && index != self->audio_index )
2430 if ( self->audio_codec[ self->audio_index ] )
2433 avcodec_close( self->audio_codec[ self->audio_index ] );
2436 self->audio_codec[ self->audio_index ] = NULL;
2438 if ( self->audio_index != -1 )
2439 self->audio_index = index;
2444 if ( context && index == INT_MAX )
2446 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2447 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2448 for ( index = 0; index < context->nb_streams; index++ )
2450 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2451 audio_codec_init( self, index, properties );
2454 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2456 // Set the frame properties
2457 if ( index < INT_MAX )
2459 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2460 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2463 if ( context && index > -1 )
2465 // Add our audio operation
2466 mlt_frame_push_audio( frame, self );
2467 mlt_frame_push_audio( frame, producer_get_audio );
2471 /** Our get frame implementation.
2474 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2476 // Access the private data
2477 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2478 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2479 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2484 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2485 producer->child = self;
2486 self->parent = producer;
2487 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2488 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2491 // Create an empty frame
2492 *frame = mlt_frame_init( service);
2496 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2500 mlt_cache_item_close( cache_item );
2504 // Update timecode on the frame we're creating
2505 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2507 // Set the position of this producer
2508 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
2511 producer_set_up_video( self, *frame );
2514 producer_set_up_audio( self, *frame );
2516 // Calculate the next timecode
2517 mlt_producer_prepare_next( producer );
2522 static void producer_avformat_close( producer_avformat self )
2524 mlt_log_debug( NULL, "producer_avformat_close\n" );
2526 // Cleanup av contexts
2527 av_free( self->av_frame );
2530 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2532 if ( self->audio_resample[i] )
2533 audio_resample_close( self->audio_resample[i] );
2534 mlt_pool_release( self->audio_buffer[i] );
2535 av_free( self->decode_buffer[i] );
2536 if ( self->audio_codec[i] )
2537 avcodec_close( self->audio_codec[i] );
2539 if ( self->video_codec )
2540 avcodec_close( self->video_codec );
2542 if ( self->dummy_context )
2543 av_close_input_file( self->dummy_context );
2544 if ( self->seekable && self->audio_format )
2545 av_close_input_file( self->audio_format );
2546 if ( self->video_format )
2547 av_close_input_file( self->video_format );
2550 vdpau_producer_close( self );
2552 if ( self->image_cache )
2553 mlt_cache_close( self->image_cache );
2555 // Cleanup the mutexes
2556 pthread_mutex_destroy( &self->audio_mutex );
2557 pthread_mutex_destroy( &self->video_mutex );
2558 pthread_mutex_destroy( &self->packets_mutex );
2560 // Cleanup the packet queues
2562 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2564 av_free_packet( pkt );
2567 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2569 av_free_packet( pkt );
2576 static void producer_close( mlt_producer parent )
2578 // Remove this instance from the cache
2579 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2582 parent->close = NULL;
2583 mlt_producer_close( parent );