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>
35 # include <libswscale/swscale.h>
38 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
39 # include <libavutil/samplefmt.h>
41 # define AV_SAMPLE_FMT_S16 SAMPLE_FMT_S16
42 # define AV_SAMPLE_FMT_S32 SAMPLE_FMT_S32
43 # define AV_SAMPLE_FMT_FLT SAMPLE_FMT_FLT
44 # if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
45 const char *avcodec_get_sample_fmt_name(int sample_fmt);
50 # include <libavcodec/vdpau.h>
52 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
53 # include <libavutil/pixdesc.h>
55 #if (LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0))
56 # include <libavutil/dict.h>
59 // System header files
65 #if LIBAVUTIL_VERSION_INT < (50<<16)
66 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
67 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
70 #if LIBAVCODEC_VERSION_MAJOR >= 53
71 #include <libavutil/opt.h>
72 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
73 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
74 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
76 #include <libavcodec/opt.h>
79 #define POSITION_INITIAL (-2)
80 #define POSITION_INVALID (-1)
82 #define MAX_AUDIO_STREAMS (10)
83 #define MAX_VDPAU_SURFACES (10)
85 struct producer_avformat_s
88 AVFormatContext *dummy_context;
89 AVFormatContext *audio_format;
90 AVFormatContext *video_format;
91 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
92 AVCodecContext *video_codec;
94 ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
95 mlt_position audio_expected;
96 mlt_position video_expected;
100 int64_t last_position;
102 int64_t current_position;
103 mlt_position nonseek_position;
106 uint8_t *audio_buffer[ MAX_AUDIO_STREAMS ];
107 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
108 uint8_t *decode_buffer[ MAX_AUDIO_STREAMS ];
109 int audio_used[ MAX_AUDIO_STREAMS ];
111 int audio_max_stream;
115 unsigned int invalid_pts_counter;
116 double resample_factor;
117 mlt_cache image_cache;
118 mlt_cache alpha_cache;
120 pthread_mutex_t video_mutex;
121 pthread_mutex_t audio_mutex;
124 pthread_mutex_t packets_mutex;
125 pthread_mutex_t open_mutex;
130 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
144 typedef struct producer_avformat_s *producer_avformat;
146 // Forward references.
147 static int list_components( char* file );
148 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock );
149 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
150 static void producer_avformat_close( producer_avformat );
151 static void producer_close( mlt_producer parent );
152 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
153 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
154 static void apply_properties( void *obj, mlt_properties properties, int flags );
155 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
156 static void get_audio_streams_info( producer_avformat self );
162 /** Constructor for libavformat.
165 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
167 if ( list_components( file ) )
170 mlt_producer producer = NULL;
172 // Check that we have a non-NULL argument
175 // Construct the producer
176 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
177 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
180 if ( mlt_producer_init( producer, self ) == 0 )
182 self->parent = producer;
184 // Get the properties
185 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
187 // Set the resource property (required for all producers)
188 mlt_properties_set( properties, "resource", file );
190 // Register transport implementation with the producer
191 producer->close = (mlt_destructor) producer_close;
193 // Register our get_frame implementation
194 producer->get_frame = producer_get_frame;
196 if ( strcmp( service, "avformat-novalidate" ) )
199 if ( producer_open( self, profile, file, 1 ) != 0 )
202 mlt_producer_close( producer );
205 else if ( self->seekable )
207 // Close the file to release resources for large playlists - reopen later as needed
208 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
209 if ( self->audio_format )
210 avformat_close_input( &self->audio_format );
211 if ( self->video_format )
212 avformat_close_input( &self->video_format );
214 if ( self->audio_format )
215 av_close_input_file( self->audio_format );
216 if ( self->video_format )
217 av_close_input_file( self->video_format );
219 self->audio_format = NULL;
220 self->video_format = NULL;
225 // Default the user-selectable indices from the auto-detected indices
226 mlt_properties_set_int( properties, "audio_index", self->audio_index );
227 mlt_properties_set_int( properties, "video_index", self->video_index );
229 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
231 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
238 int list_components( char* file )
242 // Report information about available demuxers and codecs as YAML Tiny
243 if ( file && strstr( file, "f-list" ) )
245 fprintf( stderr, "---\nformats:\n" );
246 AVInputFormat *format = NULL;
247 while ( ( format = av_iformat_next( format ) ) )
248 fprintf( stderr, " - %s\n", format->name );
249 fprintf( stderr, "...\n" );
252 if ( file && strstr( file, "acodec-list" ) )
254 fprintf( stderr, "---\naudio_codecs:\n" );
255 AVCodec *codec = NULL;
256 while ( ( codec = av_codec_next( codec ) ) )
257 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
258 fprintf( stderr, " - %s\n", codec->name );
259 fprintf( stderr, "...\n" );
262 if ( file && strstr( file, "vcodec-list" ) )
264 fprintf( stderr, "---\nvideo_codecs:\n" );
265 AVCodec *codec = NULL;
266 while ( ( codec = av_codec_next( codec ) ) )
267 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
268 fprintf( stderr, " - %s\n", codec->name );
269 fprintf( stderr, "...\n" );
276 /** Find the default streams.
279 static mlt_properties find_default_streams( producer_avformat self )
283 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
284 AVDictionaryEntry *tag = NULL;
286 AVMetadataTag *tag = NULL;
288 AVFormatContext *context = self->video_format;
289 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
291 // Default to the first audio and video streams found
292 self->audio_index = -1;
293 self->video_index = -1;
295 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
297 // Allow for multiple audio and video streams in the file and select first of each (if available)
298 for( i = 0; i < context->nb_streams; i++ )
300 // Get the codec context
301 AVStream *stream = context->streams[ i ];
302 if ( ! stream ) continue;
303 AVCodecContext *codec_context = stream->codec;
304 if ( ! codec_context ) continue;
305 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
306 if ( ! codec ) continue;
308 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
310 // Determine the type and obtain the first index of each type
311 switch( codec_context->codec_type )
313 case CODEC_TYPE_VIDEO:
314 // Use first video stream
315 if ( self->video_index < 0 )
316 self->video_index = i;
317 mlt_properties_set( meta_media, key, "video" );
318 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
319 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
320 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
321 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
322 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
323 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
325 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
328 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
329 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
330 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
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 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
344 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
345 switch ( codec_context->colorspace )
347 case AVCOL_SPC_SMPTE240M:
348 mlt_properties_set_int( meta_media, key, 240 );
350 case AVCOL_SPC_BT470BG:
351 case AVCOL_SPC_SMPTE170M:
352 mlt_properties_set_int( meta_media, key, 601 );
354 case AVCOL_SPC_BT709:
355 mlt_properties_set_int( meta_media, key, 709 );
358 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
359 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
364 case CODEC_TYPE_AUDIO:
365 // Use first audio stream
366 if ( self->audio_index < 0 )
367 self->audio_index = i;
368 mlt_properties_set( meta_media, key, "audio" );
369 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
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 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
373 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
374 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
376 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
377 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
378 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
379 mlt_properties_set_int( meta_media, key, codec_context->channels );
384 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
385 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
386 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
387 mlt_properties_set( meta_media, key, codec->name );
388 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
389 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
390 mlt_properties_set( meta_media, key, codec->long_name );
392 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
393 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
394 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
395 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
396 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
397 // mlt_properties_set_int( meta_media, key, codec_context->profile );
398 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
399 // mlt_properties_set_int( meta_media, key, codec_context->level );
402 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
403 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
404 while ( ( tag = av_dict_get( stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
406 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
409 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
411 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
412 mlt_properties_set( meta_media, key, tag->value );
417 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
418 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
419 while ( ( tag = av_dict_get( context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
421 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
424 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
426 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
427 mlt_properties_set( meta_media, key, tag->value );
431 if ( context->title && strcmp( context->title, "" ) )
432 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
433 if ( context->author && strcmp( context->author, "" ) )
434 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
435 if ( context->copyright && strcmp( context->copyright, "" ) )
436 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
437 if ( context->comment )
438 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
439 if ( context->album )
440 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
442 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
443 if ( context->track )
444 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
450 static inline int dv_is_pal( AVPacket *pkt )
452 return pkt->data[3] & 0x80;
455 static int dv_is_wide( AVPacket *pkt )
457 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
459 for ( ; i < pkt->size; i += 5 /* packet size */ )
461 if ( pkt->data[ i ] == 0x61 )
463 uint8_t x = pkt->data[ i + 2 ] & 0x7;
464 return ( x == 2 ) || ( x == 7 );
470 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
472 double aspect_ratio = 1.0;
474 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
478 if ( dv_is_pal( pkt ) )
480 if ( dv_is_wide( pkt ) )
482 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
483 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
487 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
488 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
493 if ( dv_is_wide( pkt ) )
495 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
496 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
500 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
501 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
508 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
509 stream->sample_aspect_ratio;
511 codec_context->sample_aspect_ratio;
513 // Override FFmpeg's notion of DV aspect ratios, which are
514 // based upon a width of 704. Since we do not have a normaliser
515 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
516 // we just coerce the values to facilitate a passive behaviour through
517 // the rescale normaliser when using equivalent producers and consumers.
518 // = display_aspect / (width * height)
519 if ( ar.num == 10 && ar.den == 11 )
522 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
523 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
525 else if ( ar.num == 59 && ar.den == 54 )
528 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
529 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
531 else if ( ar.num == 40 && ar.den == 33 )
534 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
535 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
537 else if ( ar.num == 118 && ar.den == 81 )
540 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
541 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
547 AVRational codec_sar = codec_context->sample_aspect_ratio;
548 AVRational stream_sar =
549 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
550 stream->sample_aspect_ratio;
554 if ( codec_sar.num > 0 )
556 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
557 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
559 else if ( stream_sar.num > 0 )
561 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
562 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
566 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
567 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
570 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
571 aspect_ratio = av_q2d( ar );
572 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
577 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
578 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVDictionary **params )
580 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
583 if ( !URL ) return NULL;
586 char *protocol = strdup( URL );
587 char *url = strchr( protocol, ':' );
589 // Only if there is not a protocol specification that avformat can handle
590 #if LIBAVFORMAT_VERSION_MAJOR >= 53
591 if ( url && avio_check( URL, 0 ) < 0 )
593 if ( url && !url_exist( URL ) )
596 // Truncate protocol string
598 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
601 *format = av_find_input_format( protocol );
603 // Eat the format designator
608 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
609 // support for legacy width and height parameters
613 // These are required by video4linux2 (defaults)
614 params->width = profile->width;
615 params->height = profile->height;
616 if ( !strstr( URL, "&frame_rate" ) )
617 params->time_base = (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
618 params->channels = 2;
619 params->sample_rate = 48000;
623 url = strchr( url, '?' );
627 char *name = strdup( ++url );
628 char *value = strchr( name, '=' );
630 // Also accept : as delimiter for backwards compatibility.
631 value = strchr( name, ':' );
636 char *t = strchr( value, '&' );
639 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
640 // translate old parameters to new av_dict names
641 if ( !strcmp( name, "frame_rate" ) )
642 av_dict_set( params, "framerate", value, 0 );
643 else if ( !strcmp( name, "pix_fmt" ) )
644 av_dict_set( params, "pixel_format", value, 0 );
645 else if ( !strcmp( name, "width" ) )
646 width = strdup( value );
647 else if ( !strcmp( name, "height" ) )
648 height = strdup( value );
650 // generic demux/device option support
651 av_dict_set( params, name, value, 0 );
653 if ( !strcmp( name, "frame_rate" ) )
654 params->time_base.den = atoi( value );
655 else if ( !strcmp( name, "frame_rate_base" ) )
656 params->time_base.num = atoi( value );
657 else if ( !strcmp( name, "sample_rate" ) )
658 params->sample_rate = atoi( value );
659 else if ( !strcmp( name, "channel" ) )
660 params->channel = atoi( value );
661 else if ( !strcmp( name, "channels" ) )
662 params->channels = atoi( value );
663 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
664 else if ( !strcmp( name, "pix_fmt" ) )
665 params->pix_fmt = av_get_pix_fmt( value );
667 else if ( !strcmp( name, "width" ) )
668 params->width = atoi( value );
669 else if ( !strcmp( name, "height" ) )
670 params->height = atoi( value );
671 else if ( !strcmp( name, "standard" ) )
672 params->standard = strdup( value );
676 url = strchr( url, '&' );
678 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
679 // continued support for legacy width and height parameters
680 if ( width && height )
682 char *s = malloc( strlen( width ) + strlen( height ) + 2 );
686 av_dict_set( params, "video_size", s, 0 );
689 if ( width ) free( width );
690 if ( height ) free ( height );
693 result = strdup( result );
697 result = strdup( URL );
703 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
707 // Get the properties
708 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
710 AVFormatContext *format = self->video_format;
712 // We will treat everything with the producer fps.
713 // TODO: make this more flexible.
714 double fps = mlt_profile_fps( profile );
717 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
719 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
720 // when producer_open is called after initial call when restoring or reseting the producer.
721 if ( format->duration != AV_NOPTS_VALUE )
723 // This isn't going to be accurate for all formats
724 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
725 mlt_properties_set_position( properties, "out", frames - 1 );
726 mlt_properties_set_position( properties, "length", frames );
727 mlt_properties_set_int( properties, "_length_computed", 1 );
731 // Set live sources to run forever
732 mlt_properties_set_position( properties, "length", INT_MAX );
733 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
734 mlt_properties_set( properties, "eof", "loop" );
735 mlt_properties_set_int( properties, "_length_computed", 1 );
739 // Check if we're seekable
740 // avdevices are typically AVFMT_NOFILE and not seekable
741 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
744 // protocols can indicate if they support seeking
745 #if LIBAVFORMAT_VERSION_MAJOR >= 53
746 self->seekable = format->pb->seekable;
748 URLContext *uc = url_fileno( format->pb );
750 self->seekable = !uc->is_streamed;
753 if ( self->seekable )
755 // Do a more rigourous test of seekable on a disposable context
756 self->seekable = av_seek_frame( format, -1, format->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
757 mlt_properties_set_int( properties, "seekable", self->seekable );
758 self->dummy_context = format;
759 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
760 self->video_format = NULL;
761 avformat_open_input( &self->video_format, filename, NULL, NULL );
762 avformat_find_stream_info( self->video_format, NULL );
764 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
765 av_find_stream_info( self->video_format );
767 format = self->video_format;
770 // Fetch the width, height and aspect ratio
771 if ( self->video_index != -1 )
773 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
774 mlt_properties_set_int( properties, "width", codec_context->width );
775 mlt_properties_set_int( properties, "height", codec_context->height );
777 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
779 // Fetch the first frame of DV so we can read it directly
784 ret = av_read_frame( format, &pkt );
785 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
787 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
794 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
798 // Verify that we can convert this to YUV 4:2:2
799 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
800 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
801 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
803 sws_freeContext( context );
814 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
816 // Return an error code (0 == no error)
818 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
823 pthread_mutex_init( &self->audio_mutex, NULL );
824 pthread_mutex_init( &self->video_mutex, NULL );
825 pthread_mutex_init( &self->packets_mutex, NULL );
826 pthread_mutex_init( &self->open_mutex, NULL );
827 pthread_mutex_lock( &self->audio_mutex );
828 pthread_mutex_lock( &self->video_mutex );
830 mlt_events_block( properties, self->parent );
833 AVInputFormat *format = NULL;
834 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
835 AVDictionary *params = NULL;
837 AVFormatParameters params;
838 memset( ¶ms, 0, sizeof(params) );
840 char *filename = parse_url( profile, URL, &format, ¶ms );
842 // Now attempt to open the file or device with filename
843 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
844 error = avformat_open_input( &self->video_format, filename, format, ¶ms ) < 0;
846 // If the URL is a network stream URL, then we probably need to open with full URL
847 error = avformat_open_input( &self->video_format, URL, format, ¶ms ) < 0;
849 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
851 // If the URL is a network stream URL, then we probably need to open with full URL
852 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
855 // Set MLT properties onto video AVFormatContext
856 if ( !error && self->video_format )
858 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
859 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
860 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
861 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
865 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
866 av_dict_free( ¶ms );
868 // Cleanup AVFormatParameters
869 if ( params.standard )
870 free( (void*) params.standard );
873 // If successful, then try to get additional info
874 if ( !error && self->video_format )
876 // Get the stream info
877 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
878 error = avformat_find_stream_info( self->video_format, NULL ) < 0;
880 error = av_find_stream_info( self->video_format ) < 0;
883 // Continue if no error
884 if ( !error && self->video_format )
886 // Find default audio and video streams
887 find_default_streams( self );
888 error = get_basic_info( self, profile, filename );
890 // Initialize position info
891 self->first_pts = -1;
892 self->last_position = POSITION_INITIAL;
894 if ( !self->audio_format )
896 // We're going to cheat here - for seekable A/V files, we will have separate contexts
897 // to support independent seeking of audio from video.
898 // TODO: Is this really necessary?
899 if ( self->audio_index != -1 && self->video_index != -1 )
901 if ( self->seekable )
903 // And open again for our audio context
904 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
905 avformat_open_input( &self->audio_format, filename, NULL, NULL );
906 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
907 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
908 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
909 avformat_find_stream_info( self->audio_format, NULL );
911 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
912 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
913 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
914 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
915 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
917 av_find_stream_info( self->audio_format );
922 self->audio_format = self->video_format;
925 else if ( self->audio_index != -1 )
927 // We only have an audio context
928 self->audio_format = self->video_format;
929 self->video_format = NULL;
931 else if ( self->video_index == -1 )
933 // Something has gone wrong
936 if ( self->audio_format && !self->audio_streams )
937 get_audio_streams_info( self );
945 self->apackets = mlt_deque_init();
946 self->vpackets = mlt_deque_init();
949 if ( self->dummy_context )
951 pthread_mutex_lock( &self->open_mutex );
952 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
953 avformat_close_input( &self->dummy_context );
955 av_close_input_file( self->dummy_context );
957 self->dummy_context = NULL;
958 pthread_mutex_unlock( &self->open_mutex );
961 // Unlock the service
964 pthread_mutex_unlock( &self->audio_mutex );
965 pthread_mutex_unlock( &self->video_mutex );
967 mlt_events_unblock( properties, self->parent );
972 static void reopen_video( producer_avformat self, mlt_producer producer )
974 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
975 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
976 pthread_mutex_lock( &self->audio_mutex );
977 pthread_mutex_lock( &self->open_mutex );
979 if ( self->video_codec )
980 avcodec_close( self->video_codec );
981 self->video_codec = NULL;
982 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
983 if ( self->dummy_context )
984 avformat_close_input( &self->dummy_context );
985 if ( self->video_format )
986 avformat_close_input( &self->video_format );
988 if ( self->dummy_context )
989 av_close_input_file( self->dummy_context );
990 if ( self->video_format )
991 av_close_input_file( self->video_format );
993 self->dummy_context = NULL;
994 self->video_format = NULL;
995 pthread_mutex_unlock( &self->open_mutex );
997 int audio_index = self->audio_index;
998 int video_index = self->video_index;
1000 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1001 mlt_properties_get( properties, "resource" ), 0 );
1003 self->audio_index = audio_index;
1004 if ( self->video_format && video_index > -1 )
1006 self->video_index = video_index;
1007 video_codec_init( self, video_index, properties );
1010 pthread_mutex_unlock( &self->audio_mutex );
1011 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1014 static int seek_video( producer_avformat self, mlt_position position,
1015 int64_t req_position, int must_decode, int use_new_seek, int *ignore )
1017 mlt_producer producer = self->parent;
1020 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
1022 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1024 // Fetch the video format context
1025 AVFormatContext *context = self->video_format;
1027 // Get the video stream
1028 AVStream *stream = context->streams[ self->video_index ];
1030 // Get codec context
1031 AVCodecContext *codec_context = stream->codec;
1033 // We may want to use the source fps if available
1034 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1035 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1037 if ( self->av_frame && position + 1 == self->video_expected )
1039 // We're paused - use last image
1042 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
1044 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1045 *ignore = ( int )( ( position - self->video_expected ) / mlt_producer_get_fps( producer ) * source_fps );
1046 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1048 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
1050 if ( use_new_seek && self->last_position == POSITION_INITIAL )
1052 // find first key frame
1057 while ( ret >= 0 && toscan-- > 0 )
1059 ret = av_read_frame( context, &pkt );
1060 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
1062 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n", pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
1063 self->first_pts = pkt.pts;
1066 av_free_packet( &pkt );
1069 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1072 // Calculate the timestamp for the requested frame
1076 timestamp = ( req_position - 0.1 / source_fps ) /
1077 ( av_q2d( stream->time_base ) * source_fps );
1078 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pos %"PRId64" pts %"PRId64"\n", req_position, timestamp );
1079 if ( self->first_pts > 0 )
1080 timestamp += self->first_pts;
1081 else if ( context->start_time != AV_NOPTS_VALUE )
1082 timestamp += context->start_time;
1086 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
1087 if ( context->start_time != AV_NOPTS_VALUE )
1088 timestamp += context->start_time;
1091 timestamp -= AV_TIME_BASE;
1092 if ( timestamp < 0 )
1094 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
1095 timestamp, position, self->video_expected, self->last_position );
1097 // Seek to the timestamp
1100 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1101 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1103 else if ( req_position > 0 || self->last_position <= 0 )
1105 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
1109 // Re-open video stream when rewinding to beginning from somewhere else.
1110 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1111 // not reliably seeking to the first frame across formats.
1112 reopen_video( self, producer );
1115 // Remove the cached info relating to the previous position
1116 self->current_position = POSITION_INVALID;
1117 self->last_position = POSITION_INVALID;
1118 av_freep( &self->av_frame );
1122 // flush any pictures still in decode buffer
1123 avcodec_flush_buffers( codec_context );
1130 /** Convert a frame position to a time code.
1133 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1135 return ( double )position / mlt_producer_get_fps( producer );
1138 // Collect information about all audio streams
1140 static void get_audio_streams_info( producer_avformat self )
1142 // Fetch the audio format context
1143 AVFormatContext *context = self->audio_format;
1147 i < context->nb_streams;
1150 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1152 AVCodecContext *codec_context = context->streams[i]->codec;
1153 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1155 // If we don't have a codec and we can't initialise it, we can't do much more...
1156 pthread_mutex_lock( &self->open_mutex );
1157 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1158 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1160 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1163 self->audio_streams++;
1164 self->audio_max_stream = i;
1165 self->total_channels += codec_context->channels;
1166 if ( codec_context->channels > self->max_channel )
1167 self->max_channel = codec_context->channels;
1168 if ( codec_context->sample_rate > self->max_frequency )
1169 self->max_frequency = codec_context->sample_rate;
1170 avcodec_close( codec_context );
1172 pthread_mutex_unlock( &self->open_mutex );
1175 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1176 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1178 // Other audio-specific initializations
1179 self->resample_factor = 1.0;
1182 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1184 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1186 const int *new_coefficients;
1188 int brightness, contrast, saturation;
1190 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1191 &brightness, &contrast, &saturation ) != -1 )
1193 // Don't change these from defaults unless explicitly told to.
1194 if ( use_full_range >= 0 )
1195 full_range = use_full_range;
1196 switch ( colorspace )
1202 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1205 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1208 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1211 new_coefficients = coefficients;
1214 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1215 brightness, contrast, saturation );
1220 static mlt_image_format pick_format( enum PixelFormat pix_fmt )
1228 return mlt_image_rgb24a;
1229 case PIX_FMT_YUV420P:
1230 case PIX_FMT_YUVJ420P:
1231 case PIX_FMT_YUVA420P:
1232 return mlt_image_yuv420p;
1236 case PIX_FMT_MONOWHITE:
1237 case PIX_FMT_MONOBLACK:
1240 return mlt_image_rgb24;
1242 return mlt_image_yuv422;
1246 static void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
1247 mlt_image_format *format, int width, int height, int colorspace, uint8_t **alpha )
1250 int full_range = -1;
1251 int flags = SWS_BICUBIC | SWS_ACCURATE_RND;
1254 flags |= SWS_CPU_CAPS_MMX;
1257 flags |= SWS_CPU_CAPS_MMX2;
1260 // extract alpha from planar formats
1261 if ( ( pix_fmt == PIX_FMT_YUVA420P
1262 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(35<<8)+0)
1263 || pix_fmt == PIX_FMT_YUVA444P
1266 *format != mlt_image_rgb24a && *format != mlt_image_opengl &&
1267 frame->data[3] && frame->linesize[3] )
1272 dst = *alpha = mlt_pool_alloc( width * height );
1273 src = frame->data[3];
1275 for ( i = 0; i < height; dst += width, src += frame->linesize[3], i++ )
1276 memcpy( dst, src, FFMIN( width, frame->linesize[3] ) );
1279 if ( *format == mlt_image_yuv420p )
1281 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1282 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1284 output.data[0] = buffer;
1285 output.data[1] = buffer + width * height;
1286 output.data[2] = buffer + ( 5 * width * height ) / 4;
1287 output.linesize[0] = width;
1288 output.linesize[1] = width >> 1;
1289 output.linesize[2] = width >> 1;
1290 set_luma_transfer( context, colorspace, full_range );
1291 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1292 output.data, output.linesize);
1293 sws_freeContext( context );
1295 else if ( *format == mlt_image_rgb24 )
1297 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1298 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1300 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1301 set_luma_transfer( context, colorspace, full_range );
1302 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1303 output.data, output.linesize);
1304 sws_freeContext( context );
1306 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1308 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1309 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1311 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1312 set_luma_transfer( context, colorspace, full_range );
1313 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1314 output.data, output.linesize);
1315 sws_freeContext( context );
1319 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1320 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1322 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1323 set_luma_transfer( context, colorspace, full_range );
1324 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1325 output.data, output.linesize);
1326 sws_freeContext( context );
1329 if ( *format == mlt_image_yuv420p )
1332 pict.data[0] = buffer;
1333 pict.data[1] = buffer + width * height;
1334 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1335 pict.linesize[0] = width;
1336 pict.linesize[1] = width >> 1;
1337 pict.linesize[2] = width >> 1;
1338 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1340 else if ( *format == mlt_image_rgb24 )
1343 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1344 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1346 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
1349 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1350 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1355 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1356 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1361 /** Allocate the image buffer and set it on the frame.
1364 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1368 if ( codec_context->width == 0 || codec_context->height == 0 )
1370 *width = codec_context->width;
1371 *height = codec_context->height;
1372 size = mlt_image_format_size( *format, *width, *height, NULL );
1373 *buffer = mlt_pool_alloc( size );
1375 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1382 /** Get an image from a frame.
1385 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1388 producer_avformat self = mlt_frame_pop_service( frame );
1389 mlt_producer producer = self->parent;
1391 // Get the properties from the frame
1392 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1394 // Obtain the frame number of this frame
1395 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1397 // Get the producer properties
1398 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1400 pthread_mutex_lock( &self->video_mutex );
1402 // Fetch the video format context
1403 AVFormatContext *context = self->video_format;
1405 // Get the video stream
1406 AVStream *stream = context->streams[ self->video_index ];
1408 // Get codec context
1409 AVCodecContext *codec_context = stream->codec;
1411 uint8_t *alpha = NULL;
1413 // Get the image cache
1414 if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1416 self->image_cache = mlt_cache_init();
1417 self->alpha_cache = mlt_cache_init();
1419 if ( self->image_cache )
1421 mlt_cache_item item = mlt_cache_get( self->image_cache, (void*) position );
1422 uint8_t *original = mlt_cache_item_data( item, (int*) format );
1425 // Set the resolution
1426 *width = codec_context->width;
1427 *height = codec_context->height;
1429 // Workaround 1088 encodings missing cropping info.
1430 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1434 int size = mlt_image_format_size( *format, *width, *height, NULL );
1437 *buffer = mlt_pool_alloc( size );
1438 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1439 memcpy( *buffer, original, size );
1440 mlt_cache_item_close( item );
1445 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1446 mlt_frame_set_image( frame, *buffer, size, NULL );
1448 self->got_picture = 1;
1451 item = mlt_cache_get( self->alpha_cache, (void*) position );
1452 original = mlt_cache_item_data( item, &size );
1455 alpha = mlt_pool_alloc( size );
1456 memcpy( alpha, original, size );
1457 mlt_cache_item_close( item );
1460 goto exit_get_image;
1469 // Special case ffwd handling
1472 // We may want to use the source fps if available
1473 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1474 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1476 // This is the physical frame position in the source
1477 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1479 // Determines if we have to decode all frames in a sequence
1480 // Temporary hack to improve intra frame only
1481 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1482 strcmp( codec_context->codec->name, "dnxhd" ) &&
1483 strcmp( codec_context->codec->name, "dvvideo" ) &&
1484 strcmp( codec_context->codec->name, "huffyuv" ) &&
1485 strcmp( codec_context->codec->name, "mjpeg" ) &&
1486 strcmp( codec_context->codec->name, "rawvideo" ) );
1488 // Turn on usage of new seek API and PTS for seeking
1489 int use_new_seek = self->seekable &&
1490 codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1491 if ( mlt_properties_get( properties, "new_seek" ) )
1492 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1493 double delay = mlt_properties_get_double( properties, "video_delay" );
1495 // Seek if necessary
1496 int paused = seek_video( self, position, req_position, must_decode, use_new_seek, &ignore );
1498 // Seek might have reopened the file
1499 context = self->video_format;
1500 stream = context->streams[ self->video_index ];
1501 codec_context = stream->codec;
1502 if ( *format == mlt_image_none ||
1503 codec_context->pix_fmt == PIX_FMT_ARGB ||
1504 codec_context->pix_fmt == PIX_FMT_RGBA ||
1505 codec_context->pix_fmt == PIX_FMT_ABGR ||
1506 codec_context->pix_fmt == PIX_FMT_BGRA )
1507 *format = pick_format( codec_context->pix_fmt );
1509 // Duplicate the last image if necessary
1510 if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture
1512 || self->current_position == req_position
1513 || ( !use_new_seek && self->current_position > req_position ) ) )
1516 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1518 // Workaround 1088 encodings missing cropping info.
1519 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1522 if ( self->vdpau && self->vdpau->buffer )
1525 picture.data[0] = self->vdpau->buffer;
1526 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1527 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1528 picture.linesize[0] = codec_context->width;
1529 picture.linesize[1] = codec_context->width / 2;
1530 picture.linesize[2] = codec_context->width / 2;
1531 convert_image( (AVFrame*) &picture, *buffer,
1532 PIX_FMT_YUV420P, format, *width, *height, self->colorspace, &alpha );
1536 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1537 format, *width, *height, self->colorspace, &alpha );
1540 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1545 int64_t int_position = 0;
1546 int decode_errors = 0;
1547 int got_picture = 0;
1549 av_init_packet( &pkt );
1551 // Construct an AVFrame for YUV422 conversion
1552 if ( !self->av_frame )
1553 self->av_frame = avcodec_alloc_frame( );
1555 while( ret >= 0 && !got_picture )
1558 pthread_mutex_lock( &self->packets_mutex );
1559 if ( mlt_deque_count( self->vpackets ) )
1561 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1567 ret = av_read_frame( context, &pkt );
1568 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->audio_index )
1570 if ( !av_dup_packet( &pkt ) )
1572 AVPacket *tmp = malloc( sizeof(AVPacket) );
1574 mlt_deque_push_back( self->apackets, tmp );
1578 pthread_mutex_unlock( &self->packets_mutex );
1580 // We only deal with video from the selected video_index
1581 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1583 // Determine time code of the packet
1586 int64_t pts = pkt.pts;
1587 if ( self->first_pts > 0 )
1588 pts -= self->first_pts;
1589 else if ( context->start_time != AV_NOPTS_VALUE )
1590 pts -= context->start_time;
1591 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.1 );
1592 if ( pkt.pts == AV_NOPTS_VALUE )
1594 self->invalid_pts_counter++;
1595 if ( self->invalid_pts_counter > 20 )
1597 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1598 mlt_properties_set_int( properties, "new_seek", 0 );
1599 int_position = req_position;
1605 self->invalid_pts_counter = 0;
1607 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1608 pkt.pts, req_position, self->current_position, int_position );
1612 if ( pkt.dts != AV_NOPTS_VALUE )
1614 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pkt.dts + delay ) * source_fps + 0.5 );
1615 if ( context->start_time != AV_NOPTS_VALUE )
1616 int_position -= ( int64_t )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1617 if ( int_position == self->last_position )
1618 int_position = self->last_position + 1;
1620 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1621 pkt.dts, req_position, self->current_position, int_position );
1622 // Make a dumb assumption on streams that contain wild timestamps
1623 if ( abs( req_position - int_position ) > 999 )
1625 int_position = req_position;
1626 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1629 self->last_position = int_position;
1632 if ( must_decode || int_position >= req_position )
1637 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1639 vdpau_decoder_init( self );
1641 self->vdpau->is_decoded = 0;
1644 codec_context->reordered_opaque = pkt.pts;
1645 if ( int_position >= req_position )
1646 codec_context->skip_loop_filter = AVDISCARD_NONE;
1647 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1648 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1650 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1652 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1655 if ( ++decode_errors <= 10 )
1668 // Determine time code of the packet
1669 int64_t pts = self->av_frame->reordered_opaque;
1670 if ( self->first_pts > 0 )
1671 pts -= self->first_pts;
1672 else if ( context->start_time != AV_NOPTS_VALUE )
1673 pts -= context->start_time;
1674 int_position = ( int64_t )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1675 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %"PRId64", key %d\n", int_position, self->av_frame->key_frame );
1678 if ( int_position < req_position )
1683 else if ( int_position >= req_position )
1686 codec_context->skip_loop_filter = AVDISCARD_NONE;
1688 else if ( ignore -- )
1693 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1696 // Now handle the picture if we have one
1699 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1701 // Workaround 1088 encodings missing cropping info.
1702 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1707 if ( self->vdpau->is_decoded )
1709 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1711 uint32_t pitches[3];
1712 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1714 if ( !self->vdpau->buffer )
1715 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1716 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1717 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1718 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1719 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1720 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1721 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1723 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1724 if ( status == VDP_STATUS_OK )
1726 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1727 format, *width, *height, self->colorspace, &alpha );
1731 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1732 image_size = self->vdpau->is_decoded = 0;
1737 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1738 image_size = got_picture = 0;
1743 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1744 format, *width, *height, self->colorspace, &alpha );
1745 self->top_field_first |= self->av_frame->top_field_first;
1746 self->current_position = int_position;
1747 self->got_picture = 1;
1754 if ( self->seekable || pkt.stream_index != self->audio_index )
1755 av_free_packet( &pkt );
1759 if ( self->got_picture && image_size > 0 && self->image_cache )
1761 // Copy buffer to image cache
1762 uint8_t *image = mlt_pool_alloc( image_size );
1763 memcpy( image, *buffer, image_size );
1764 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1767 int alpha_size = (*width) * (*height);
1768 image = mlt_pool_alloc( alpha_size );
1769 memcpy( image, alpha, alpha_size );
1770 mlt_cache_put( self->alpha_cache, (void*) position, image, alpha_size, mlt_pool_release );
1773 // Try to duplicate last image if there was a decoding failure
1774 else if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1777 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1779 // Workaround 1088 encodings missing cropping info.
1780 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1783 if ( self->vdpau && self->vdpau->buffer )
1786 picture.data[0] = self->vdpau->buffer;
1787 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1788 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1789 picture.linesize[0] = codec_context->width;
1790 picture.linesize[1] = codec_context->width / 2;
1791 picture.linesize[2] = codec_context->width / 2;
1792 convert_image( (AVFrame*) &picture, *buffer,
1793 PIX_FMT_YUV420P, format, *width, *height, self->colorspace, &alpha );
1797 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1798 format, *width, *height, self->colorspace, &alpha );
1799 self->got_picture = 1;
1802 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1805 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1806 self->video_expected = position + 1;
1810 pthread_mutex_unlock( &self->video_mutex );
1812 // Set the progressive flag
1813 if ( mlt_properties_get( properties, "force_progressive" ) )
1814 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1815 else if ( self->av_frame )
1816 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1818 // Set the field order property for this frame
1819 if ( mlt_properties_get( properties, "force_tff" ) )
1820 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1822 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1824 // Set immutable properties of the selected track's (or overridden) source attributes.
1825 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1826 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1827 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1828 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1832 mlt_frame_set_alpha( frame, alpha, (*width) * (*height), mlt_pool_release );
1834 return !self->got_picture;
1837 /** Process properties as AVOptions and apply to AV context obj
1840 static void apply_properties( void *obj, mlt_properties properties, int flags )
1843 int count = mlt_properties_count( properties );
1844 for ( i = 0; i < count; i++ )
1846 const char *opt_name = mlt_properties_get_name( properties, i );
1847 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
1848 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1850 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1852 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1855 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1856 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1857 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1858 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1859 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1860 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1862 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1868 /** Initialize the video codec context.
1871 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1873 // Initialise the codec if necessary
1874 if ( !self->video_codec )
1876 // Get the video stream
1877 AVStream *stream = self->video_format->streams[ index ];
1879 // Get codec context
1880 AVCodecContext *codec_context = stream->codec;
1883 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1885 if ( codec_context->codec_id == CODEC_ID_H264 )
1887 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1889 if ( vdpau_init( self ) )
1891 self->video_codec = codec_context;
1892 if ( !vdpau_decoder_init( self ) )
1897 codec = avcodec_find_decoder( codec_context->codec_id );
1901 // Initialise multi-threading
1902 int thread_count = mlt_properties_get_int( properties, "threads" );
1903 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1904 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1905 if ( thread_count > 1 )
1906 codec_context->thread_count = thread_count;
1908 // If we don't have a codec and we can't initialise it, we can't do much more...
1909 pthread_mutex_lock( &self->open_mutex );
1910 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1911 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1913 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1916 // Now store the codec with its destructor
1917 self->video_codec = codec_context;
1921 // Remember that we can't use this later
1922 self->video_index = -1;
1923 pthread_mutex_unlock( &self->open_mutex );
1926 pthread_mutex_unlock( &self->open_mutex );
1928 // Process properties as AVOptions
1929 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1930 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1931 if ( codec->priv_class && codec_context->priv_data )
1932 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1935 // Reset some image properties
1936 mlt_properties_set_int( properties, "width", self->video_codec->width );
1937 mlt_properties_set_int( properties, "height", self->video_codec->height );
1938 // For DV, we'll just use the saved aspect ratio
1939 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1940 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1942 // Determine the fps first from the codec
1943 double source_fps = (double) self->video_codec->time_base.den /
1944 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1946 if ( mlt_properties_get( properties, "force_fps" ) )
1948 source_fps = mlt_properties_get_double( properties, "force_fps" );
1949 stream->time_base = av_d2q( source_fps, 1024 );
1950 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1951 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1955 // If the muxer reports a frame rate different than the codec
1956 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1957 double muxer_fps = av_q2d( stream->avg_frame_rate );
1958 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1959 muxer_fps = av_q2d( stream->r_frame_rate );
1961 double muxer_fps = av_q2d( stream->r_frame_rate );
1963 // Choose the lesser - the wrong tends to be off by some multiple of 10
1964 source_fps = FFMIN( source_fps, muxer_fps );
1965 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1967 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1968 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1970 else if ( muxer_fps > 0 )
1972 AVRational frame_rate = stream->r_frame_rate;
1973 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1974 // avg_frame_rate gives some approximate value that does not well match the media.
1975 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1976 // results in some very choppy output, but some value slightly different works
1978 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1979 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1980 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1982 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1983 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1984 source_fps = av_q2d( frame_rate );
1988 source_fps = mlt_producer_get_fps( self->parent );
1989 AVRational frame_rate = av_d2q( source_fps, 255 );
1990 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1991 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1995 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1996 if ( source_fps > 0 )
1997 mlt_properties_set_double( properties, "source_fps", source_fps );
1999 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
2001 // Set the YUV colorspace from override or detect
2002 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
2003 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
2004 if ( ! self->colorspace )
2006 switch ( self->video_codec->colorspace )
2008 case AVCOL_SPC_SMPTE240M:
2009 self->colorspace = 240;
2011 case AVCOL_SPC_BT470BG:
2012 case AVCOL_SPC_SMPTE170M:
2013 self->colorspace = 601;
2015 case AVCOL_SPC_BT709:
2016 self->colorspace = 709;
2019 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
2020 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
2025 // Let apps get chosen colorspace
2026 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
2028 return self->video_codec && self->video_index > -1;
2031 /** Set up video handling.
2034 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
2037 mlt_producer producer = self->parent;
2039 // Get the properties
2040 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2042 // Fetch the video format context
2043 AVFormatContext *context = self->video_format;
2045 // Get the video_index
2046 int index = mlt_properties_get_int( properties, "video_index" );
2048 // Reopen the file if necessary
2049 if ( !context && index > -1 )
2051 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2052 mlt_properties_get( properties, "resource" ), 1 );
2053 context = self->video_format;
2056 // Exception handling for video_index
2057 if ( context && index >= (int) context->nb_streams )
2059 // Get the last video stream
2060 for ( index = context->nb_streams - 1;
2061 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
2063 mlt_properties_set_int( properties, "video_index", index );
2065 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
2067 // Invalidate the video stream
2069 mlt_properties_set_int( properties, "video_index", index );
2072 // Update the video properties if the index changed
2073 if ( index != self->video_index )
2075 // Reset the video properties if the index changed
2076 self->video_index = index;
2077 pthread_mutex_lock( &self->open_mutex );
2078 if ( self->video_codec )
2079 avcodec_close( self->video_codec );
2080 self->video_codec = NULL;
2081 pthread_mutex_unlock( &self->open_mutex );
2084 // Get the frame properties
2085 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2088 if ( context && index > -1 && video_codec_init( self, index, properties ) )
2090 // Set the frame properties
2091 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
2092 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
2093 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
2095 // Set the width and height
2096 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
2097 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
2098 // real_width and real_height are deprecated in favor of meta.media.width and .height
2099 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
2100 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
2101 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
2102 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
2103 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
2104 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
2106 // Workaround 1088 encodings missing cropping info.
2107 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
2109 mlt_properties_set_int( properties, "meta.media.height", 1080 );
2110 mlt_properties_set_int( frame_properties, "real_height", 1080 );
2113 // Add our image operation
2114 mlt_frame_push_service( frame, self );
2115 mlt_frame_push_get_image( frame, producer_get_image );
2119 // If something failed, use test card image
2120 mlt_properties_set_int( frame_properties, "test_image", 1 );
2124 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
2128 // Seek if necessary
2129 if ( self->seekable && position != self->audio_expected )
2131 if ( position + 1 == self->audio_expected )
2133 // We're paused - silence required
2136 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
2138 // Fast forward - seeking is inefficient for small distances - just ignore following frames
2139 *ignore = position - self->audio_expected;
2141 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
2143 AVFormatContext *context = self->audio_format;
2144 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
2145 if ( context->start_time != AV_NOPTS_VALUE )
2146 timestamp += context->start_time;
2147 if ( timestamp < 0 )
2150 // Set to the real timecode
2151 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
2154 // Clear the usage in the audio buffer
2155 int i = MAX_AUDIO_STREAMS + 1;
2157 self->audio_used[i - 1] = 0;
2163 static int sample_bytes( AVCodecContext *context )
2165 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2166 return av_get_bytes_per_sample( context->sample_fmt );
2167 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2168 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2170 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2174 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2176 // Fetch the audio_format
2177 AVFormatContext *context = self->audio_format;
2179 // Get the current stream index
2180 int index = pkt.stream_index;
2182 // Get codec context
2183 AVCodecContext *codec_context = self->audio_codec[ index ];
2185 // Obtain the resample context if it exists (not always needed)
2186 ReSampleContext *resample = self->audio_resample[ index ];
2188 // Obtain the audio buffers
2189 uint8_t *audio_buffer = self->audio_buffer[ index ];
2190 uint8_t *decode_buffer = self->decode_buffer[ index ];
2192 int audio_used = self->audio_used[ index ];
2193 uint8_t *ptr = pkt.data;
2197 while ( ptr && ret >= 0 && len > 0 )
2199 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2200 int data_size = self->audio_buffer_size[ index ];
2203 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2204 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2205 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2206 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2208 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2212 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2216 pkt.size = len -= ret;
2217 pkt.data = ptr += ret;
2219 // If decoded successfully
2220 if ( data_size > 0 )
2222 // Figure out how many samples will be needed after resampling
2223 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2224 int samples_needed = self->resample_factor * convert_samples;
2226 // Resize audio buffer to prevent overflow
2227 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2229 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2230 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2234 // Copy to audio buffer while resampling
2235 uint8_t *source = decode_buffer;
2236 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2237 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2241 // Straight copy to audio buffer
2242 memcpy( &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ], decode_buffer, data_size );
2243 audio_used += convert_samples;
2247 while ( *ignore && audio_used )
2250 audio_used -= audio_used > samples ? samples : audio_used;
2251 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2252 audio_used * sizeof_sample );
2257 // If we're behind, ignore this packet
2258 // Skip this on non-seekable, audio-only inputs.
2259 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2261 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
2262 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2263 int64_t int_position = ( int64_t )( current_pts * fps + 0.5 );
2264 if ( context->start_time != AV_NOPTS_VALUE )
2265 int_position -= ( int64_t )( fps * context->start_time / AV_TIME_BASE + 0.5 );
2267 if ( int_position > 0 )
2269 if ( int_position < req_position )
2270 // We are behind, so skip some
2271 *ignore = req_position - int_position;
2272 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2273 // We are ahead, so seek backwards some more
2274 seek_audio( self, req_position, timecode - 1.0, ignore );
2278 self->audio_used[ index ] = audio_used;
2283 /** Get the audio from a frame.
2285 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2288 producer_avformat self = mlt_frame_pop_audio( frame );
2290 pthread_mutex_lock( &self->audio_mutex );
2292 // Obtain the frame number of this frame
2293 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
2295 // Calculate the real time code
2296 double real_timecode = producer_time_of_frame( self->parent, position );
2298 // Get the producer fps
2299 double fps = mlt_producer_get_fps( self->parent );
2301 // Number of frames to ignore (for ffwd)
2302 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2304 // Flag for paused (silence)
2305 int paused = seek_audio( self, position, real_timecode, &ignore[0] );
2307 // Initialize ignore for all streams from the seek return value
2308 int i = MAX_AUDIO_STREAMS;
2310 ignore[i] = ignore[0];
2312 // Fetch the audio_format
2313 AVFormatContext *context = self->audio_format;
2315 int sizeof_sample = sizeof( int16_t );
2317 // Determine the tracks to use
2318 int index = self->audio_index;
2319 int index_max = self->audio_index + 1;
2320 if ( self->audio_index == INT_MAX )
2323 index_max = context->nb_streams;
2324 *channels = self->total_channels;
2325 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2326 *frequency = FFMAX( self->max_frequency, *frequency );
2329 // Initialize the resamplers and buffers
2330 for ( ; index < index_max; index++ )
2332 // Get codec context
2333 AVCodecContext *codec_context = self->audio_codec[ index ];
2335 if ( codec_context && !self->audio_buffer[ index ] )
2337 // Check for resample and create if necessary
2338 if ( codec_context->channels <= 2 )
2340 // Determine by how much resampling will increase number of samples
2341 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2342 resample_factor *= (double) *frequency / codec_context->sample_rate;
2343 if ( resample_factor > self->resample_factor )
2344 self->resample_factor = resample_factor;
2346 // Create the resampler
2347 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2348 self->audio_resample[ index ] = av_audio_resample_init(
2349 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2350 codec_context->channels, *frequency, codec_context->sample_rate,
2351 AV_SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2353 self->audio_resample[ index ] = audio_resample_init(
2354 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2355 codec_context->channels, *frequency, codec_context->sample_rate );
2360 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2361 sizeof_sample = sample_bytes( codec_context );
2364 // Check for audio buffer and create if necessary
2365 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2366 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2368 // Check for decoder buffer and create if necessary
2369 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2373 // Get the audio if required
2380 av_init_packet( &pkt );
2382 // If not resampling, give consumer more than requested.
2383 // It requested number samples based on requested frame rate.
2384 // Do not clean this up with a samples *= ...!
2385 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2386 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2388 while ( ret >= 0 && !got_audio )
2390 // Check if the buffer already contains the samples required
2391 if ( self->audio_index != INT_MAX &&
2392 self->audio_used[ self->audio_index ] >= *samples &&
2393 ignore[ self->audio_index ] == 0 )
2398 else if ( self->audio_index == INT_MAX )
2400 // Check if there is enough audio for all streams
2402 for ( index = 0; got_audio && index < context->nb_streams; index++ )
2403 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2410 pthread_mutex_lock( &self->packets_mutex );
2411 if ( mlt_deque_count( self->apackets ) )
2413 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2419 ret = av_read_frame( context, &pkt );
2420 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2422 if ( !av_dup_packet( &pkt ) )
2424 AVPacket *tmp = malloc( sizeof(AVPacket) );
2426 mlt_deque_push_back( self->vpackets, tmp );
2430 pthread_mutex_unlock( &self->packets_mutex );
2432 // We only deal with audio from the selected audio index
2433 index = pkt.stream_index;
2434 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2435 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2437 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2438 self->audio_codec[index]->channels : *channels;
2439 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2442 if ( self->seekable || index != self->video_index )
2443 av_free_packet( &pkt );
2447 // Set some additional return values
2448 *format = mlt_audio_s16;
2449 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2451 index = self->audio_index;
2452 *channels = self->audio_codec[ index ]->channels;
2453 *frequency = self->audio_codec[ index ]->sample_rate;
2454 *format = self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_S32 ? mlt_audio_s32le
2455 : self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_FLT ? mlt_audio_f32le
2457 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2459 else if ( self->audio_index == INT_MAX )
2461 // This only works if all audio tracks have the same sample format.
2462 for ( index = 0; index < index_max; index++ )
2463 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2465 *format = self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_S32 ? mlt_audio_s32le
2466 : self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_FLT ? mlt_audio_f32le
2468 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2473 // Allocate and set the frame's audio buffer
2474 int size = mlt_audio_format_size( *format, *samples, *channels );
2475 *buffer = mlt_pool_alloc( size );
2476 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2478 // Interleave tracks if audio_index=all
2479 if ( self->audio_index == INT_MAX )
2481 uint8_t *dest = *buffer;
2483 for ( i = 0; i < *samples; i++ )
2485 for ( index = 0; index < index_max; index++ )
2486 if ( self->audio_codec[ index ] )
2488 int current_channels = self->audio_codec[ index ]->channels;
2489 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2490 memcpy( dest, src, current_channels * sizeof_sample );
2491 dest += current_channels * sizeof_sample;
2494 for ( index = 0; index < index_max; index++ )
2495 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2497 int current_channels = self->audio_codec[ index ]->channels;
2498 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2499 self->audio_used[index] -= *samples;
2500 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2503 // Copy a single track to the output buffer
2506 index = self->audio_index;
2508 // Now handle the audio if we have enough
2509 if ( self->audio_used[ index ] > 0 )
2511 uint8_t *src = self->audio_buffer[ index ];
2512 // copy samples from audio_buffer
2513 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2514 memcpy( *buffer, src, size * *channels * sizeof_sample );
2515 // supply the remaining requested samples as silence
2516 if ( *samples > self->audio_used[ index ] )
2517 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2518 // reposition the samples within audio_buffer
2519 self->audio_used[ index ] -= size;
2520 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2524 // Otherwise fill with silence
2525 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2531 // Get silence and don't touch the context
2532 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2535 // Regardless of speed (other than paused), we expect to get the next frame
2537 self->audio_expected = position + 1;
2539 pthread_mutex_unlock( &self->audio_mutex );
2544 /** Initialize the audio codec context.
2547 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2549 // Initialise the codec if necessary
2550 if ( !self->audio_codec[ index ] )
2552 // Get codec context
2553 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2556 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2558 // If we don't have a codec and we can't initialise it, we can't do much more...
2559 pthread_mutex_lock( &self->open_mutex );
2560 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2561 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2563 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2566 // Now store the codec with its destructor
2567 if ( self->audio_codec[ index ] )
2568 avcodec_close( self->audio_codec[ index ] );
2569 self->audio_codec[ index ] = codec_context;
2573 // Remember that we can't use self later
2574 self->audio_index = -1;
2576 pthread_mutex_unlock( &self->open_mutex );
2578 // Process properties as AVOptions
2579 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2580 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
2581 if ( codec && codec->priv_class && codec_context->priv_data )
2582 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2585 return self->audio_codec[ index ] && self->audio_index > -1;
2588 /** Set up audio handling.
2591 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2594 mlt_producer producer = self->parent;
2596 // Get the properties
2597 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2599 // Fetch the audio format context
2600 AVFormatContext *context = self->audio_format;
2602 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2604 // Get the audio_index
2605 int index = mlt_properties_get_int( properties, "audio_index" );
2607 // Handle all audio tracks
2608 if ( self->audio_index > -1 &&
2609 mlt_properties_get( properties, "audio_index" ) &&
2610 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2613 // Reopen the file if necessary
2614 if ( !context && self->audio_index > -1 && index > -1 )
2616 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2617 mlt_properties_get( properties, "resource" ), 1 );
2618 context = self->audio_format;
2621 // Exception handling for audio_index
2622 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2624 for ( index = context->nb_streams - 1;
2625 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2627 mlt_properties_set_int( properties, "audio_index", index );
2629 if ( context && index > -1 && index < INT_MAX &&
2630 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2632 index = self->audio_index;
2633 mlt_properties_set_int( properties, "audio_index", index );
2636 // Update the audio properties if the index changed
2637 if ( context && index > -1 && index != self->audio_index )
2639 pthread_mutex_lock( &self->open_mutex );
2640 if ( self->audio_codec[ self->audio_index ] )
2641 avcodec_close( self->audio_codec[ self->audio_index ] );
2642 self->audio_codec[ self->audio_index ] = NULL;
2643 pthread_mutex_unlock( &self->open_mutex );
2645 if ( self->audio_index != -1 )
2646 self->audio_index = index;
2651 if ( context && index == INT_MAX )
2653 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2654 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2655 for ( index = 0; index < context->nb_streams; index++ )
2657 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2658 audio_codec_init( self, index, properties );
2661 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2663 // Set the frame properties
2664 if ( index < INT_MAX )
2666 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2667 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2670 if ( context && index > -1 )
2672 // Add our audio operation
2673 mlt_frame_push_audio( frame, self );
2674 mlt_frame_push_audio( frame, producer_get_audio );
2678 /** Our get frame implementation.
2681 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2683 // Access the private data
2684 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2685 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2686 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2691 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2692 producer->child = self;
2693 self->parent = producer;
2694 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2695 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2698 // Create an empty frame
2699 *frame = mlt_frame_init( service);
2703 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2707 mlt_cache_item_close( cache_item );
2711 // Update timecode on the frame we're creating
2712 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2715 producer_set_up_video( self, *frame );
2718 producer_set_up_audio( self, *frame );
2720 // Set the position of this producer
2721 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2722 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", position );
2724 // Calculate the next timecode
2725 mlt_producer_prepare_next( producer );
2730 static void producer_avformat_close( producer_avformat self )
2732 mlt_log_debug( NULL, "producer_avformat_close\n" );
2734 // Cleanup av contexts
2735 av_free( self->av_frame );
2736 pthread_mutex_lock( &self->open_mutex );
2738 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2740 if ( self->audio_resample[i] )
2741 audio_resample_close( self->audio_resample[i] );
2742 mlt_pool_release( self->audio_buffer[i] );
2743 av_free( self->decode_buffer[i] );
2744 if ( self->audio_codec[i] )
2745 avcodec_close( self->audio_codec[i] );
2746 self->audio_codec[i] = NULL;
2748 if ( self->video_codec )
2749 avcodec_close( self->video_codec );
2750 self->video_codec = NULL;
2752 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2753 if ( self->dummy_context )
2754 avformat_close_input( &self->dummy_context );
2755 if ( self->seekable && self->audio_format )
2756 avformat_close_input( &self->audio_format );
2757 if ( self->video_format )
2758 avformat_close_input( &self->video_format );
2760 if ( self->dummy_context )
2761 av_close_input_file( self->dummy_context );
2762 if ( self->seekable && self->audio_format )
2763 av_close_input_file( self->audio_format );
2764 if ( self->video_format )
2765 av_close_input_file( self->video_format );
2767 pthread_mutex_unlock( &self->open_mutex );
2769 vdpau_producer_close( self );
2771 if ( self->image_cache )
2772 mlt_cache_close( self->image_cache );
2773 if ( self->alpha_cache )
2774 mlt_cache_close( self->alpha_cache );
2776 // Cleanup the mutexes
2777 pthread_mutex_destroy( &self->audio_mutex );
2778 pthread_mutex_destroy( &self->video_mutex );
2779 pthread_mutex_destroy( &self->packets_mutex );
2780 pthread_mutex_destroy( &self->open_mutex );
2782 // Cleanup the packet queues
2784 if ( self->apackets )
2786 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2788 av_free_packet( pkt );
2791 mlt_deque_close( self->apackets );
2792 self->apackets = NULL;
2794 if ( self->vpackets )
2796 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2798 av_free_packet( pkt );
2801 mlt_deque_close( self->vpackets );
2802 self->vpackets = NULL;
2808 static void producer_close( mlt_producer parent )
2810 // Remove this instance from the cache
2811 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2814 parent->close = NULL;
2815 mlt_producer_close( parent );