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 );
149 /** Constructor for libavformat.
152 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
154 if ( list_components( file ) )
157 mlt_producer producer = NULL;
159 // Check that we have a non-NULL argument
162 // Construct the producer
163 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
164 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
167 if ( mlt_producer_init( producer, self ) == 0 )
169 self->parent = producer;
171 // Get the properties
172 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
174 // Set the resource property (required for all producers)
175 mlt_properties_set( properties, "resource", file );
177 // Register transport implementation with the producer
178 producer->close = (mlt_destructor) producer_close;
180 // Register our get_frame implementation
181 producer->get_frame = producer_get_frame;
183 if ( strcmp( service, "avformat-novalidate" ) )
186 if ( producer_open( self, profile, file ) != 0 )
189 mlt_producer_close( producer );
192 else if ( self->seekable )
194 // Close the file to release resources for large playlists - reopen later as needed
196 if ( self->dummy_context )
197 av_close_input_file( self->dummy_context );
198 self->dummy_context = NULL;
199 if ( self->audio_format )
200 av_close_input_file( self->audio_format );
201 self->audio_format = NULL;
202 if ( self->video_format )
203 av_close_input_file( self->video_format );
204 self->video_format = NULL;
207 // Default the user-selectable indices from the auto-detected indices
208 mlt_properties_set_int( properties, "audio_index", self->audio_index );
209 mlt_properties_set_int( properties, "video_index", self->video_index );
215 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
217 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
224 int list_components( char* file )
228 // Report information about available demuxers and codecs as YAML Tiny
229 if ( file && strstr( file, "f-list" ) )
231 fprintf( stderr, "---\nformats:\n" );
232 AVInputFormat *format = NULL;
233 while ( ( format = av_iformat_next( format ) ) )
234 fprintf( stderr, " - %s\n", format->name );
235 fprintf( stderr, "...\n" );
238 if ( file && strstr( file, "acodec-list" ) )
240 fprintf( stderr, "---\naudio_codecs:\n" );
241 AVCodec *codec = NULL;
242 while ( ( codec = av_codec_next( codec ) ) )
243 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
244 fprintf( stderr, " - %s\n", codec->name );
245 fprintf( stderr, "...\n" );
248 if ( file && strstr( file, "vcodec-list" ) )
250 fprintf( stderr, "---\nvideo_codecs:\n" );
251 AVCodec *codec = NULL;
252 while ( ( codec = av_codec_next( codec ) ) )
253 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
254 fprintf( stderr, " - %s\n", codec->name );
255 fprintf( stderr, "...\n" );
262 /** Find the default streams.
265 static mlt_properties find_default_streams( producer_avformat self )
269 AVMetadataTag *tag = NULL;
270 AVFormatContext *context = self->video_format;
271 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
273 // Default to the first audio and video streams found
274 self->audio_index = -1;
275 self->video_index = -1;
277 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
279 // Allow for multiple audio and video streams in the file and select first of each (if available)
280 for( i = 0; i < context->nb_streams; i++ )
282 // Get the codec context
283 AVStream *stream = context->streams[ i ];
284 if ( ! stream ) continue;
285 AVCodecContext *codec_context = stream->codec;
286 if ( ! codec_context ) continue;
287 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
288 if ( ! codec ) continue;
290 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
292 // Determine the type and obtain the first index of each type
293 switch( codec_context->codec_type )
295 case CODEC_TYPE_VIDEO:
296 // Use first video stream
297 if ( self->video_index < 0 )
298 self->video_index = i;
299 mlt_properties_set( meta_media, key, "video" );
300 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
301 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
302 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
303 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
304 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
305 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
307 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
310 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
311 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
312 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
314 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
315 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
316 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
317 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
318 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
319 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
320 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
321 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
322 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
323 switch ( codec_context->colorspace )
325 case AVCOL_SPC_SMPTE240M:
326 mlt_properties_set_int( meta_media, key, 240 );
328 case AVCOL_SPC_BT470BG:
329 case AVCOL_SPC_SMPTE170M:
330 mlt_properties_set_int( meta_media, key, 601 );
332 case AVCOL_SPC_BT709:
333 mlt_properties_set_int( meta_media, key, 709 );
336 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
337 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
342 case CODEC_TYPE_AUDIO:
343 // Use first audio stream
344 if ( self->audio_index < 0 )
345 self->audio_index = i;
346 mlt_properties_set( meta_media, key, "audio" );
347 #if LIBAVCODEC_VERSION_MAJOR > 52
348 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
349 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
350 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
351 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
352 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
354 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
355 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
356 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
357 mlt_properties_set_int( meta_media, key, codec_context->channels );
362 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
363 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
364 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
365 mlt_properties_set( meta_media, key, codec->name );
366 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
367 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
368 mlt_properties_set( meta_media, key, codec->long_name );
370 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
371 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
372 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
373 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
374 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
375 // mlt_properties_set_int( meta_media, key, codec_context->profile );
376 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
377 // mlt_properties_set_int( meta_media, key, codec_context->level );
380 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
381 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
383 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
385 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
386 mlt_properties_set( meta_media, key, tag->value );
391 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
392 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
394 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
396 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
397 mlt_properties_set( meta_media, key, tag->value );
401 if ( context->title && strcmp( context->title, "" ) )
402 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
403 if ( context->author && strcmp( context->author, "" ) )
404 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
405 if ( context->copyright && strcmp( context->copyright, "" ) )
406 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
407 if ( context->comment )
408 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
409 if ( context->album )
410 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
412 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
413 if ( context->track )
414 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
420 static inline int dv_is_pal( AVPacket *pkt )
422 return pkt->data[3] & 0x80;
425 static int dv_is_wide( AVPacket *pkt )
427 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
429 for ( ; i < pkt->size; i += 5 /* packet size */ )
431 if ( pkt->data[ i ] == 0x61 )
433 uint8_t x = pkt->data[ i + 2 ] & 0x7;
434 return ( x == 2 ) || ( x == 7 );
440 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
442 double aspect_ratio = 1.0;
444 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
448 if ( dv_is_pal( pkt ) )
450 if ( dv_is_wide( pkt ) )
452 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
453 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
457 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
458 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
463 if ( dv_is_wide( pkt ) )
465 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
466 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
470 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
471 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
478 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
479 stream->sample_aspect_ratio;
481 codec_context->sample_aspect_ratio;
483 // Override FFmpeg's notion of DV aspect ratios, which are
484 // based upon a width of 704. Since we do not have a normaliser
485 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
486 // we just coerce the values to facilitate a passive behaviour through
487 // the rescale normaliser when using equivalent producers and consumers.
488 // = display_aspect / (width * height)
489 if ( ar.num == 10 && ar.den == 11 )
492 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
493 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
495 else if ( ar.num == 59 && ar.den == 54 )
498 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
499 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
501 else if ( ar.num == 40 && ar.den == 33 )
504 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
505 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
507 else if ( ar.num == 118 && ar.den == 81 )
510 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
511 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
517 AVRational codec_sar = codec_context->sample_aspect_ratio;
518 AVRational stream_sar =
519 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
520 stream->sample_aspect_ratio;
524 if ( codec_sar.num > 0 )
526 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
527 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
529 else if ( stream_sar.num > 0 )
531 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
532 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
536 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
537 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
540 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
541 aspect_ratio = av_q2d( ar );
542 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
547 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters **parameters )
549 if ( !URL ) return NULL;
552 char *protocol = strdup( URL );
553 char *url = strchr( protocol, ':' );
555 // Only if there is not a protocol specification that avformat can handle
556 #if LIBAVFORMAT_VERSION_MAJOR > 52
557 if ( url && avio_check( URL, 0 ) < 0 )
559 if ( url && !url_exist( URL ) )
562 // Truncate protocol string
566 *format = av_find_input_format( protocol );
568 // Eat the format designator
574 AVFormatParameters *params = *parameters = calloc( 1, sizeof( AVFormatParameters ) );
576 // These are required by video4linux2 (defaults)
577 params->width = profile->width;
578 params->height = profile->height;
579 params->time_base= (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
580 params->channels = 2;
581 params->sample_rate = 48000;
584 url = strchr( url, '?' );
588 char *name = strdup( ++url );
589 char *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, '&' );
624 return result ? strdup( result ) : strdup( URL );
627 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
631 // Get the properties
632 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
634 AVFormatContext *format = self->video_format;
636 // We will treat everything with the producer fps.
637 // TODO: make this more flexible.
638 double fps = mlt_profile_fps( profile );
641 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
643 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
644 // when producer_open is called after initial call when restoring or reseting the producer.
645 if ( format->duration != AV_NOPTS_VALUE )
647 // This isn't going to be accurate for all formats
648 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
649 mlt_properties_set_position( properties, "out", frames - 1 );
650 mlt_properties_set_position( properties, "length", frames );
651 mlt_properties_set_int( properties, "_length_computed", 1 );
655 // Set live sources to run forever
656 mlt_properties_set_position( properties, "length", INT_MAX );
657 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
658 mlt_properties_set( properties, "eof", "loop" );
659 mlt_properties_set_int( properties, "_length_computed", 1 );
663 if ( format->start_time != AV_NOPTS_VALUE )
664 self->start_time = format->start_time;
666 // Check if we're seekable
667 // avdevices are typically AVFMT_NOFILE and not seekable
668 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
671 // protocols can indicate if they support seeking
672 #if LIBAVFORMAT_VERSION_MAJOR > 52
673 self->seekable = context->pb->seekable;
675 URLContext *uc = url_fileno( format->pb );
677 self->seekable = !uc->is_streamed;
680 if ( self->seekable )
682 // Do a more rigourous test of seekable on a disposable context
683 self->seekable = av_seek_frame( format, -1, self->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
684 mlt_properties_set_int( properties, "seekable", self->seekable );
685 self->dummy_context = format;
686 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
687 format = self->video_format;
688 av_find_stream_info( format );
691 // Fetch the width, height and aspect ratio
692 if ( self->video_index != -1 )
694 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
695 mlt_properties_set_int( properties, "width", codec_context->width );
696 mlt_properties_set_int( properties, "height", codec_context->height );
698 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
700 // Fetch the first frame of DV so we can read it directly
705 ret = av_read_frame( format, &pkt );
706 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
708 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
715 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
719 // Verify that we can convert this to YUV 4:2:2
720 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
721 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
722 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
724 sws_freeContext( context );
735 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL )
737 // Return an error code (0 == no error)
741 pthread_mutex_init( &self->audio_mutex, NULL );
742 pthread_mutex_init( &self->video_mutex, NULL );
743 pthread_mutex_init( &self->packets_mutex, NULL );
744 pthread_mutex_lock( &self->audio_mutex );
745 pthread_mutex_lock( &self->video_mutex );
748 AVInputFormat *format = NULL;
749 AVFormatParameters *params = NULL;
750 char *filename = parse_url( profile, URL, &format, ¶ms );
752 // Now attempt to open the file or device with filename
753 error = av_open_input_file( &self->video_format, filename, format, 0, params ) < 0;
755 // If the URL is a network stream URL, then we probably need to open with full URL
756 error = av_open_input_file( &self->video_format, URL, format, 0, params ) < 0;
758 // Cleanup AVFormatParameters
761 if ( params->standard )
762 free( (void*) params->standard );
766 // If successful, then try to get additional info
769 // Get the stream info
770 error = av_find_stream_info( self->video_format ) < 0;
772 // Continue if no error
775 // Find default audio and video streams
776 find_default_streams( self );
777 error = get_basic_info( self, profile, filename );
779 // Initialize position info
780 self->first_pts = -1;
781 self->last_position = POSITION_INITIAL;
783 // We're going to cheat here - for seekable A/V files, we will have separate contexts
784 // to support independent seeking of audio from video.
785 // TODO: Is this really necessary?
786 if ( self->audio_index != -1 && self->video_index != -1 )
788 if ( self->seekable )
790 // And open again for our audio context
791 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
792 av_find_stream_info( self->audio_format );
796 self->audio_format = self->video_format;
799 else if ( self->audio_index != -1 )
801 // We only have an audio context
802 self->audio_format = self->video_format;
803 self->video_format = NULL;
805 else if ( self->video_index == -1 )
807 // Something has gone wrong
816 self->apackets = mlt_deque_init();
817 self->vpackets = mlt_deque_init();
820 // Unlock the service
821 pthread_mutex_unlock( &self->audio_mutex );
822 pthread_mutex_unlock( &self->video_mutex );
827 static void reopen_video( producer_avformat self, mlt_producer producer )
829 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
830 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
831 pthread_mutex_lock( &self->audio_mutex );
833 if ( self->video_codec )
836 avcodec_close( self->video_codec );
839 self->video_codec = NULL;
840 if ( self->dummy_context )
841 av_close_input_file( self->dummy_context );
842 self->dummy_context = NULL;
843 if ( self->video_format )
844 av_close_input_file( self->video_format );
845 self->video_format = NULL;
847 int audio_index = self->audio_index;
848 int video_index = self->video_index;
850 mlt_events_block( properties, producer );
851 pthread_mutex_unlock( &self->audio_mutex );
852 pthread_mutex_unlock( &self->video_mutex );
853 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
854 mlt_properties_get( properties, "resource" ) );
855 pthread_mutex_lock( &self->video_mutex );
856 pthread_mutex_lock( &self->audio_mutex );
857 if ( self->dummy_context )
859 av_close_input_file( self->dummy_context );
860 self->dummy_context = NULL;
862 mlt_events_unblock( properties, producer );
863 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
864 #if LIBAVFORMAT_VERSION_MAJOR > 52
865 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
866 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
869 self->audio_index = audio_index;
870 if ( self->video_format && video_index > -1 )
872 self->video_index = video_index;
873 video_codec_init( self, video_index, properties );
876 pthread_mutex_unlock( &self->audio_mutex );
877 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
880 static int seek_video( producer_avformat self, mlt_position position,
881 int req_position, int must_decode, int use_new_seek, int *ignore )
883 mlt_producer producer = self->parent;
886 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
888 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
890 // Fetch the video format context
891 AVFormatContext *context = self->video_format;
893 // Get the video stream
894 AVStream *stream = context->streams[ self->video_index ];
897 AVCodecContext *codec_context = stream->codec;
899 // We may want to use the source fps if available
900 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
901 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
903 if ( self->av_frame && position + 1 == self->video_expected )
905 // We're paused - use last image
908 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
910 // Fast forward - seeking is inefficient for small distances - just ignore following frames
911 *ignore = ( int )( ( position - self->video_expected ) / mlt_producer_get_fps( producer ) * source_fps );
912 codec_context->skip_loop_filter = AVDISCARD_NONREF;
914 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
916 if ( use_new_seek && self->last_position == POSITION_INITIAL )
918 // find first key frame
923 while ( ret >= 0 && toscan-- > 0 )
925 ret = av_read_frame( context, &pkt );
926 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
928 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) );
929 self->first_pts = pkt.pts;
932 av_free_packet( &pkt );
935 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
938 // Calculate the timestamp for the requested frame
942 timestamp = ( req_position - 0.1 / source_fps ) /
943 ( av_q2d( stream->time_base ) * source_fps );
944 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %"PRId64" ", req_position, timestamp );
945 if ( self->first_pts > 0 )
946 timestamp += self->first_pts;
947 else if ( context->start_time != AV_NOPTS_VALUE )
948 timestamp += context->start_time;
952 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
953 if ( context->start_time != AV_NOPTS_VALUE )
954 timestamp += context->start_time;
957 timestamp -= AV_TIME_BASE;
960 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %d\n",
961 timestamp, position, self->video_expected, self->last_position );
963 // Seek to the timestamp
966 codec_context->skip_loop_filter = AVDISCARD_NONREF;
967 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
969 else if ( req_position > 0 || self->last_position <= 0 )
971 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
975 // Re-open video stream when rewinding to beginning from somewhere else.
976 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
977 // not reliably seeking to the first frame across formats.
978 reopen_video( self, producer );
981 // Remove the cached info relating to the previous position
982 self->current_position = POSITION_INVALID;
983 self->last_position = POSITION_INVALID;
984 av_freep( &self->av_frame );
988 // flush any pictures still in decode buffer
989 avcodec_flush_buffers( codec_context );
996 /** Convert a frame position to a time code.
999 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1001 return ( double )position / mlt_producer_get_fps( producer );
1004 // Collect information about all audio streams
1006 static void get_audio_streams_info( producer_avformat self )
1008 // Fetch the audio format context
1009 AVFormatContext *context = self->audio_format;
1013 i < context->nb_streams;
1016 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1018 AVCodecContext *codec_context = context->streams[i]->codec;
1019 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1021 // If we don't have a codec and we can't initialise it, we can't do much more...
1023 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1025 self->audio_streams++;
1026 self->audio_max_stream = i;
1027 self->total_channels += codec_context->channels;
1028 if ( codec_context->channels > self->max_channel )
1029 self->max_channel = codec_context->channels;
1030 if ( codec_context->sample_rate > self->max_frequency )
1031 self->max_frequency = codec_context->sample_rate;
1032 avcodec_close( codec_context );
1037 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1038 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1040 // Other audio-specific initializations
1041 self->resample_factor = 1.0;
1044 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1046 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1048 const int *new_coefficients;
1050 int brightness, contrast, saturation;
1052 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1053 &brightness, &contrast, &saturation ) != -1 )
1055 // Don't change these from defaults unless explicitly told to.
1056 if ( use_full_range >= 0 )
1057 full_range = use_full_range;
1058 switch ( colorspace )
1064 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1067 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1070 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1073 new_coefficients = coefficients;
1076 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1077 brightness, contrast, saturation );
1082 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
1083 mlt_image_format *format, int width, int height, int colorspace )
1086 int full_range = -1;
1087 int flags = SWS_BILINEAR | SWS_ACCURATE_RND;
1090 flags |= SWS_CPU_CAPS_MMX;
1093 flags |= SWS_CPU_CAPS_MMX2;
1096 if ( pix_fmt == PIX_FMT_RGB32 )
1098 *format = mlt_image_rgb24a;
1099 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1100 width, height, PIX_FMT_RGBA, flags, NULL, NULL, NULL);
1102 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1103 set_luma_transfer( context, colorspace, full_range );
1104 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1105 output.data, output.linesize);
1106 sws_freeContext( context );
1108 else if ( *format == mlt_image_yuv420p )
1110 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1111 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1113 output.data[0] = buffer;
1114 output.data[1] = buffer + width * height;
1115 output.data[2] = buffer + ( 5 * width * height ) / 4;
1116 output.linesize[0] = width;
1117 output.linesize[1] = width >> 1;
1118 output.linesize[2] = width >> 1;
1119 set_luma_transfer( context, colorspace, full_range );
1120 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1121 output.data, output.linesize);
1122 sws_freeContext( context );
1124 else if ( *format == mlt_image_rgb24 )
1126 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1127 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1129 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1130 set_luma_transfer( context, colorspace, full_range );
1131 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1132 output.data, output.linesize);
1133 sws_freeContext( context );
1135 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1137 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1138 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1140 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1141 set_luma_transfer( context, colorspace, full_range );
1142 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1143 output.data, output.linesize);
1144 sws_freeContext( context );
1148 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1149 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1151 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1152 set_luma_transfer( context, colorspace, full_range );
1153 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1154 output.data, output.linesize);
1155 sws_freeContext( context );
1158 if ( *format == mlt_image_yuv420p )
1161 pict.data[0] = buffer;
1162 pict.data[1] = buffer + width * height;
1163 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1164 pict.linesize[0] = width;
1165 pict.linesize[1] = width >> 1;
1166 pict.linesize[2] = width >> 1;
1167 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1169 else if ( *format == mlt_image_rgb24 )
1172 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1173 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1175 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
1178 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1179 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1184 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1185 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1190 /** Allocate the image buffer and set it on the frame.
1193 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1197 if ( codec_context->width == 0 || codec_context->height == 0 )
1200 *width = codec_context->width;
1201 *height = codec_context->height;
1203 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
1204 size = *width * ( *height + 1 ) * 4;
1206 size = mlt_image_format_size( *format, *width, *height, NULL );
1208 // Construct the output image
1209 *buffer = mlt_pool_alloc( size );
1211 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1218 /** Get an image from a frame.
1221 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1224 producer_avformat self = mlt_frame_pop_service( frame );
1225 mlt_producer producer = self->parent;
1227 // Get the properties from the frame
1228 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1230 // Obtain the frame number of this frame
1231 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1233 // Get the producer properties
1234 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1236 pthread_mutex_lock( &self->video_mutex );
1238 // Fetch the video format context
1239 AVFormatContext *context = self->video_format;
1241 // Get the video stream
1242 AVStream *stream = context->streams[ self->video_index ];
1244 // Get codec context
1245 AVCodecContext *codec_context = stream->codec;
1247 // Get the image cache
1248 if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1249 self->image_cache = mlt_cache_init();
1250 if ( self->image_cache )
1252 mlt_cache_item item = mlt_cache_get( self->image_cache, (void*) position );
1253 uint8_t *original = mlt_cache_item_data( item, (int*) format );
1256 // Set the resolution
1257 *width = codec_context->width;
1258 *height = codec_context->height;
1260 // Workaround 1088 encodings missing cropping info.
1261 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1265 int size = mlt_image_format_size( *format, *width, *height, NULL );
1268 *buffer = mlt_pool_alloc( size );
1269 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1270 memcpy( *buffer, original, size );
1271 mlt_cache_item_close( item );
1276 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1277 mlt_frame_set_image( frame, *buffer, size, NULL );
1279 self->got_picture = 1;
1281 goto exit_get_image;
1290 // Special case ffwd handling
1293 // We may want to use the source fps if available
1294 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1295 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1297 // This is the physical frame position in the source
1298 int req_position = ( int )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1300 // Determines if we have to decode all frames in a sequence
1301 // Temporary hack to improve intra frame only
1302 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
1303 strcmp( codec_context->codec->name, "dvvideo" ) &&
1304 strcmp( codec_context->codec->name, "huffyuv" ) &&
1305 strcmp( codec_context->codec->name, "mjpeg" ) &&
1306 strcmp( codec_context->codec->name, "rawvideo" );
1308 // Turn on usage of new seek API and PTS for seeking
1309 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1310 if ( mlt_properties_get( properties, "new_seek" ) )
1311 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1313 // Seek if necessary
1314 int paused = seek_video( self, position, req_position, must_decode, use_new_seek, &ignore );
1316 // Seek might have reopened the file
1317 context = self->video_format;
1318 stream = context->streams[ self->video_index ];
1319 codec_context = stream->codec;
1321 // Duplicate the last image if necessary
1322 if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture && self->seekable
1324 || self->current_position == req_position
1325 || ( !use_new_seek && self->current_position > req_position ) ) )
1328 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1330 // Workaround 1088 encodings missing cropping info.
1331 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1334 if ( self->vdpau && self->vdpau->buffer )
1337 picture.data[0] = self->vdpau->buffer;
1338 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1339 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1340 picture.linesize[0] = codec_context->width;
1341 picture.linesize[1] = codec_context->width / 2;
1342 picture.linesize[2] = codec_context->width / 2;
1343 convert_image( (AVFrame*) &picture, *buffer,
1344 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1348 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1349 format, *width, *height, self->colorspace );
1352 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1357 int int_position = 0;
1358 int decode_errors = 0;
1359 int got_picture = 0;
1361 av_init_packet( &pkt );
1363 // Construct an AVFrame for YUV422 conversion
1364 if ( !self->av_frame )
1365 self->av_frame = avcodec_alloc_frame( );
1367 while( ret >= 0 && !got_picture )
1370 pthread_mutex_lock( &self->packets_mutex );
1371 if ( mlt_deque_count( self->vpackets ) )
1373 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1379 ret = av_read_frame( context, &pkt );
1380 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->audio_index )
1382 if ( !av_dup_packet( &pkt ) )
1384 AVPacket *tmp = malloc( sizeof(AVPacket) );
1386 mlt_deque_push_back( self->apackets, tmp );
1390 pthread_mutex_unlock( &self->packets_mutex );
1392 // We only deal with video from the selected video_index
1393 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1395 // Determine time code of the packet
1398 int64_t pts = pkt.pts;
1399 if ( self->first_pts > 0 )
1400 pts -= self->first_pts;
1401 else if ( context->start_time != AV_NOPTS_VALUE )
1402 pts -= context->start_time;
1403 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1404 if ( pkt.pts == AV_NOPTS_VALUE )
1406 self->invalid_pts_counter++;
1407 if ( self->invalid_pts_counter > 20 )
1409 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1410 mlt_properties_set_int( properties, "new_seek", 0 );
1411 int_position = req_position;
1417 self->invalid_pts_counter = 0;
1419 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1420 pkt.pts, req_position, self->current_position, int_position );
1424 if ( self->seekable && pkt.dts != AV_NOPTS_VALUE )
1426 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1427 if ( context->start_time != AV_NOPTS_VALUE )
1428 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1429 if ( int_position == self->last_position )
1430 int_position = self->last_position + 1;
1434 int_position = req_position;
1436 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1437 pkt.dts, req_position, self->current_position, int_position );
1438 // Make a dumb assumption on streams that contain wild timestamps
1439 if ( abs( req_position - int_position ) > 999 )
1441 int_position = req_position;
1442 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1445 self->last_position = int_position;
1448 if ( must_decode || int_position >= req_position )
1451 if ( g_vdpau && self->vdpau )
1453 if ( g_vdpau->producer != self )
1455 vdpau_decoder_close();
1456 vdpau_decoder_init( self );
1459 self->vdpau->is_decoded = 0;
1462 codec_context->reordered_opaque = pkt.pts;
1463 if ( int_position >= req_position )
1464 codec_context->skip_loop_filter = AVDISCARD_NONE;
1465 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1466 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1468 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1470 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1473 if ( ++decode_errors <= 10 )
1486 // Determine time code of the packet
1487 int64_t pts = self->av_frame->reordered_opaque;
1488 if ( self->first_pts > 0 )
1489 pts -= self->first_pts;
1490 else if ( context->start_time != AV_NOPTS_VALUE )
1491 pts -= context->start_time;
1492 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1493 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, self->av_frame->key_frame );
1496 if ( int_position < req_position )
1501 else if ( int_position >= req_position )
1504 codec_context->skip_loop_filter = AVDISCARD_NONE;
1506 else if ( ignore -- )
1511 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1514 // Now handle the picture if we have one
1517 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1519 // Workaround 1088 encodings missing cropping info.
1520 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1525 if ( self->vdpau->is_decoded )
1527 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1529 uint32_t pitches[3];
1530 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1532 if ( !self->vdpau->buffer )
1533 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1534 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1535 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1536 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1537 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1538 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1539 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1541 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1542 if ( status == VDP_STATUS_OK )
1544 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1545 format, *width, *height, self->colorspace );
1549 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1550 image_size = self->vdpau->is_decoded = 0;
1555 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1556 image_size = got_picture = 0;
1561 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1562 format, *width, *height, self->colorspace );
1563 self->top_field_first |= self->av_frame->top_field_first;
1564 self->current_position = int_position;
1565 self->got_picture = 1;
1572 if ( self->seekable || pkt.stream_index != self->audio_index )
1573 av_free_packet( &pkt );
1577 if ( self->got_picture && image_size > 0 && self->image_cache )
1579 // Copy buffer to image cache
1580 uint8_t *image = mlt_pool_alloc( image_size );
1581 memcpy( image, *buffer, image_size );
1582 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1584 // Try to duplicate last image if there was a decoding failure
1585 else if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1588 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1590 // Workaround 1088 encodings missing cropping info.
1591 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1594 if ( self->vdpau && self->vdpau->buffer )
1597 picture.data[0] = self->vdpau->buffer;
1598 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1599 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1600 picture.linesize[0] = codec_context->width;
1601 picture.linesize[1] = codec_context->width / 2;
1602 picture.linesize[2] = codec_context->width / 2;
1603 convert_image( (AVFrame*) &picture, *buffer,
1604 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1608 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1609 format, *width, *height, self->colorspace );
1610 self->got_picture = 1;
1613 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1616 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1617 self->video_expected = position + 1;
1621 pthread_mutex_unlock( &self->video_mutex );
1623 // Set the progressive flag
1624 if ( mlt_properties_get( properties, "force_progressive" ) )
1625 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1626 else if ( self->av_frame )
1627 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1629 // Set the field order property for this frame
1630 if ( mlt_properties_get( properties, "force_tff" ) )
1631 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1633 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1635 // Set immutable properties of the selected track's (or overridden) source attributes.
1636 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1637 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1638 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1639 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1641 return !self->got_picture;
1644 /** Process properties as AVOptions and apply to AV context obj
1647 static void apply_properties( void *obj, mlt_properties properties, int flags )
1650 int count = mlt_properties_count( properties );
1651 for ( i = 0; i < count; i++ )
1653 const char *opt_name = mlt_properties_get_name( properties, i );
1654 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1655 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1658 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1659 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1660 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1661 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1663 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1669 /** Initialize the video codec context.
1672 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1674 // Initialise the codec if necessary
1675 if ( !self->video_codec )
1677 // Get the video stream
1678 AVStream *stream = self->video_format->streams[ index ];
1680 // Get codec context
1681 AVCodecContext *codec_context = stream->codec;
1684 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1686 if ( codec_context->codec_id == CODEC_ID_H264 )
1688 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1690 if ( vdpau_init( self ) )
1692 self->video_codec = codec_context;
1693 if ( !vdpau_decoder_init( self ) )
1694 vdpau_decoder_close();
1698 codec = avcodec_find_decoder( codec_context->codec_id );
1702 // Initialise multi-threading
1703 int thread_count = mlt_properties_get_int( properties, "threads" );
1704 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1705 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1706 if ( thread_count > 1 )
1707 codec_context->thread_count = thread_count;
1709 // If we don't have a codec and we can't initialise it, we can't do much more...
1711 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1713 // Now store the codec with its destructor
1714 self->video_codec = codec_context;
1718 // Remember that we can't use this later
1719 self->video_index = -1;
1725 // Process properties as AVOptions
1726 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1727 #if LIBAVCODEC_VERSION_MAJOR > 52
1728 if ( codec->priv_class && codec_context->priv_data )
1729 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1732 // Reset some image properties
1733 mlt_properties_set_int( properties, "width", self->video_codec->width );
1734 mlt_properties_set_int( properties, "height", self->video_codec->height );
1735 // For DV, we'll just use the saved aspect ratio
1736 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1737 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1739 // Determine the fps first from the codec
1740 double source_fps = (double) self->video_codec->time_base.den /
1741 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1743 if ( mlt_properties_get( properties, "force_fps" ) )
1745 source_fps = mlt_properties_get_double( properties, "force_fps" );
1746 stream->time_base = av_d2q( source_fps, 1024 );
1747 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1748 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1752 // If the muxer reports a frame rate different than the codec
1753 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1754 double muxer_fps = av_q2d( stream->avg_frame_rate );
1755 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1756 muxer_fps = av_q2d( stream->r_frame_rate );
1758 double muxer_fps = av_q2d( stream->r_frame_rate );
1760 // Choose the lesser - the wrong tends to be off by some multiple of 10
1761 source_fps = FFMIN( source_fps, muxer_fps );
1762 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1764 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1765 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1767 else if ( muxer_fps > 0 )
1769 AVRational frame_rate = stream->r_frame_rate;
1770 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1771 // avg_frame_rate gives some approximate value that does not well match the media.
1772 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1773 // results in some very choppy output, but some value slightly different works
1775 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1776 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1777 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1779 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1780 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1784 source_fps = mlt_producer_get_fps( self->parent );
1785 AVRational frame_rate = av_d2q( source_fps, 255 );
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 is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1792 if ( source_fps > 0 )
1793 mlt_properties_set_double( properties, "source_fps", source_fps );
1795 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
1797 // Set the YUV colorspace from override or detect
1798 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1799 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1800 if ( ! self->colorspace )
1802 switch ( self->video_codec->colorspace )
1804 case AVCOL_SPC_SMPTE240M:
1805 self->colorspace = 240;
1807 case AVCOL_SPC_BT470BG:
1808 case AVCOL_SPC_SMPTE170M:
1809 self->colorspace = 601;
1811 case AVCOL_SPC_BT709:
1812 self->colorspace = 709;
1815 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1816 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1821 // Let apps get chosen colorspace
1822 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1824 return self->video_codec && self->video_index > -1;
1827 /** Set up video handling.
1830 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1833 mlt_producer producer = self->parent;
1835 // Get the properties
1836 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1838 // Fetch the video format context
1839 AVFormatContext *context = self->video_format;
1841 // Get the video_index
1842 int index = mlt_properties_get_int( properties, "video_index" );
1844 // Reopen the file if necessary
1845 if ( !context && index > -1 )
1847 mlt_events_block( properties, producer );
1848 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1849 mlt_properties_get( properties, "resource" ) );
1850 context = self->video_format;
1851 if ( self->dummy_context )
1853 av_close_input_file( self->dummy_context );
1854 self->dummy_context = NULL;
1856 mlt_events_unblock( properties, producer );
1857 if ( self->audio_format && !self->audio_streams )
1858 get_audio_streams_info( self );
1860 // Process properties as AVOptions
1863 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1864 #if LIBAVFORMAT_VERSION_MAJOR > 52
1865 if ( context->iformat && context->iformat->priv_class && context->priv_data )
1866 apply_properties( context->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
1871 // Exception handling for video_index
1872 if ( context && index >= (int) context->nb_streams )
1874 // Get the last video stream
1875 for ( index = context->nb_streams - 1;
1876 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1878 mlt_properties_set_int( properties, "video_index", index );
1880 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1882 // Invalidate the video stream
1884 mlt_properties_set_int( properties, "video_index", index );
1887 // Update the video properties if the index changed
1888 if ( index != self->video_index )
1890 // Reset the video properties if the index changed
1891 self->video_index = index;
1892 if ( self->video_codec )
1895 avcodec_close( self->video_codec );
1898 self->video_codec = NULL;
1901 // Get the frame properties
1902 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1905 if ( context && index > -1 && video_codec_init( self, index, properties ) )
1907 // Set the frame properties
1908 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1909 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1910 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1912 // Set the width and height
1913 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
1914 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
1915 // real_width and real_height are deprecated in favor of meta.media.width and .height
1916 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
1917 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
1918 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
1919 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
1920 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1921 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
1923 // Workaround 1088 encodings missing cropping info.
1924 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1926 mlt_properties_set_int( properties, "meta.media.height", 1080 );
1927 mlt_properties_set_int( frame_properties, "real_height", 1080 );
1930 // Add our image operation
1931 mlt_frame_push_service( frame, self );
1932 mlt_frame_push_get_image( frame, producer_get_image );
1936 // If something failed, use test card image
1937 mlt_properties_set_int( frame_properties, "test_image", 1 );
1941 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
1945 // Seek if necessary
1946 if ( self->seekable && position != self->audio_expected )
1948 if ( position + 1 == self->audio_expected )
1950 // We're paused - silence required
1953 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
1955 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1956 *ignore = position - self->audio_expected;
1958 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
1960 AVFormatContext *context = self->audio_format;
1961 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1962 if ( context->start_time != AV_NOPTS_VALUE )
1963 timestamp += context->start_time;
1964 if ( timestamp < 0 )
1967 // Set to the real timecode
1968 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1971 // Clear the usage in the audio buffer
1972 int i = MAX_AUDIO_STREAMS + 1;
1974 self->audio_used[i - 1] = 0;
1980 static int sample_bytes( AVCodecContext *context )
1982 #if LIBAVCODEC_VERSION_MAJOR > 52
1983 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
1985 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
1989 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
1991 // Fetch the audio_format
1992 AVFormatContext *context = self->audio_format;
1994 // Get the current stream index
1995 int index = pkt.stream_index;
1997 // Get codec context
1998 AVCodecContext *codec_context = self->audio_codec[ index ];
2000 // Obtain the resample context if it exists (not always needed)
2001 ReSampleContext *resample = self->audio_resample[ index ];
2003 // Obtain the audio buffers
2004 uint8_t *audio_buffer = self->audio_buffer[ index ];
2005 uint8_t *decode_buffer = self->decode_buffer[ index ];
2007 int audio_used = self->audio_used[ index ];
2008 uint8_t *ptr = pkt.data;
2012 while ( ptr && ret >= 0 && len > 0 )
2014 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2015 int data_size = self->audio_buffer_size[ index ];
2018 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2019 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2020 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2021 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2023 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2027 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2031 pkt.size = len -= ret;
2032 pkt.data = ptr += ret;
2034 // If decoded successfully
2035 if ( data_size > 0 )
2037 // Figure out how many samples will be needed after resampling
2038 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2039 int samples_needed = self->resample_factor * convert_samples;
2041 // Resize audio buffer to prevent overflow
2042 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2044 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2045 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2049 // Copy to audio buffer while resampling
2050 uint8_t *source = decode_buffer;
2051 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2052 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2056 // Straight copy to audio buffer
2057 memcpy( &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ], decode_buffer, data_size );
2058 audio_used += convert_samples;
2062 while ( *ignore && audio_used > samples )
2065 audio_used -= samples;
2066 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2067 audio_used * sizeof_sample );
2072 // If we're behind, ignore this packet
2075 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
2076 int req_position = ( int )( timecode * fps + 0.5 );
2077 int int_position = ( int )( current_pts * fps + 0.5 );
2078 if ( context->start_time != AV_NOPTS_VALUE )
2079 int_position -= ( int )( fps * context->start_time / AV_TIME_BASE + 0.5 );
2081 if ( self->seekable && *ignore == 0 )
2083 if ( int_position < req_position )
2084 // We are behind, so skip some
2086 else if ( int_position > req_position + 2 )
2087 // We are ahead, so seek backwards some more
2088 seek_audio( self, req_position, timecode - 1.0, ignore );
2092 self->audio_used[ index ] = audio_used;
2097 /** Get the audio from a frame.
2099 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2102 producer_avformat self = mlt_frame_pop_audio( frame );
2104 pthread_mutex_lock( &self->audio_mutex );
2106 // Obtain the frame number of this frame
2107 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
2109 // Calculate the real time code
2110 double real_timecode = producer_time_of_frame( self->parent, position );
2112 // Get the producer fps
2113 double fps = mlt_producer_get_fps( self->parent );
2115 // Number of frames to ignore (for ffwd)
2118 // Flag for paused (silence)
2119 int paused = seek_audio( self, position, real_timecode, &ignore );
2121 // Fetch the audio_format
2122 AVFormatContext *context = self->audio_format;
2124 int sizeof_sample = sizeof( int16_t );
2126 // Determine the tracks to use
2127 int index = self->audio_index;
2128 int index_max = self->audio_index + 1;
2129 if ( self->audio_index == INT_MAX )
2132 index_max = context->nb_streams;
2133 *channels = self->total_channels;
2134 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2135 *frequency = FFMAX( self->max_frequency, *frequency );
2138 // Initialize the resamplers and buffers
2139 for ( ; index < index_max; index++ )
2141 // Get codec context
2142 AVCodecContext *codec_context = self->audio_codec[ index ];
2144 if ( codec_context && !self->audio_buffer[ index ] )
2146 // Check for resample and create if necessary
2147 if ( codec_context->channels <= 2 )
2149 // Determine by how much resampling will increase number of samples
2150 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2151 resample_factor *= (double) *frequency / codec_context->sample_rate;
2152 if ( resample_factor > self->resample_factor )
2153 self->resample_factor = resample_factor;
2155 // Create the resampler
2156 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2157 self->audio_resample[ index ] = av_audio_resample_init(
2158 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2159 codec_context->channels, *frequency, codec_context->sample_rate,
2160 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2162 self->audio_resample[ index ] = audio_resample_init(
2163 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2164 codec_context->channels, *frequency, codec_context->sample_rate );
2169 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2170 sizeof_sample = sample_bytes( codec_context );
2173 // Check for audio buffer and create if necessary
2174 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2175 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2177 // Check for decoder buffer and create if necessary
2178 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2182 // Get the audio if required
2189 av_init_packet( &pkt );
2191 // If not resampling, give consumer more than requested.
2192 // It requested number samples based on requested frame rate.
2193 // Do not clean this up with a samples *= ...!
2194 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2195 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2197 while ( ret >= 0 && !got_audio )
2199 // Check if the buffer already contains the samples required
2200 if ( self->audio_index != INT_MAX && self->audio_used[ self->audio_index ] >= *samples && ignore == 0 )
2207 pthread_mutex_lock( &self->packets_mutex );
2208 if ( mlt_deque_count( self->apackets ) )
2210 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2216 ret = av_read_frame( context, &pkt );
2217 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2219 if ( !av_dup_packet( &pkt ) )
2221 AVPacket *tmp = malloc( sizeof(AVPacket) );
2223 mlt_deque_push_back( self->vpackets, tmp );
2227 pthread_mutex_unlock( &self->packets_mutex );
2229 // We only deal with audio from the selected audio index
2230 index = pkt.stream_index;
2231 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2232 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2234 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2235 self->audio_codec[index]->channels : *channels;
2236 ret = decode_audio( self, &ignore, pkt, channels2, *samples, real_timecode, fps );
2239 if ( self->seekable || index != self->video_index )
2240 av_free_packet( &pkt );
2242 if ( self->audio_index == INT_MAX && ret >= 0 )
2244 // Determine if there is enough audio for all streams
2246 for ( index = 0; index < context->nb_streams; index++ )
2248 if ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples )
2254 // Set some additional return values
2255 *format = mlt_audio_s16;
2256 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2258 index = self->audio_index;
2259 *channels = self->audio_codec[ index ]->channels;
2260 *frequency = self->audio_codec[ index ]->sample_rate;
2261 *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2262 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2264 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2266 else if ( self->audio_index == INT_MAX )
2268 // This only works if all audio tracks have the same sample format.
2269 for ( index = 0; index < index_max; index++ )
2270 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2272 *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2273 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2275 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2280 // Allocate and set the frame's audio buffer
2281 int size = mlt_audio_format_size( *format, *samples, *channels );
2282 *buffer = mlt_pool_alloc( size );
2283 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2285 // Interleave tracks if audio_index=all
2286 if ( self->audio_index == INT_MAX )
2288 uint8_t *dest = *buffer;
2290 for ( i = 0; i < *samples; i++ )
2292 for ( index = 0; index < index_max; index++ )
2293 if ( self->audio_codec[ index ] )
2295 int current_channels = self->audio_codec[ index ]->channels;
2296 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2297 memcpy( dest, src, current_channels * sizeof_sample );
2298 dest += current_channels * sizeof_sample;
2301 for ( index = 0; index < index_max; index++ )
2302 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2304 int current_channels = self->audio_codec[ index ]->channels;
2305 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2306 self->audio_used[index] -= *samples;
2307 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2310 // Copy a single track to the output buffer
2313 index = self->audio_index;
2315 // Now handle the audio if we have enough
2316 if ( self->audio_used[ index ] > 0 )
2318 uint8_t *src = self->audio_buffer[ index ];
2319 // copy samples from audio_buffer
2320 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2321 memcpy( *buffer, src, size * *channels * sizeof_sample );
2322 // supply the remaining requested samples as silence
2323 if ( *samples > self->audio_used[ index ] )
2324 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2325 // reposition the samples within audio_buffer
2326 self->audio_used[ index ] -= size;
2327 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2331 // Otherwise fill with silence
2332 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2338 // Get silence and don't touch the context
2339 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2342 // Regardless of speed (other than paused), we expect to get the next frame
2344 self->audio_expected = position + 1;
2346 pthread_mutex_unlock( &self->audio_mutex );
2351 /** Initialize the audio codec context.
2354 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2356 // Initialise the codec if necessary
2357 if ( !self->audio_codec[ index ] )
2359 // Get codec context
2360 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2363 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2365 // If we don't have a codec and we can't initialise it, we can't do much more...
2367 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2369 // Now store the codec with its destructor
2370 if ( self->audio_codec[ index ] )
2371 avcodec_close( self->audio_codec[ index ] );
2372 self->audio_codec[ index ] = codec_context;
2376 // Remember that we can't use self later
2377 self->audio_index = -1;
2381 // Process properties as AVOptions
2382 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2383 #if LIBAVCODEC_VERSION_MAJOR > 52
2384 if ( codec && codec->priv_class && codec_context->priv_data )
2385 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2388 return self->audio_codec[ index ] && self->audio_index > -1;
2391 /** Set up audio handling.
2394 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2397 mlt_producer producer = self->parent;
2399 // Get the properties
2400 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2402 // Fetch the audio format context
2403 AVFormatContext *context = self->audio_format;
2405 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2407 // Get the audio_index
2408 int index = mlt_properties_get_int( properties, "audio_index" );
2410 // Handle all audio tracks
2411 if ( self->audio_index > -1 &&
2412 mlt_properties_get( properties, "audio_index" ) &&
2413 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2416 // Reopen the file if necessary
2417 if ( !context && self->audio_index > -1 && index > -1 )
2419 mlt_events_block( properties, producer );
2420 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2421 mlt_properties_get( properties, "resource" ) );
2422 context = self->audio_format;
2423 if ( self->dummy_context )
2425 av_close_input_file( self->dummy_context );
2426 self->dummy_context = NULL;
2428 mlt_events_unblock( properties, producer );
2429 if ( self->audio_format )
2430 get_audio_streams_info( self );
2433 // Exception handling for audio_index
2434 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2436 for ( index = context->nb_streams - 1;
2437 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2439 mlt_properties_set_int( properties, "audio_index", index );
2441 if ( context && index > -1 && index < INT_MAX &&
2442 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2444 index = self->audio_index;
2445 mlt_properties_set_int( properties, "audio_index", index );
2448 // Update the audio properties if the index changed
2449 if ( context && index > -1 && index != self->audio_index )
2451 if ( self->audio_codec[ self->audio_index ] )
2454 avcodec_close( self->audio_codec[ self->audio_index ] );
2457 self->audio_codec[ self->audio_index ] = NULL;
2459 if ( self->audio_index != -1 )
2460 self->audio_index = index;
2465 if ( context && index == INT_MAX )
2467 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2468 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2469 for ( index = 0; index < context->nb_streams; index++ )
2471 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2472 audio_codec_init( self, index, properties );
2475 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2477 // Set the frame properties
2478 if ( index < INT_MAX )
2480 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2481 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2484 if ( context && index > -1 )
2486 // Add our audio operation
2487 mlt_frame_push_audio( frame, self );
2488 mlt_frame_push_audio( frame, producer_get_audio );
2492 /** Our get frame implementation.
2495 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2497 // Access the private data
2498 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2499 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2500 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2505 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2506 producer->child = self;
2507 self->parent = producer;
2508 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2509 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2512 // Create an empty frame
2513 *frame = mlt_frame_init( service);
2517 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2521 mlt_cache_item_close( cache_item );
2525 // Update timecode on the frame we're creating
2526 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2528 // Set the position of this producer
2529 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
2532 producer_set_up_video( self, *frame );
2535 producer_set_up_audio( self, *frame );
2537 // Calculate the next timecode
2538 mlt_producer_prepare_next( producer );
2543 static void producer_avformat_close( producer_avformat self )
2545 mlt_log_debug( NULL, "producer_avformat_close\n" );
2547 // Cleanup av contexts
2548 av_free( self->av_frame );
2551 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2553 if ( self->audio_resample[i] )
2554 audio_resample_close( self->audio_resample[i] );
2555 mlt_pool_release( self->audio_buffer[i] );
2556 av_free( self->decode_buffer[i] );
2557 if ( self->audio_codec[i] )
2558 avcodec_close( self->audio_codec[i] );
2560 if ( self->video_codec )
2561 avcodec_close( self->video_codec );
2563 if ( self->dummy_context )
2564 av_close_input_file( self->dummy_context );
2565 if ( self->seekable && self->audio_format )
2566 av_close_input_file( self->audio_format );
2567 if ( self->video_format )
2568 av_close_input_file( self->video_format );
2571 vdpau_producer_close( self );
2573 if ( self->image_cache )
2574 mlt_cache_close( self->image_cache );
2576 // Cleanup the mutexes
2577 pthread_mutex_destroy( &self->audio_mutex );
2578 pthread_mutex_destroy( &self->video_mutex );
2579 pthread_mutex_destroy( &self->packets_mutex );
2581 // Cleanup the packet queues
2583 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2585 av_free_packet( pkt );
2588 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2590 av_free_packet( pkt );
2597 static void producer_close( mlt_producer parent )
2599 // Remove this instance from the cache
2600 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2603 parent->close = NULL;
2604 mlt_producer_close( parent );