2 * producer_avformat.c -- avformat producer
3 * Copyright (C) 2003-2012 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>
34 #include <libswscale/swscale.h>
35 #include <libavutil/samplefmt.h>
36 #include <libavutil/pixdesc.h>
39 # include <libavcodec/vdpau.h>
41 #if (LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0))
42 # include <libavutil/dict.h>
45 // System header files
51 #if LIBAVCODEC_VERSION_MAJOR >= 53
52 #include <libavutil/opt.h>
53 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
54 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
55 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
57 #include <libavcodec/opt.h>
60 #define POSITION_INITIAL (-2)
61 #define POSITION_INVALID (-1)
63 #define MAX_AUDIO_STREAMS (32)
64 #define MAX_VDPAU_SURFACES (10)
65 #define MAX_AUDIO_FRAME_SIZE (192000) // 1 second of 48khz 32bit audio
67 struct producer_avformat_s
70 AVFormatContext *dummy_context;
71 AVFormatContext *audio_format;
72 AVFormatContext *video_format;
73 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
74 AVCodecContext *video_codec;
77 mlt_position audio_expected;
78 mlt_position video_expected;
82 int64_t last_position;
84 int64_t current_position;
85 mlt_position nonseek_position;
87 uint8_t *audio_buffer[ MAX_AUDIO_STREAMS ];
88 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
89 uint8_t *decode_buffer[ MAX_AUDIO_STREAMS ];
90 int audio_used[ MAX_AUDIO_STREAMS ];
96 unsigned int invalid_pts_counter;
97 unsigned int invalid_dts_counter;
98 mlt_cache image_cache;
101 pthread_mutex_t video_mutex;
102 pthread_mutex_t audio_mutex;
105 pthread_mutex_t packets_mutex;
106 pthread_mutex_t open_mutex;
108 AVRational video_time_base;
113 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
127 typedef struct producer_avformat_s *producer_avformat;
129 // Forward references.
130 static int list_components( char* file );
131 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock );
132 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
133 static void producer_avformat_close( producer_avformat );
134 static void producer_close( mlt_producer parent );
135 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
136 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
137 static void apply_properties( void *obj, mlt_properties properties, int flags );
138 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
139 static void get_audio_streams_info( producer_avformat self );
140 static mlt_audio_format pick_audio_format( int sample_fmt );
146 /** Constructor for libavformat.
149 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
151 if ( list_components( file ) )
154 mlt_producer producer = NULL;
156 // Check that we have a non-NULL argument
159 // Construct the producer
160 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
161 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
164 if ( mlt_producer_init( producer, self ) == 0 )
166 self->parent = producer;
168 // Get the properties
169 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
171 // Set the resource property (required for all producers)
172 mlt_properties_set( properties, "resource", file );
174 // Register transport implementation with the producer
175 producer->close = (mlt_destructor) producer_close;
177 // Register our get_frame implementation
178 producer->get_frame = producer_get_frame;
180 if ( strcmp( service, "avformat-novalidate" ) )
183 if ( producer_open( self, profile, file, 1 ) != 0 )
186 mlt_producer_close( producer );
188 producer_avformat_close( self );
190 else if ( self->seekable )
192 // Close the file to release resources for large playlists - reopen later as needed
193 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
194 if ( self->audio_format )
195 avformat_close_input( &self->audio_format );
196 if ( self->video_format )
197 avformat_close_input( &self->video_format );
199 if ( self->audio_format )
200 av_close_input_file( self->audio_format );
201 if ( self->video_format )
202 av_close_input_file( self->video_format );
204 self->audio_format = NULL;
205 self->video_format = NULL;
210 // Default the user-selectable indices from the auto-detected indices
211 mlt_properties_set_int( properties, "audio_index", self->audio_index );
212 mlt_properties_set_int( properties, "video_index", self->video_index );
214 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
216 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
223 int list_components( char* file )
227 // Report information about available demuxers and codecs as YAML Tiny
228 if ( file && strstr( file, "f-list" ) )
230 fprintf( stderr, "---\nformats:\n" );
231 AVInputFormat *format = NULL;
232 while ( ( format = av_iformat_next( format ) ) )
233 fprintf( stderr, " - %s\n", format->name );
234 fprintf( stderr, "...\n" );
237 if ( file && strstr( file, "acodec-list" ) )
239 fprintf( stderr, "---\naudio_codecs:\n" );
240 AVCodec *codec = NULL;
241 while ( ( codec = av_codec_next( codec ) ) )
242 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
243 fprintf( stderr, " - %s\n", codec->name );
244 fprintf( stderr, "...\n" );
247 if ( file && strstr( file, "vcodec-list" ) )
249 fprintf( stderr, "---\nvideo_codecs:\n" );
250 AVCodec *codec = NULL;
251 while ( ( codec = av_codec_next( codec ) ) )
252 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
253 fprintf( stderr, " - %s\n", codec->name );
254 fprintf( stderr, "...\n" );
261 static int first_video_index( producer_avformat self )
263 AVFormatContext *context = self->video_format? self->video_format : self->audio_format;
264 int i = -1; // not found
267 for ( i = 0; i < context->nb_streams; i++ ) {
268 if ( context->streams[i]->codec &&
269 context->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
272 if ( i == context->nb_streams )
278 /** Find the default streams.
281 static mlt_properties find_default_streams( producer_avformat self )
285 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
286 AVDictionaryEntry *tag = NULL;
288 AVMetadataTag *tag = NULL;
290 AVFormatContext *context = self->video_format;
291 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
293 // Default to the first audio and video streams found
294 self->audio_index = -1;
295 self->video_index = -1;
297 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
299 // Allow for multiple audio and video streams in the file and select first of each (if available)
300 for( i = 0; i < context->nb_streams; i++ )
302 // Get the codec context
303 AVStream *stream = context->streams[ i ];
304 if ( ! stream ) continue;
305 AVCodecContext *codec_context = stream->codec;
306 if ( ! codec_context ) continue;
307 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
308 if ( ! codec ) continue;
310 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
312 // Determine the type and obtain the first index of each type
313 switch( codec_context->codec_type )
315 case CODEC_TYPE_VIDEO:
316 // Use first video stream
317 if ( self->video_index < 0 )
318 self->video_index = i;
319 mlt_properties_set( meta_media, key, "video" );
320 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
321 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
322 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
323 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
324 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
326 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
327 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
328 snprintf( key, sizeof(key), "meta.media.%d.codec.width", i );
329 mlt_properties_set_int( meta_media, key, codec_context->width );
330 snprintf( key, sizeof(key), "meta.media.%d.codec.height", i );
331 mlt_properties_set_int( meta_media, key, codec_context->height );
332 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
333 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
334 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
335 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
336 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(3<<8)+0)
337 mlt_properties_set( meta_media, key, av_get_pix_fmt_name( codec_context->pix_fmt ) );
339 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
341 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
342 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
343 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
344 switch ( codec_context->colorspace )
346 case AVCOL_SPC_SMPTE240M:
347 mlt_properties_set_int( meta_media, key, 240 );
349 case AVCOL_SPC_BT470BG:
350 case AVCOL_SPC_SMPTE170M:
351 mlt_properties_set_int( meta_media, key, 601 );
353 case AVCOL_SPC_BT709:
354 mlt_properties_set_int( meta_media, key, 709 );
357 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
358 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
362 case CODEC_TYPE_AUDIO:
363 if ( !codec_context->channels )
365 // Use first audio stream
366 if ( self->audio_index < 0 && pick_audio_format( codec_context->sample_fmt ) != mlt_audio_none )
367 self->audio_index = i;
369 mlt_properties_set( meta_media, key, "audio" );
370 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
371 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
372 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
373 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
374 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
375 mlt_properties_set_int( meta_media, key, codec_context->channels );
380 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
381 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
382 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
383 mlt_properties_set( meta_media, key, codec->name );
384 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
385 mlt_properties_set( meta_media, key, codec->long_name );
386 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
387 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
388 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
389 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
390 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
391 // mlt_properties_set_int( meta_media, key, codec_context->profile );
392 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
393 // mlt_properties_set_int( meta_media, key, codec_context->level );
396 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
397 while ( ( tag = av_dict_get( stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
399 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
402 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
404 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
405 mlt_properties_set( meta_media, key, tag->value );
409 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
410 while ( ( tag = av_dict_get( context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
412 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
415 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
417 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
418 mlt_properties_set( meta_media, key, tag->value );
425 static inline int dv_is_pal( AVPacket *pkt )
427 return pkt->data[3] & 0x80;
430 static int dv_is_wide( AVPacket *pkt )
432 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
434 for ( ; i < pkt->size; i += 5 /* packet size */ )
436 if ( pkt->data[ i ] == 0x61 )
438 uint8_t x = pkt->data[ i + 2 ] & 0x7;
439 return ( x == 2 ) || ( x == 7 );
445 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
447 double aspect_ratio = 1.0;
449 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
453 if ( dv_is_pal( pkt ) )
455 if ( dv_is_wide( pkt ) )
457 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
458 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
462 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
463 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
468 if ( dv_is_wide( pkt ) )
470 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
471 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
475 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
476 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
482 AVRational ar = stream->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 = stream->sample_aspect_ratio;
519 if ( codec_sar.num > 0 )
521 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
522 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
524 else if ( stream_sar.num > 0 )
526 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
527 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
531 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
532 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
535 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
536 aspect_ratio = av_q2d( ar );
537 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
542 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
543 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVDictionary **params )
545 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
548 if ( !URL ) return NULL;
551 char *protocol = strdup( URL );
552 char *url = strchr( protocol, ':' );
554 // Only if there is not a protocol specification that avformat can handle
555 #if LIBAVFORMAT_VERSION_MAJOR >= 53
556 if ( url && avio_check( URL, 0 ) < 0 )
558 if ( url && !url_exist( URL ) )
561 // Truncate protocol string
563 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
566 *format = av_find_input_format( protocol );
568 // Eat the format designator
573 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
574 // support for legacy width and height parameters
578 // These are required by video4linux2 (defaults)
579 params->width = profile->width;
580 params->height = profile->height;
581 if ( !strstr( URL, "&frame_rate" ) )
582 params->time_base = (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
583 params->channels = 2;
584 params->sample_rate = 48000;
588 url = strchr( url, '?' );
592 char *name = strdup( ++url );
593 char *value = strchr( name, '=' );
595 // Also accept : as delimiter for backwards compatibility.
596 value = strchr( name, ':' );
601 char *t = strchr( value, '&' );
604 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
605 // translate old parameters to new av_dict names
606 if ( !strcmp( name, "frame_rate" ) )
607 av_dict_set( params, "framerate", value, 0 );
608 else if ( !strcmp( name, "pix_fmt" ) )
609 av_dict_set( params, "pixel_format", value, 0 );
610 else if ( !strcmp( name, "width" ) )
611 width = strdup( value );
612 else if ( !strcmp( name, "height" ) )
613 height = strdup( value );
615 // generic demux/device option support
616 av_dict_set( params, name, value, 0 );
618 if ( !strcmp( name, "frame_rate" ) )
619 params->time_base.den = atoi( value );
620 else if ( !strcmp( name, "frame_rate_base" ) )
621 params->time_base.num = atoi( value );
622 else if ( !strcmp( name, "sample_rate" ) )
623 params->sample_rate = atoi( value );
624 else if ( !strcmp( name, "channel" ) )
625 params->channel = atoi( value );
626 else if ( !strcmp( name, "channels" ) )
627 params->channels = atoi( value );
628 else if ( !strcmp( name, "pix_fmt" ) )
629 params->pix_fmt = av_get_pix_fmt( value );
630 else if ( !strcmp( name, "width" ) )
631 params->width = atoi( value );
632 else if ( !strcmp( name, "height" ) )
633 params->height = atoi( value );
634 else if ( !strcmp( name, "standard" ) )
635 params->standard = strdup( value );
639 url = strchr( url, '&' );
641 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
642 // continued support for legacy width and height parameters
643 if ( width && height )
645 char *s = malloc( strlen( width ) + strlen( height ) + 2 );
649 av_dict_set( params, "video_size", s, 0 );
652 if ( width ) free( width );
653 if ( height ) free ( height );
656 result = strdup( result );
660 result = strdup( URL );
666 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
670 // Get the properties
671 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
673 AVFormatContext *format = self->video_format;
675 // We will treat everything with the producer fps.
676 // TODO: make this more flexible.
677 double fps = mlt_profile_fps( profile );
680 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
682 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
683 // when producer_open is called after initial call when restoring or reseting the producer.
684 if ( format->duration != AV_NOPTS_VALUE )
686 // This isn't going to be accurate for all formats
687 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
688 mlt_properties_set_position( properties, "out", frames - 1 );
689 mlt_properties_set_position( properties, "length", frames );
690 mlt_properties_set_int( properties, "_length_computed", 1 );
694 // Set live sources to run forever
695 mlt_properties_set_position( properties, "length", INT_MAX );
696 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
697 mlt_properties_set( properties, "eof", "loop" );
698 mlt_properties_set_int( properties, "_length_computed", 1 );
702 // Check if we're seekable
703 // avdevices are typically AVFMT_NOFILE and not seekable
704 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
707 // protocols can indicate if they support seeking
708 #if LIBAVFORMAT_VERSION_MAJOR >= 53
709 self->seekable = format->pb->seekable;
711 URLContext *uc = url_fileno( format->pb );
713 self->seekable = !uc->is_streamed;
716 if ( self->seekable )
718 // Do a more rigourous test of seekable on a disposable context
719 self->seekable = av_seek_frame( format, -1, format->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
720 mlt_properties_set_int( properties, "seekable", self->seekable );
721 self->dummy_context = format;
722 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
723 self->video_format = NULL;
724 avformat_open_input( &self->video_format, filename, NULL, NULL );
725 avformat_find_stream_info( self->video_format, NULL );
727 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
728 av_find_stream_info( self->video_format );
730 format = self->video_format;
733 // Fetch the width, height and aspect ratio
734 if ( self->video_index != -1 )
736 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
737 mlt_properties_set_int( properties, "width", codec_context->width );
738 mlt_properties_set_int( properties, "height", codec_context->height );
740 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
742 // Fetch the first frame of DV so we can read it directly
747 ret = av_read_frame( format, &pkt );
748 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
750 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
751 av_free_packet(&pkt);
755 av_free_packet(&pkt);
760 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
763 // Verify that we can convert this to YUV 4:2:2
764 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
765 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
766 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
768 sws_freeContext( context );
778 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
780 // Return an error code (0 == no error)
782 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
787 if ( !self->is_mutex_init )
789 pthread_mutex_init( &self->audio_mutex, NULL );
790 pthread_mutex_init( &self->video_mutex, NULL );
791 pthread_mutex_init( &self->packets_mutex, NULL );
792 pthread_mutex_init( &self->open_mutex, NULL );
793 self->is_mutex_init = 1;
795 pthread_mutex_lock( &self->audio_mutex );
796 pthread_mutex_lock( &self->video_mutex );
798 mlt_events_block( properties, self->parent );
801 AVInputFormat *format = NULL;
802 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
803 AVDictionary *params = NULL;
805 AVFormatParameters params;
806 memset( ¶ms, 0, sizeof(params) );
808 char *filename = parse_url( profile, URL, &format, ¶ms );
810 // Now attempt to open the file or device with filename
811 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
812 error = avformat_open_input( &self->video_format, filename, format, ¶ms ) < 0;
814 // If the URL is a network stream URL, then we probably need to open with full URL
815 error = avformat_open_input( &self->video_format, URL, format, ¶ms ) < 0;
817 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
819 // If the URL is a network stream URL, then we probably need to open with full URL
820 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
823 // Set MLT properties onto video AVFormatContext
824 if ( !error && self->video_format )
826 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
827 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
828 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
831 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
832 av_dict_free( ¶ms );
834 // Cleanup AVFormatParameters
835 if ( params.standard )
836 free( (void*) params.standard );
839 // If successful, then try to get additional info
840 if ( !error && self->video_format )
842 // Get the stream info
843 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
844 error = avformat_find_stream_info( self->video_format, NULL ) < 0;
846 error = av_find_stream_info( self->video_format ) < 0;
849 // Continue if no error
850 if ( !error && self->video_format )
852 // Find default audio and video streams
853 find_default_streams( self );
854 error = get_basic_info( self, profile, filename );
856 // Initialize position info
857 self->first_pts = AV_NOPTS_VALUE;
858 self->last_position = POSITION_INITIAL;
860 if ( !self->audio_format )
862 // We're going to cheat here - for seekable A/V files, we will have separate contexts
863 // to support independent seeking of audio from video.
864 // TODO: Is this really necessary?
865 if ( self->audio_index != -1 && self->video_index != -1 )
867 if ( self->seekable )
869 // And open again for our audio context
870 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
871 avformat_open_input( &self->audio_format, filename, NULL, NULL );
872 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
873 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
874 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
875 avformat_find_stream_info( self->audio_format, NULL );
877 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
878 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
879 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
880 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
881 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
883 av_find_stream_info( self->audio_format );
888 self->audio_format = self->video_format;
891 else if ( self->audio_index != -1 )
893 // We only have an audio context
894 self->audio_format = self->video_format;
895 self->video_format = NULL;
897 else if ( self->video_index == -1 )
899 // Something has gone wrong
902 if ( self->audio_format && !self->audio_streams )
903 get_audio_streams_info( self );
911 self->apackets = mlt_deque_init();
912 self->vpackets = mlt_deque_init();
915 if ( self->dummy_context )
917 pthread_mutex_lock( &self->open_mutex );
918 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
919 avformat_close_input( &self->dummy_context );
921 av_close_input_file( self->dummy_context );
923 self->dummy_context = NULL;
924 pthread_mutex_unlock( &self->open_mutex );
927 // Unlock the service
930 pthread_mutex_unlock( &self->audio_mutex );
931 pthread_mutex_unlock( &self->video_mutex );
933 mlt_events_unblock( properties, self->parent );
938 static void reopen_video( producer_avformat self, mlt_producer producer )
940 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
941 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
942 pthread_mutex_lock( &self->audio_mutex );
943 pthread_mutex_lock( &self->open_mutex );
945 if ( self->video_codec )
946 avcodec_close( self->video_codec );
947 self->video_codec = NULL;
948 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
949 if ( self->dummy_context )
950 avformat_close_input( &self->dummy_context );
951 if ( self->video_format )
952 avformat_close_input( &self->video_format );
954 if ( self->dummy_context )
955 av_close_input_file( self->dummy_context );
956 if ( self->video_format )
957 av_close_input_file( self->video_format );
959 self->dummy_context = NULL;
960 self->video_format = NULL;
961 pthread_mutex_unlock( &self->open_mutex );
963 int audio_index = self->audio_index;
964 int video_index = self->video_index;
966 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
967 mlt_properties_get( properties, "resource" ), 0 );
969 self->audio_index = audio_index;
970 if ( self->video_format && video_index > -1 )
972 self->video_index = video_index;
973 video_codec_init( self, video_index, properties );
976 pthread_mutex_unlock( &self->audio_mutex );
977 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
980 static int64_t best_pts( producer_avformat self, int64_t pts, int64_t dts )
982 self->invalid_pts_counter += pts == AV_NOPTS_VALUE;
983 self->invalid_dts_counter += dts == AV_NOPTS_VALUE;
984 if ( ( self->invalid_pts_counter <= self->invalid_dts_counter
985 || dts == AV_NOPTS_VALUE ) && pts != AV_NOPTS_VALUE )
991 static void find_first_pts( producer_avformat self, int video_index )
994 AVFormatContext *context = self->video_format? self->video_format : self->audio_format;
999 while ( ret >= 0 && toscan-- > 0 )
1001 ret = av_read_frame( context, &pkt );
1002 if ( ret >= 0 && pkt.stream_index == video_index && ( pkt.flags & PKT_FLAG_KEY ) )
1004 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
1005 "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n",
1006 pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
1007 self->first_pts = best_pts( self, pkt.pts, pkt.dts );
1008 if ( self->first_pts != AV_NOPTS_VALUE )
1011 av_free_packet( &pkt );
1013 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1016 static int seek_video( producer_avformat self, mlt_position position,
1017 int64_t req_position, int preseek )
1019 mlt_producer producer = self->parent;
1022 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
1024 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1026 // Fetch the video format context
1027 AVFormatContext *context = self->video_format;
1029 // Get the video stream
1030 AVStream *stream = context->streams[ self->video_index ];
1032 // Get codec context
1033 AVCodecContext *codec_context = stream->codec;
1035 // We may want to use the source fps if available
1036 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1037 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1039 if ( self->last_position == POSITION_INITIAL )
1040 find_first_pts( self, self->video_index );
1042 if ( self->av_frame && position + 1 == self->video_expected )
1044 // We're paused - use last image
1047 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
1049 // Calculate the timestamp for the requested frame
1050 int64_t timestamp = req_position / ( av_q2d( self->video_time_base ) * source_fps );
1051 if ( req_position <= 0 )
1053 else if ( self->first_pts != AV_NOPTS_VALUE )
1054 timestamp += self->first_pts;
1055 else if ( context->start_time != AV_NOPTS_VALUE )
1056 timestamp += context->start_time;
1057 if ( preseek && av_q2d( self->video_time_base ) != 0 )
1058 timestamp -= 2 / av_q2d( self->video_time_base );
1059 if ( timestamp < 0 )
1061 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
1062 timestamp, position, self->video_expected, self->last_position );
1064 // Seek to the timestamp
1065 // NOTE: reopen_video is disabled at this time because it is causing trouble with A/V sync.
1066 if ( 1 || req_position > 0 || self->last_position <= 0 )
1068 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1069 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1071 // flush any pictures still in decode buffer
1072 avcodec_flush_buffers( codec_context );
1076 // Re-open video stream when rewinding to beginning from somewhere else.
1077 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1078 // not reliably seeking to the first frame across formats.
1079 reopen_video( self, producer );
1082 // Remove the cached info relating to the previous position
1083 self->current_position = POSITION_INVALID;
1084 self->last_position = POSITION_INVALID;
1085 av_freep( &self->av_frame );
1091 /** Convert a frame position to a time code.
1094 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1096 return ( double )position / mlt_producer_get_fps( producer );
1099 // Collect information about all audio streams
1101 static void get_audio_streams_info( producer_avformat self )
1103 // Fetch the audio format context
1104 AVFormatContext *context = self->audio_format;
1108 i < context->nb_streams;
1111 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1113 AVCodecContext *codec_context = context->streams[i]->codec;
1114 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1116 // If we don't have a codec and we can't initialise it, we can't do much more...
1117 pthread_mutex_lock( &self->open_mutex );
1118 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1119 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1121 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1124 self->audio_streams++;
1125 self->audio_max_stream = i;
1126 self->total_channels += codec_context->channels;
1127 if ( codec_context->channels > self->max_channel )
1128 self->max_channel = codec_context->channels;
1129 if ( codec_context->sample_rate > self->max_frequency )
1130 self->max_frequency = codec_context->sample_rate;
1131 avcodec_close( codec_context );
1133 pthread_mutex_unlock( &self->open_mutex );
1136 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1137 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1140 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1143 const int *new_coefficients;
1145 int brightness, contrast, saturation;
1147 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1148 &brightness, &contrast, &saturation ) != -1 )
1150 // Don't change these from defaults unless explicitly told to.
1151 if ( use_full_range >= 0 )
1152 full_range = use_full_range;
1153 switch ( colorspace )
1159 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1162 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1165 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1168 new_coefficients = coefficients;
1171 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1172 brightness, contrast, saturation );
1176 static mlt_image_format pick_pix_format( enum PixelFormat pix_fmt )
1184 return mlt_image_rgb24a;
1185 case PIX_FMT_YUV420P:
1186 case PIX_FMT_YUVJ420P:
1187 case PIX_FMT_YUVA420P:
1188 return mlt_image_yuv420p;
1192 case PIX_FMT_MONOWHITE:
1193 case PIX_FMT_MONOBLACK:
1196 return mlt_image_rgb24;
1198 return mlt_image_yuv422;
1202 static mlt_audio_format pick_audio_format( int sample_fmt )
1204 switch ( sample_fmt )
1207 case AV_SAMPLE_FMT_U8:
1208 return mlt_audio_u8;
1209 case AV_SAMPLE_FMT_S16:
1210 return mlt_audio_s16;
1211 case AV_SAMPLE_FMT_S32:
1212 return mlt_audio_s32le;
1213 case AV_SAMPLE_FMT_FLT:
1214 return mlt_audio_f32le;
1215 // planar - this producer converts planar to interleaved
1216 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1217 case AV_SAMPLE_FMT_U8P:
1218 return mlt_audio_u8;
1219 case AV_SAMPLE_FMT_S16P:
1220 return mlt_audio_s16;
1221 case AV_SAMPLE_FMT_S32P:
1222 return mlt_audio_s32le;
1223 case AV_SAMPLE_FMT_FLTP:
1224 return mlt_audio_f32le;
1227 return mlt_audio_none;
1231 static void convert_image( producer_avformat self, AVFrame *frame, uint8_t *buffer, int pix_fmt,
1232 mlt_image_format *format, int width, int height, uint8_t **alpha )
1234 int flags = SWS_BICUBIC | SWS_ACCURATE_RND;
1237 flags |= SWS_CPU_CAPS_MMX;
1240 flags |= SWS_CPU_CAPS_MMX2;
1243 // extract alpha from planar formats
1244 if ( ( pix_fmt == PIX_FMT_YUVA420P
1245 #if defined(FFUDIV) && LIBAVUTIL_VERSION_INT >= ((51<<16)+(35<<8)+101)
1246 || pix_fmt == PIX_FMT_YUVA444P
1249 *format != mlt_image_rgb24a && *format != mlt_image_opengl &&
1250 frame->data[3] && frame->linesize[3] )
1255 dst = *alpha = mlt_pool_alloc( width * height );
1256 src = frame->data[3];
1258 for ( i = 0; i < height; dst += width, src += frame->linesize[3], i++ )
1259 memcpy( dst, src, FFMIN( width, frame->linesize[3] ) );
1262 if ( *format == mlt_image_yuv420p )
1264 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1265 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1267 output.data[0] = buffer;
1268 output.data[1] = buffer + width * height;
1269 output.data[2] = buffer + ( 5 * width * height ) / 4;
1270 output.linesize[0] = width;
1271 output.linesize[1] = width >> 1;
1272 output.linesize[2] = width >> 1;
1273 set_luma_transfer( context, self->colorspace, -1 );
1274 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1275 output.data, output.linesize);
1276 sws_freeContext( context );
1278 else if ( *format == mlt_image_rgb24 )
1280 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1281 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1283 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1284 set_luma_transfer( context, self->colorspace, self->full_luma );
1285 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1286 output.data, output.linesize);
1287 sws_freeContext( context );
1289 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1291 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1292 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1294 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1295 set_luma_transfer( context, self->colorspace, self->full_luma );
1296 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1297 output.data, output.linesize);
1298 sws_freeContext( context );
1302 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1303 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1305 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1306 set_luma_transfer( context, self->colorspace, -1 );
1307 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1308 output.data, output.linesize);
1309 sws_freeContext( context );
1313 /** Allocate the image buffer and set it on the frame.
1316 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1320 if ( codec_context->width == 0 || codec_context->height == 0 )
1323 if ( *format == mlt_image_glsl )
1324 *format = pick_pix_format( codec_context->pix_fmt );
1326 *width = codec_context->width;
1327 *height = codec_context->height;
1328 size = mlt_image_format_size( *format, *width, *height, NULL );
1329 *buffer = mlt_pool_alloc( size );
1331 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1338 /** Get an image from a frame.
1341 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1344 producer_avformat self = mlt_frame_pop_service( frame );
1345 mlt_producer producer = self->parent;
1347 // Get the properties from the frame
1348 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1350 // Obtain the frame number of this frame
1351 mlt_position position = mlt_frame_original_position( frame );
1353 // Get the producer properties
1354 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1356 pthread_mutex_lock( &self->video_mutex );
1358 // Fetch the video format context
1359 AVFormatContext *context = self->video_format;
1361 // Get the video stream
1362 AVStream *stream = context->streams[ self->video_index ];
1364 // Get codec context
1365 AVCodecContext *codec_context = stream->codec;
1367 uint8_t *alpha = NULL;
1368 int got_picture = 0;
1371 // Get the image cache
1372 if ( ! self->image_cache )
1374 // if cache size supplied by environment variable
1375 int cache_supplied = getenv( "MLT_AVFORMAT_CACHE" ) != NULL;
1376 int cache_size = cache_supplied? atoi( getenv( "MLT_AVFORMAT_CACHE" ) ) : 0;
1378 // cache size supplied via property
1379 if ( mlt_properties_get( properties, "cache" ) )
1382 cache_size = mlt_properties_get_int( properties, "cache" );
1384 if ( mlt_properties_get_int( properties, "noimagecache" ) )
1386 // create cache if not disabled
1387 if ( !cache_supplied || cache_size > 0 )
1388 self->image_cache = mlt_cache_init();
1389 // set cache size if supplied
1390 if ( self->image_cache && cache_supplied )
1391 mlt_cache_set_size( self->image_cache, cache_size );
1393 if ( self->image_cache )
1395 mlt_frame original = mlt_cache_get_frame( self->image_cache, position );
1398 mlt_properties orig_props = MLT_FRAME_PROPERTIES( original );
1401 *buffer = mlt_properties_get_data( orig_props, "alpha", &size );
1403 mlt_frame_set_alpha( frame, *buffer, size, NULL );
1404 *buffer = mlt_properties_get_data( orig_props, "image", &size );
1405 mlt_frame_set_image( frame, *buffer, size, NULL );
1406 mlt_properties_set_data( frame_properties, "avformat.image_cache", original, 0, (mlt_destructor) mlt_frame_close, NULL );
1407 *format = mlt_properties_get_int( orig_props, "format" );
1409 // Set the resolution
1410 *width = codec_context->width;
1411 *height = codec_context->height;
1413 // Workaround 1088 encodings missing cropping info.
1414 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1418 goto exit_get_image;
1423 // We may want to use the source fps if available
1424 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1425 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1427 // This is the physical frame position in the source
1428 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1430 // Determines if we have to decode all frames in a sequence
1431 // Temporary hack to improve intra frame only
1432 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1433 strcmp( codec_context->codec->name, "dnxhd" ) &&
1434 strcmp( codec_context->codec->name, "dvvideo" ) &&
1435 strcmp( codec_context->codec->name, "huffyuv" ) &&
1436 strcmp( codec_context->codec->name, "mjpeg" ) &&
1437 strcmp( codec_context->codec->name, "rawvideo" ) );
1439 double delay = mlt_properties_get_double( properties, "video_delay" );
1441 // Seek if necessary
1442 const char *interp = mlt_properties_get( frame_properties, "rescale.interp" );
1443 int preseek = must_decode
1444 #if defined(FFUDIV) && LIBAVFORMAT_VERSION_INT >= ((53<<16)+(24<<8)+2)
1445 && ( interp && strcmp( interp, "nearest" ) )
1447 && codec_context->has_b_frames;
1448 int paused = seek_video( self, position, req_position, preseek );
1450 // Seek might have reopened the file
1451 context = self->video_format;
1452 stream = context->streams[ self->video_index ];
1453 codec_context = stream->codec;
1454 if ( *format == mlt_image_none ||
1455 codec_context->pix_fmt == PIX_FMT_ARGB ||
1456 codec_context->pix_fmt == PIX_FMT_RGBA ||
1457 codec_context->pix_fmt == PIX_FMT_ABGR ||
1458 codec_context->pix_fmt == PIX_FMT_BGRA )
1459 *format = pick_pix_format( codec_context->pix_fmt );
1461 // Duplicate the last image if necessary
1462 if ( self->av_frame && self->av_frame->linesize[0]
1463 && ( paused || self->current_position >= req_position ) )
1466 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1468 // Workaround 1088 encodings missing cropping info.
1469 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1472 if ( self->vdpau && self->vdpau->buffer )
1475 picture.data[0] = self->vdpau->buffer;
1476 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1477 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1478 picture.linesize[0] = codec_context->width;
1479 picture.linesize[1] = codec_context->width / 2;
1480 picture.linesize[2] = codec_context->width / 2;
1481 convert_image( self, (AVFrame*) &picture, *buffer,
1482 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1486 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1487 format, *width, *height, &alpha );
1494 int64_t int_position = 0;
1495 int decode_errors = 0;
1497 // Construct an AVFrame for YUV422 conversion
1498 if ( !self->av_frame )
1499 self->av_frame = avcodec_alloc_frame( );
1501 while( ret >= 0 && !got_picture )
1504 if ( self->pkt.stream_index == self->video_index )
1505 av_free_packet( &self->pkt );
1506 av_init_packet( &self->pkt );
1507 pthread_mutex_lock( &self->packets_mutex );
1508 if ( mlt_deque_count( self->vpackets ) )
1510 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1516 ret = av_read_frame( context, &self->pkt );
1517 if ( ret >= 0 && !self->seekable && self->pkt.stream_index == self->audio_index )
1519 if ( !av_dup_packet( &self->pkt ) )
1521 AVPacket *tmp = malloc( sizeof(AVPacket) );
1523 mlt_deque_push_back( self->apackets, tmp );
1527 pthread_mutex_unlock( &self->packets_mutex );
1529 // We only deal with video from the selected video_index
1530 if ( ret >= 0 && self->pkt.stream_index == self->video_index && self->pkt.size > 0 )
1532 int64_t pts = best_pts( self, self->pkt.pts, self->pkt.dts );
1533 if ( pts != AV_NOPTS_VALUE )
1535 if ( !self->seekable && self->first_pts == AV_NOPTS_VALUE )
1536 self->first_pts = pts;
1537 if ( self->first_pts != AV_NOPTS_VALUE )
1538 pts -= self->first_pts;
1539 else if ( context->start_time != AV_NOPTS_VALUE )
1540 pts -= context->start_time;
1541 int_position = ( int64_t )( ( av_q2d( self->video_time_base ) * pts + delay ) * source_fps + 0.5 );
1542 if ( int_position == self->last_position )
1543 int_position = self->last_position + 1;
1545 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1546 "V pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1547 self->pkt.pts, self->pkt.dts, req_position, self->current_position, int_position );
1549 // Make a dumb assumption on streams that contain wild timestamps
1550 if ( abs( req_position - int_position ) > 999 )
1552 int_position = req_position;
1553 mlt_log_warning( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!\n" );
1555 self->last_position = int_position;
1558 if ( must_decode || int_position >= req_position )
1563 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1565 vdpau_decoder_init( self );
1567 self->vdpau->is_decoded = 0;
1570 codec_context->reordered_opaque = int_position;
1571 if ( int_position >= req_position )
1572 codec_context->skip_loop_filter = AVDISCARD_NONE;
1573 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1574 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &self->pkt );
1576 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, self->pkt.data, self->pkt.size );
1578 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1581 if ( ++decode_errors <= 10 )
1592 // Get position of reordered frame
1593 int_position = self->av_frame->reordered_opaque;
1594 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(106<<8)+0))
1595 pts = best_pts( self, self->av_frame->pkt_pts, self->av_frame->pkt_dts );
1596 if ( pts != AV_NOPTS_VALUE )
1598 if ( self->first_pts != AV_NOPTS_VALUE )
1599 pts -= self->first_pts;
1600 else if ( context->start_time != AV_NOPTS_VALUE )
1601 pts -= context->start_time;
1602 int_position = ( int64_t )( ( av_q2d( self->video_time_base ) * pts + delay ) * source_fps + 0.5 );
1606 if ( int_position < req_position )
1608 else if ( int_position >= req_position )
1609 codec_context->skip_loop_filter = AVDISCARD_NONE;
1611 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, self->pkt.flags & PKT_FLAG_KEY );
1614 // Now handle the picture if we have one
1617 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1619 // Workaround 1088 encodings missing cropping info.
1620 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1625 if ( self->vdpau->is_decoded )
1627 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1629 uint32_t pitches[3];
1630 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1632 if ( !self->vdpau->buffer )
1633 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1634 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1635 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1636 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1637 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1638 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1639 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1641 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1642 if ( status == VDP_STATUS_OK )
1644 convert_image( self, self->av_frame, *buffer, PIX_FMT_YUV420P,
1645 format, *width, *height, &alpha );
1649 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1650 image_size = self->vdpau->is_decoded = 0;
1655 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1656 image_size = got_picture = 0;
1661 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1662 format, *width, *height, &alpha );
1663 self->top_field_first |= self->av_frame->top_field_first;
1664 self->current_position = int_position;
1672 // Free packet data if not video and not live audio packet
1673 if ( self->pkt.stream_index != self->video_index &&
1674 !( !self->seekable && self->pkt.stream_index == self->audio_index ) )
1675 av_free_packet( &self->pkt );
1681 mlt_frame_set_alpha( frame, alpha, (*width) * (*height), mlt_pool_release );
1683 if ( image_size > 0 && self->image_cache )
1685 mlt_properties_set_int( frame_properties, "format", *format );
1686 mlt_cache_put_frame( self->image_cache, frame );
1689 // Try to duplicate last image if there was a decoding failure
1690 // TODO: with multithread decoding a partial frame decoding resulting
1691 // in failure also resets av_frame making test below fail.
1692 if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1695 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1697 // Workaround 1088 encodings missing cropping info.
1698 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1701 if ( self->vdpau && self->vdpau->buffer )
1704 picture.data[0] = self->vdpau->buffer;
1705 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1706 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1707 picture.linesize[0] = codec_context->width;
1708 picture.linesize[1] = codec_context->width / 2;
1709 picture.linesize[2] = codec_context->width / 2;
1710 convert_image( self, (AVFrame*) &picture, *buffer,
1711 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1715 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1716 format, *width, *height, &alpha );
1721 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1722 self->video_expected = position + 1;
1726 pthread_mutex_unlock( &self->video_mutex );
1728 // Set the progressive flag
1729 if ( mlt_properties_get( properties, "force_progressive" ) )
1730 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1731 else if ( self->av_frame )
1732 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1734 // Set the field order property for this frame
1735 if ( mlt_properties_get( properties, "force_tff" ) )
1736 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1738 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1740 // Set immutable properties of the selected track's (or overridden) source attributes.
1741 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1742 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1743 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1744 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1746 // If we already have RGB, then the full range processing either happened already
1747 // or does not apply (RGB source).
1748 if ( *format == mlt_image_rgb24 || *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1749 mlt_properties_set( frame_properties, "force_full_luma", NULL );
1751 return !got_picture;
1754 /** Process properties as AVOptions and apply to AV context obj
1757 static void apply_properties( void *obj, mlt_properties properties, int flags )
1760 int count = mlt_properties_count( properties );
1761 for ( i = 0; i < count; i++ )
1763 const char *opt_name = mlt_properties_get_name( properties, i );
1764 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
1765 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1767 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1769 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1772 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1773 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1774 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1775 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1776 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1777 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1779 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1785 /** Initialize the video codec context.
1788 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1790 // Initialise the codec if necessary
1791 if ( !self->video_codec )
1793 // Get the video stream
1794 AVStream *stream = self->video_format->streams[ index ];
1796 // Get codec context
1797 AVCodecContext *codec_context = stream->codec;
1800 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1802 if ( codec_context->codec_id == CODEC_ID_H264 )
1804 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1806 if ( vdpau_init( self ) )
1808 self->video_codec = codec_context;
1809 if ( !vdpau_decoder_init( self ) )
1814 codec = avcodec_find_decoder( codec_context->codec_id );
1818 // Initialise multi-threading
1819 int thread_count = mlt_properties_get_int( properties, "threads" );
1820 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1821 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1822 if ( thread_count > 1 )
1823 codec_context->thread_count = thread_count;
1825 // If we don't have a codec and we can't initialise it, we can't do much more...
1826 pthread_mutex_lock( &self->open_mutex );
1827 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1828 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1830 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1833 // Now store the codec with its destructor
1834 self->video_codec = codec_context;
1838 // Remember that we can't use this later
1839 self->video_index = -1;
1840 pthread_mutex_unlock( &self->open_mutex );
1843 pthread_mutex_unlock( &self->open_mutex );
1845 // Process properties as AVOptions
1846 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1847 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1848 if ( codec->priv_class && codec_context->priv_data )
1849 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1852 // Reset some image properties
1853 if ( self->video_codec )
1855 mlt_properties_set_int( properties, "width", self->video_codec->width );
1856 mlt_properties_set_int( properties, "height", self->video_codec->height );
1858 // For DV, we'll just use the saved aspect ratio
1859 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1860 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1862 // Determine the fps first from the codec
1863 double source_fps = (double) self->video_codec->time_base.den /
1864 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1867 // If the muxer reports a frame rate different than the codec
1868 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1869 double muxer_fps = av_q2d( stream->avg_frame_rate );
1870 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1871 muxer_fps = av_q2d( stream->r_frame_rate );
1873 double muxer_fps = av_q2d( stream->r_frame_rate );
1875 // Choose the lesser - the wrong tends to be off by some multiple of 10
1876 source_fps = FFMIN( source_fps, muxer_fps );
1877 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1879 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1880 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1882 else if ( muxer_fps > 0 )
1884 AVRational frame_rate = stream->r_frame_rate;
1885 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1886 // avg_frame_rate gives some approximate value that does not well match the media.
1887 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1888 // results in some very choppy output, but some value slightly different works
1890 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1891 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1892 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1894 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1895 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1899 source_fps = mlt_producer_get_fps( self->parent );
1900 AVRational frame_rate = av_d2q( source_fps, 255 );
1901 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1902 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1905 self->video_time_base = stream->time_base;
1906 if ( mlt_properties_get( properties, "force_fps" ) )
1908 double source_fps = mlt_properties_get_double( properties, "force_fps" );
1909 AVRational fps = av_d2q( source_fps, 1024 );
1910 self->video_time_base.num *= mlt_properties_get_int( properties, "meta.media.frame_rate_num" ) * fps.den;
1911 self->video_time_base.den *= mlt_properties_get_int( properties, "meta.media.frame_rate_den" ) * fps.num;
1912 mlt_properties_set_int( properties, "meta.media.frame_rate_num", fps.num );
1913 mlt_properties_set_int( properties, "meta.media.frame_rate_den", fps.den );
1916 // Set the YUV colorspace from override or detect
1917 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1918 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1919 if ( ! self->colorspace )
1921 switch ( self->video_codec->colorspace )
1923 case AVCOL_SPC_SMPTE240M:
1924 self->colorspace = 240;
1926 case AVCOL_SPC_BT470BG:
1927 case AVCOL_SPC_SMPTE170M:
1928 self->colorspace = 601;
1930 case AVCOL_SPC_BT709:
1931 self->colorspace = 709;
1934 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1935 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1940 // Let apps get chosen colorspace
1941 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1943 self->full_luma = -1;
1944 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(72<<8)+2)
1945 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent), "color_range %d\n", codec_context->color_range );
1946 if ( codec_context->color_range == AVCOL_RANGE_JPEG )
1947 self->full_luma = 1;
1949 if ( mlt_properties_get( properties, "set.force_full_luma" ) )
1950 self->full_luma = mlt_properties_get_int( properties, "set.force_full_luma" );
1952 return self->video_codec && self->video_index > -1;
1955 /** Set up video handling.
1958 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1961 mlt_producer producer = self->parent;
1963 // Get the properties
1964 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1966 // Fetch the video format context
1967 AVFormatContext *context = self->video_format;
1969 // Get the video_index
1970 int index = mlt_properties_get_int( properties, "video_index" );
1972 // Reopen the file if necessary
1973 if ( !context && index > -1 )
1975 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1976 mlt_properties_get( properties, "resource" ), 1 );
1977 context = self->video_format;
1980 // Exception handling for video_index
1981 if ( context && index >= (int) context->nb_streams )
1983 // Get the last video stream
1984 for ( index = context->nb_streams - 1;
1985 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1987 mlt_properties_set_int( properties, "video_index", index );
1989 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1991 // Invalidate the video stream
1993 mlt_properties_set_int( properties, "video_index", index );
1996 // Update the video properties if the index changed
1997 if ( index != self->video_index )
1999 // Reset the video properties if the index changed
2000 self->video_index = index;
2001 pthread_mutex_lock( &self->open_mutex );
2002 if ( self->video_codec )
2003 avcodec_close( self->video_codec );
2004 self->video_codec = NULL;
2005 pthread_mutex_unlock( &self->open_mutex );
2008 // Get the frame properties
2009 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2012 if ( context && index > -1 && video_codec_init( self, index, properties ) )
2014 // Set the frame properties
2015 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
2016 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
2017 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
2019 // Set the width and height
2020 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
2021 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
2022 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
2023 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
2024 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
2025 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
2027 // Workaround 1088 encodings missing cropping info.
2028 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
2030 mlt_properties_set_int( properties, "meta.media.height", 1080 );
2033 // Add our image operation
2034 mlt_frame_push_service( frame, self );
2035 mlt_frame_push_get_image( frame, producer_get_image );
2039 // If something failed, use test card image
2040 mlt_properties_set_int( frame_properties, "test_image", 1 );
2044 static int seek_audio( producer_avformat self, mlt_position position, double timecode )
2048 // Seek if necessary
2049 if ( self->seekable && ( position != self->audio_expected || self->last_position < 0 ) )
2051 if ( self->last_position == POSITION_INITIAL )
2053 int video_index = self->video_index;
2054 if ( video_index == -1 )
2055 video_index = first_video_index( self );
2056 if ( video_index >= 0 )
2057 find_first_pts( self, video_index );
2060 if ( position + 1 == self->audio_expected )
2062 // We're paused - silence required
2065 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
2067 AVFormatContext *context = self->audio_format;
2068 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
2069 if ( context->start_time != AV_NOPTS_VALUE )
2070 timestamp += context->start_time;
2071 if ( timestamp < 0 )
2074 // Set to the real timecode
2075 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
2078 // Clear the usage in the audio buffer
2079 int i = MAX_AUDIO_STREAMS + 1;
2081 self->audio_used[i - 1] = 0;
2087 static int sample_bytes( AVCodecContext *context )
2089 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2090 return av_get_bytes_per_sample( context->sample_fmt );
2091 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2092 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2094 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2098 static void planar_to_interleaved( uint8_t *dest, uint8_t *src, int samples, int channels, int bytes_per_sample )
2101 for ( s = 0; s < samples; s++ )
2103 for ( c = 0; c < channels; c++ )
2105 memcpy( dest, src + ( c * samples + s ) * bytes_per_sample, bytes_per_sample );
2106 dest += bytes_per_sample;
2111 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2113 // Fetch the audio_format
2114 AVFormatContext *context = self->audio_format;
2116 // Get the current stream index
2117 int index = pkt.stream_index;
2119 // Get codec context
2120 AVCodecContext *codec_context = self->audio_codec[ index ];
2122 // Obtain the audio buffers
2123 uint8_t *audio_buffer = self->audio_buffer[ index ];
2124 uint8_t *decode_buffer = self->decode_buffer[ index ];
2126 int audio_used = self->audio_used[ index ];
2127 uint8_t *ptr = pkt.data;
2131 while ( ptr && ret >= 0 && len > 0 )
2133 int sizeof_sample = sample_bytes( codec_context );
2134 int data_size = self->audio_buffer_size[ index ];
2137 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2138 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2139 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2140 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2142 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2146 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2150 pkt.size = len -= ret;
2151 pkt.data = ptr += ret;
2153 // If decoded successfully
2154 if ( data_size > 0 )
2156 // Figure out how many samples will be needed after resampling
2157 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2159 // Resize audio buffer to prevent overflow
2160 if ( ( audio_used + convert_samples ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2162 self->audio_buffer_size[ index ] = ( audio_used + convert_samples * 2 ) * channels * sizeof_sample;
2163 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2165 uint8_t *source = decode_buffer;
2166 uint8_t *dest = &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ];
2167 switch ( codec_context->sample_fmt )
2169 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2170 case AV_SAMPLE_FMT_U8P:
2171 case AV_SAMPLE_FMT_S16P:
2172 case AV_SAMPLE_FMT_S32P:
2173 case AV_SAMPLE_FMT_FLTP:
2174 planar_to_interleaved( dest, source, convert_samples, codec_context->channels, sizeof_sample );
2178 // Straight copy to audio buffer
2179 memcpy( dest, decode_buffer, data_size );
2181 audio_used += convert_samples;
2184 while ( *ignore && audio_used )
2187 audio_used -= audio_used > samples ? samples : audio_used;
2188 memmove( audio_buffer, &audio_buffer[ samples * codec_context->channels * sizeof_sample ],
2189 audio_used * sizeof_sample );
2194 // If we're behind, ignore this packet
2195 // Skip this on non-seekable, audio-only inputs.
2196 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2198 int64_t pts = pkt.pts;
2199 if ( self->first_pts != AV_NOPTS_VALUE )
2200 pts -= self->first_pts;
2201 else if ( context->start_time != AV_NOPTS_VALUE )
2202 pts -= context->start_time;
2203 double timebase = av_q2d( context->streams[ index ]->time_base );
2204 int64_t int_position = ( int64_t )( timebase * pts * fps + 0.5 );
2205 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2207 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
2208 "A pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
2209 pkt.pts, pkt.dts, req_position, self->current_position, int_position );
2211 if ( int_position > 0 )
2213 if ( int_position < req_position )
2214 // We are behind, so skip some
2215 *ignore = req_position - int_position;
2216 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2217 // We are ahead, so seek backwards some more
2218 seek_audio( self, req_position, timecode - 1.0 );
2220 // Cancel the find_first_pts() in seek_audio()
2221 if ( self->video_index == -1 && self->last_position == POSITION_INITIAL )
2222 self->last_position = int_position;
2225 self->audio_used[ index ] = audio_used;
2230 /** Get the audio from a frame.
2232 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2235 producer_avformat self = mlt_frame_pop_audio( frame );
2237 pthread_mutex_lock( &self->audio_mutex );
2239 // Obtain the frame number of this frame
2240 mlt_position position = mlt_frame_original_position( frame );
2242 // Calculate the real time code
2243 double real_timecode = producer_time_of_frame( self->parent, position );
2245 // Get the producer fps
2246 double fps = mlt_producer_get_fps( self->parent );
2248 // Number of frames to ignore (for ffwd)
2249 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2251 // Flag for paused (silence)
2252 int paused = seek_audio( self, position, real_timecode );
2254 // Initialize ignore for all streams from the seek return value
2255 int i = MAX_AUDIO_STREAMS;
2257 ignore[i] = ignore[0];
2259 // Fetch the audio_format
2260 AVFormatContext *context = self->audio_format;
2262 int sizeof_sample = sizeof( int16_t );
2264 // Determine the tracks to use
2265 int index = self->audio_index;
2266 int index_max = self->audio_index + 1;
2267 if ( self->audio_index == INT_MAX )
2270 index_max = FFMIN( MAX_AUDIO_STREAMS, context->nb_streams );
2271 *channels = self->total_channels;
2272 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2273 *frequency = FFMAX( self->max_frequency, *frequency );
2276 // Initialize the buffers
2277 for ( ; index < index_max && index < MAX_AUDIO_STREAMS; index++ )
2279 // Get codec context
2280 AVCodecContext *codec_context = self->audio_codec[ index ];
2282 if ( codec_context && !self->audio_buffer[ index ] )
2284 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2285 sizeof_sample = sample_bytes( codec_context );
2287 // Check for audio buffer and create if necessary
2288 self->audio_buffer_size[ index ] = MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2289 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2291 // Check for decoder buffer and create if necessary
2292 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2296 // Get the audio if required
2297 if ( !paused && *frequency > 0 )
2303 av_init_packet( &pkt );
2305 // It requested number samples based on requested frame rate.
2306 // Do not clean this up with a samples *= ...!
2307 if ( self->audio_index != INT_MAX )
2308 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2310 while ( ret >= 0 && !got_audio )
2312 // Check if the buffer already contains the samples required
2313 if ( self->audio_index != INT_MAX &&
2314 self->audio_used[ self->audio_index ] >= *samples &&
2315 ignore[ self->audio_index ] == 0 )
2320 else if ( self->audio_index == INT_MAX )
2322 // Check if there is enough audio for all streams
2324 for ( index = 0; got_audio && index < index_max; index++ )
2325 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2332 pthread_mutex_lock( &self->packets_mutex );
2333 if ( mlt_deque_count( self->apackets ) )
2335 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2341 ret = av_read_frame( context, &pkt );
2342 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2344 if ( !av_dup_packet( &pkt ) )
2346 AVPacket *tmp = malloc( sizeof(AVPacket) );
2348 mlt_deque_push_back( self->vpackets, tmp );
2352 pthread_mutex_unlock( &self->packets_mutex );
2354 // We only deal with audio from the selected audio index
2355 index = pkt.stream_index;
2356 if ( index < MAX_AUDIO_STREAMS && ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2357 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2359 int channels2 = self->audio_codec[index]->channels;
2360 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2363 if ( self->seekable || index != self->video_index )
2364 av_free_packet( &pkt );
2368 // Set some additional return values
2369 *format = mlt_audio_s16;
2370 if ( self->audio_index != INT_MAX )
2372 index = self->audio_index;
2373 *channels = self->audio_codec[ index ]->channels;
2374 *frequency = self->audio_codec[ index ]->sample_rate;
2375 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2376 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2378 else if ( self->audio_index == INT_MAX )
2380 for ( index = 0; index < index_max; index++ )
2381 if ( self->audio_codec[ index ] )
2383 // XXX: This only works if all audio tracks have the same sample format.
2384 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2385 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2390 // Allocate and set the frame's audio buffer
2391 int size = mlt_audio_format_size( *format, *samples, *channels );
2392 *buffer = mlt_pool_alloc( size );
2393 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2395 // Interleave tracks if audio_index=all
2396 if ( self->audio_index == INT_MAX )
2398 uint8_t *dest = *buffer;
2400 for ( i = 0; i < *samples; i++ )
2402 for ( index = 0; index < index_max; index++ )
2403 if ( self->audio_codec[ index ] )
2405 int current_channels = self->audio_codec[ index ]->channels;
2406 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2407 memcpy( dest, src, current_channels * sizeof_sample );
2408 dest += current_channels * sizeof_sample;
2411 for ( index = 0; index < index_max; index++ )
2412 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2414 int current_channels = self->audio_codec[ index ]->channels;
2415 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2416 self->audio_used[index] -= *samples;
2417 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2420 // Copy a single track to the output buffer
2423 index = self->audio_index;
2425 // Now handle the audio if we have enough
2426 if ( self->audio_used[ index ] > 0 )
2428 uint8_t *src = self->audio_buffer[ index ];
2429 // copy samples from audio_buffer
2430 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2431 memcpy( *buffer, src, size * *channels * sizeof_sample );
2432 // supply the remaining requested samples as silence
2433 if ( *samples > self->audio_used[ index ] )
2434 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2435 // reposition the samples within audio_buffer
2436 self->audio_used[ index ] -= size;
2437 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2441 // Otherwise fill with silence
2442 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2448 // Get silence and don't touch the context
2449 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2452 // Regardless of speed (other than paused), we expect to get the next frame
2454 self->audio_expected = position + 1;
2456 pthread_mutex_unlock( &self->audio_mutex );
2461 /** Initialize the audio codec context.
2464 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2466 // Initialise the codec if necessary
2467 if ( !self->audio_codec[ index ] )
2469 // Get codec context
2470 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2473 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2475 // If we don't have a codec and we can't initialise it, we can't do much more...
2476 pthread_mutex_lock( &self->open_mutex );
2477 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2478 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2480 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2483 // Now store the codec with its destructor
2484 if ( self->audio_codec[ index ] )
2485 avcodec_close( self->audio_codec[ index ] );
2486 self->audio_codec[ index ] = codec_context;
2490 // Remember that we can't use self later
2491 self->audio_index = -1;
2493 pthread_mutex_unlock( &self->open_mutex );
2495 // Process properties as AVOptions
2496 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2497 if ( codec && codec->priv_class && codec_context->priv_data )
2498 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2500 return self->audio_codec[ index ] && self->audio_index > -1;
2503 /** Set up audio handling.
2506 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2509 mlt_producer producer = self->parent;
2511 // Get the properties
2512 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2514 // Fetch the audio format context
2515 AVFormatContext *context = self->audio_format;
2517 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2519 // Get the audio_index
2520 int index = mlt_properties_get_int( properties, "audio_index" );
2522 // Handle all audio tracks
2523 if ( self->audio_index > -1 &&
2524 mlt_properties_get( properties, "audio_index" ) &&
2525 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2528 // Reopen the file if necessary
2529 if ( !context && self->audio_index > -1 && index > -1 )
2531 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2532 mlt_properties_get( properties, "resource" ), 1 );
2533 context = self->audio_format;
2536 // Exception handling for audio_index
2537 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2539 for ( index = context->nb_streams - 1;
2540 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2542 mlt_properties_set_int( properties, "audio_index", index );
2544 if ( context && index > -1 && index < INT_MAX &&
2545 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2547 index = self->audio_index;
2548 mlt_properties_set_int( properties, "audio_index", index );
2550 if ( context && index > -1 && index < INT_MAX &&
2551 pick_audio_format( context->streams[ index ]->codec->sample_fmt ) == mlt_audio_none )
2556 // Update the audio properties if the index changed
2557 if ( context && index > -1 && index != self->audio_index )
2559 pthread_mutex_lock( &self->open_mutex );
2560 if ( self->audio_codec[ self->audio_index ] )
2561 avcodec_close( self->audio_codec[ self->audio_index ] );
2562 self->audio_codec[ self->audio_index ] = NULL;
2563 pthread_mutex_unlock( &self->open_mutex );
2565 if ( self->audio_index != -1 )
2566 self->audio_index = index;
2571 if ( context && index == INT_MAX )
2573 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2574 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2575 for ( index = 0; index < context->nb_streams; index++ )
2577 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2578 audio_codec_init( self, index, properties );
2581 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2583 // Set the frame properties
2584 if ( index < MAX_AUDIO_STREAMS )
2586 mlt_properties_set_int( frame_properties, "audio_frequency", self->audio_codec[ index ]->sample_rate );
2587 mlt_properties_set_int( frame_properties, "audio_channels", self->audio_codec[ index ]->channels );
2590 if ( context && index > -1 )
2592 // Add our audio operation
2593 mlt_frame_push_audio( frame, self );
2594 mlt_frame_push_audio( frame, producer_get_audio );
2598 /** Our get frame implementation.
2601 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2603 // Access the private data
2604 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2605 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2606 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2611 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2612 producer->child = self;
2613 self->parent = producer;
2614 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2615 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2618 // Create an empty frame
2619 *frame = mlt_frame_init( service);
2623 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2627 mlt_cache_item_close( cache_item );
2631 // Update timecode on the frame we're creating
2632 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2635 producer_set_up_video( self, *frame );
2638 producer_set_up_audio( self, *frame );
2640 // Set the position of this producer
2641 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2642 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "original_position", position );
2644 // Calculate the next timecode
2645 mlt_producer_prepare_next( producer );
2650 static void producer_avformat_close( producer_avformat self )
2652 mlt_log_debug( NULL, "producer_avformat_close\n" );
2654 // Cleanup av contexts
2655 av_free_packet( &self->pkt );
2656 av_free( self->av_frame );
2657 pthread_mutex_lock( &self->open_mutex );
2659 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2661 mlt_pool_release( self->audio_buffer[i] );
2662 av_free( self->decode_buffer[i] );
2663 if ( self->audio_codec[i] )
2664 avcodec_close( self->audio_codec[i] );
2665 self->audio_codec[i] = NULL;
2667 if ( self->video_codec )
2668 avcodec_close( self->video_codec );
2669 self->video_codec = NULL;
2671 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2672 if ( self->dummy_context )
2673 avformat_close_input( &self->dummy_context );
2674 if ( self->seekable && self->audio_format )
2675 avformat_close_input( &self->audio_format );
2676 if ( self->video_format )
2677 avformat_close_input( &self->video_format );
2679 if ( self->dummy_context )
2680 av_close_input_file( self->dummy_context );
2681 if ( self->seekable && self->audio_format )
2682 av_close_input_file( self->audio_format );
2683 if ( self->video_format )
2684 av_close_input_file( self->video_format );
2686 pthread_mutex_unlock( &self->open_mutex );
2688 vdpau_producer_close( self );
2690 if ( self->image_cache )
2691 mlt_cache_close( self->image_cache );
2693 // Cleanup the mutexes
2694 if ( self->is_mutex_init )
2696 pthread_mutex_destroy( &self->audio_mutex );
2697 pthread_mutex_destroy( &self->video_mutex );
2698 pthread_mutex_destroy( &self->packets_mutex );
2699 pthread_mutex_destroy( &self->open_mutex );
2702 // Cleanup the packet queues
2704 if ( self->apackets )
2706 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2708 av_free_packet( pkt );
2711 mlt_deque_close( self->apackets );
2712 self->apackets = NULL;
2714 if ( self->vpackets )
2716 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2718 av_free_packet( pkt );
2721 mlt_deque_close( self->vpackets );
2722 self->vpackets = NULL;
2728 static void producer_close( mlt_producer parent )
2730 // Remove this instance from the cache
2731 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2734 parent->close = NULL;
2735 mlt_producer_close( parent );