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;
105 uint8_t *audio_buffer[ MAX_AUDIO_STREAMS ];
106 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
107 uint8_t *decode_buffer[ MAX_AUDIO_STREAMS ];
108 int audio_used[ MAX_AUDIO_STREAMS ];
110 int audio_max_stream;
114 unsigned int invalid_pts_counter;
115 double resample_factor;
116 mlt_cache image_cache;
118 pthread_mutex_t video_mutex;
119 pthread_mutex_t audio_mutex;
122 pthread_mutex_t packets_mutex;
123 pthread_mutex_t open_mutex;
128 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
142 typedef struct producer_avformat_s *producer_avformat;
144 // Forward references.
145 static int list_components( char* file );
146 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock );
147 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
148 static void producer_avformat_close( producer_avformat );
149 static void producer_close( mlt_producer parent );
150 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
151 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
152 static void apply_properties( void *obj, mlt_properties properties, int flags );
153 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
154 static void get_audio_streams_info( producer_avformat self );
160 /** Constructor for libavformat.
163 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
165 if ( list_components( file ) )
168 mlt_producer producer = NULL;
170 // Check that we have a non-NULL argument
173 // Construct the producer
174 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
175 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
178 if ( mlt_producer_init( producer, self ) == 0 )
180 self->parent = producer;
182 // Get the properties
183 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
185 // Set the resource property (required for all producers)
186 mlt_properties_set( properties, "resource", file );
188 // Register transport implementation with the producer
189 producer->close = (mlt_destructor) producer_close;
191 // Register our get_frame implementation
192 producer->get_frame = producer_get_frame;
194 if ( strcmp( service, "avformat-novalidate" ) )
197 if ( producer_open( self, profile, file, 1 ) != 0 )
200 mlt_producer_close( producer );
203 else if ( self->seekable )
205 // Close the file to release resources for large playlists - reopen later as needed
206 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
207 if ( self->audio_format )
208 avformat_close_input( &self->audio_format );
209 if ( self->video_format )
210 avformat_close_input( &self->video_format );
212 if ( self->audio_format )
213 av_close_input_file( self->audio_format );
214 if ( self->video_format )
215 av_close_input_file( self->video_format );
217 self->audio_format = NULL;
218 self->video_format = NULL;
223 // Default the user-selectable indices from the auto-detected indices
224 mlt_properties_set_int( properties, "audio_index", self->audio_index );
225 mlt_properties_set_int( properties, "video_index", self->video_index );
227 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
229 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
236 int list_components( char* file )
240 // Report information about available demuxers and codecs as YAML Tiny
241 if ( file && strstr( file, "f-list" ) )
243 fprintf( stderr, "---\nformats:\n" );
244 AVInputFormat *format = NULL;
245 while ( ( format = av_iformat_next( format ) ) )
246 fprintf( stderr, " - %s\n", format->name );
247 fprintf( stderr, "...\n" );
250 if ( file && strstr( file, "acodec-list" ) )
252 fprintf( stderr, "---\naudio_codecs:\n" );
253 AVCodec *codec = NULL;
254 while ( ( codec = av_codec_next( codec ) ) )
255 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
256 fprintf( stderr, " - %s\n", codec->name );
257 fprintf( stderr, "...\n" );
260 if ( file && strstr( file, "vcodec-list" ) )
262 fprintf( stderr, "---\nvideo_codecs:\n" );
263 AVCodec *codec = NULL;
264 while ( ( codec = av_codec_next( codec ) ) )
265 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
266 fprintf( stderr, " - %s\n", codec->name );
267 fprintf( stderr, "...\n" );
274 /** Find the default streams.
277 static mlt_properties find_default_streams( producer_avformat self )
281 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
282 AVDictionaryEntry *tag = NULL;
284 AVMetadataTag *tag = NULL;
286 AVFormatContext *context = self->video_format;
287 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
289 // Default to the first audio and video streams found
290 self->audio_index = -1;
291 self->video_index = -1;
293 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
295 // Allow for multiple audio and video streams in the file and select first of each (if available)
296 for( i = 0; i < context->nb_streams; i++ )
298 // Get the codec context
299 AVStream *stream = context->streams[ i ];
300 if ( ! stream ) continue;
301 AVCodecContext *codec_context = stream->codec;
302 if ( ! codec_context ) continue;
303 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
304 if ( ! codec ) continue;
306 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
308 // Determine the type and obtain the first index of each type
309 switch( codec_context->codec_type )
311 case CODEC_TYPE_VIDEO:
312 // Use first video stream
313 if ( self->video_index < 0 )
314 self->video_index = i;
315 mlt_properties_set( meta_media, key, "video" );
316 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
317 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
318 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
319 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
320 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
321 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
323 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
326 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
327 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
328 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
330 snprintf( key, sizeof(key), "meta.media.%d.codec.width", i );
331 mlt_properties_set_int( meta_media, key, codec_context->width );
332 snprintf( key, sizeof(key), "meta.media.%d.codec.height", i );
333 mlt_properties_set_int( meta_media, key, codec_context->height );
334 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
335 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
336 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
337 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
338 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(3<<8)+0)
339 mlt_properties_set( meta_media, key, av_get_pix_fmt_name( codec_context->pix_fmt ) );
341 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
343 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
344 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
345 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
346 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
347 switch ( codec_context->colorspace )
349 case AVCOL_SPC_SMPTE240M:
350 mlt_properties_set_int( meta_media, key, 240 );
352 case AVCOL_SPC_BT470BG:
353 case AVCOL_SPC_SMPTE170M:
354 mlt_properties_set_int( meta_media, key, 601 );
356 case AVCOL_SPC_BT709:
357 mlt_properties_set_int( meta_media, key, 709 );
360 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
361 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
366 case CODEC_TYPE_AUDIO:
367 if ( !codec_context->channels )
369 // Use first audio stream
370 if ( self->audio_index < 0 )
371 self->audio_index = i;
372 mlt_properties_set( meta_media, key, "audio" );
373 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
374 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
375 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
376 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
377 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
378 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
380 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
381 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
382 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
383 mlt_properties_set_int( meta_media, key, codec_context->channels );
388 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
389 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
390 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
391 mlt_properties_set( meta_media, key, codec->name );
392 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
393 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
394 mlt_properties_set( meta_media, key, codec->long_name );
396 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
397 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
398 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
399 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
400 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
401 // mlt_properties_set_int( meta_media, key, codec_context->profile );
402 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
403 // mlt_properties_set_int( meta_media, key, codec_context->level );
406 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
407 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
408 while ( ( tag = av_dict_get( stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
410 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
413 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
415 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
416 mlt_properties_set( meta_media, key, tag->value );
421 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
422 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
423 while ( ( tag = av_dict_get( context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
425 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
428 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
430 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
431 mlt_properties_set( meta_media, key, tag->value );
435 if ( context->title && strcmp( context->title, "" ) )
436 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
437 if ( context->author && strcmp( context->author, "" ) )
438 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
439 if ( context->copyright && strcmp( context->copyright, "" ) )
440 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
441 if ( context->comment )
442 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
443 if ( context->album )
444 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
446 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
447 if ( context->track )
448 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
454 static inline int dv_is_pal( AVPacket *pkt )
456 return pkt->data[3] & 0x80;
459 static int dv_is_wide( AVPacket *pkt )
461 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
463 for ( ; i < pkt->size; i += 5 /* packet size */ )
465 if ( pkt->data[ i ] == 0x61 )
467 uint8_t x = pkt->data[ i + 2 ] & 0x7;
468 return ( x == 2 ) || ( x == 7 );
474 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
476 double aspect_ratio = 1.0;
478 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
482 if ( dv_is_pal( pkt ) )
484 if ( dv_is_wide( pkt ) )
486 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
487 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
491 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
492 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
497 if ( dv_is_wide( pkt ) )
499 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
500 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
504 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
505 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
512 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
513 stream->sample_aspect_ratio;
515 codec_context->sample_aspect_ratio;
517 // Override FFmpeg's notion of DV aspect ratios, which are
518 // based upon a width of 704. Since we do not have a normaliser
519 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
520 // we just coerce the values to facilitate a passive behaviour through
521 // the rescale normaliser when using equivalent producers and consumers.
522 // = display_aspect / (width * height)
523 if ( ar.num == 10 && ar.den == 11 )
526 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
527 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
529 else if ( ar.num == 59 && ar.den == 54 )
532 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
533 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
535 else if ( ar.num == 40 && ar.den == 33 )
538 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
539 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
541 else if ( ar.num == 118 && ar.den == 81 )
544 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
545 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
551 AVRational codec_sar = codec_context->sample_aspect_ratio;
552 AVRational stream_sar =
553 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
554 stream->sample_aspect_ratio;
558 if ( codec_sar.num > 0 )
560 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
561 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
563 else if ( stream_sar.num > 0 )
565 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
566 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
570 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
571 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
574 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
575 aspect_ratio = av_q2d( ar );
576 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
581 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
582 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVDictionary **params )
584 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
587 if ( !URL ) return NULL;
590 char *protocol = strdup( URL );
591 char *url = strchr( protocol, ':' );
593 // Only if there is not a protocol specification that avformat can handle
594 #if LIBAVFORMAT_VERSION_MAJOR >= 53
595 if ( url && avio_check( URL, 0 ) < 0 )
597 if ( url && !url_exist( URL ) )
600 // Truncate protocol string
602 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
605 *format = av_find_input_format( protocol );
607 // Eat the format designator
612 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
613 // support for legacy width and height parameters
617 // These are required by video4linux2 (defaults)
618 params->width = profile->width;
619 params->height = profile->height;
620 if ( !strstr( URL, "&frame_rate" ) )
621 params->time_base = (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
622 params->channels = 2;
623 params->sample_rate = 48000;
627 url = strchr( url, '?' );
631 char *name = strdup( ++url );
632 char *value = strchr( name, '=' );
634 // Also accept : as delimiter for backwards compatibility.
635 value = strchr( name, ':' );
640 char *t = strchr( value, '&' );
643 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
644 // translate old parameters to new av_dict names
645 if ( !strcmp( name, "frame_rate" ) )
646 av_dict_set( params, "framerate", value, 0 );
647 else if ( !strcmp( name, "pix_fmt" ) )
648 av_dict_set( params, "pixel_format", value, 0 );
649 else if ( !strcmp( name, "width" ) )
650 width = strdup( value );
651 else if ( !strcmp( name, "height" ) )
652 height = strdup( value );
654 // generic demux/device option support
655 av_dict_set( params, name, value, 0 );
657 if ( !strcmp( name, "frame_rate" ) )
658 params->time_base.den = atoi( value );
659 else if ( !strcmp( name, "frame_rate_base" ) )
660 params->time_base.num = atoi( value );
661 else if ( !strcmp( name, "sample_rate" ) )
662 params->sample_rate = atoi( value );
663 else if ( !strcmp( name, "channel" ) )
664 params->channel = atoi( value );
665 else if ( !strcmp( name, "channels" ) )
666 params->channels = atoi( value );
667 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
668 else if ( !strcmp( name, "pix_fmt" ) )
669 params->pix_fmt = av_get_pix_fmt( value );
671 else if ( !strcmp( name, "width" ) )
672 params->width = atoi( value );
673 else if ( !strcmp( name, "height" ) )
674 params->height = atoi( value );
675 else if ( !strcmp( name, "standard" ) )
676 params->standard = strdup( value );
680 url = strchr( url, '&' );
682 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
683 // continued support for legacy width and height parameters
684 if ( width && height )
686 char *s = malloc( strlen( width ) + strlen( height ) + 2 );
690 av_dict_set( params, "video_size", s, 0 );
693 if ( width ) free( width );
694 if ( height ) free ( height );
697 result = strdup( result );
701 result = strdup( URL );
707 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
711 // Get the properties
712 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
714 AVFormatContext *format = self->video_format;
716 // We will treat everything with the producer fps.
717 // TODO: make this more flexible.
718 double fps = mlt_profile_fps( profile );
721 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
723 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
724 // when producer_open is called after initial call when restoring or reseting the producer.
725 if ( format->duration != AV_NOPTS_VALUE )
727 // This isn't going to be accurate for all formats
728 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
729 mlt_properties_set_position( properties, "out", frames - 1 );
730 mlt_properties_set_position( properties, "length", frames );
731 mlt_properties_set_int( properties, "_length_computed", 1 );
735 // Set live sources to run forever
736 mlt_properties_set_position( properties, "length", INT_MAX );
737 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
738 mlt_properties_set( properties, "eof", "loop" );
739 mlt_properties_set_int( properties, "_length_computed", 1 );
743 // Check if we're seekable
744 // avdevices are typically AVFMT_NOFILE and not seekable
745 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
748 // protocols can indicate if they support seeking
749 #if LIBAVFORMAT_VERSION_MAJOR >= 53
750 self->seekable = format->pb->seekable;
752 URLContext *uc = url_fileno( format->pb );
754 self->seekable = !uc->is_streamed;
757 if ( self->seekable )
759 // Do a more rigourous test of seekable on a disposable context
760 self->seekable = av_seek_frame( format, -1, format->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
761 mlt_properties_set_int( properties, "seekable", self->seekable );
762 self->dummy_context = format;
763 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
764 self->video_format = NULL;
765 avformat_open_input( &self->video_format, filename, NULL, NULL );
766 avformat_find_stream_info( self->video_format, NULL );
768 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
769 av_find_stream_info( self->video_format );
771 format = self->video_format;
774 // Fetch the width, height and aspect ratio
775 if ( self->video_index != -1 )
777 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
778 mlt_properties_set_int( properties, "width", codec_context->width );
779 mlt_properties_set_int( properties, "height", codec_context->height );
781 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
783 // Fetch the first frame of DV so we can read it directly
788 ret = av_read_frame( format, &pkt );
789 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
791 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
798 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
802 // Verify that we can convert this to YUV 4:2:2
803 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
804 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
805 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
807 sws_freeContext( context );
818 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
820 // Return an error code (0 == no error)
822 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
827 pthread_mutex_init( &self->audio_mutex, NULL );
828 pthread_mutex_init( &self->video_mutex, NULL );
829 pthread_mutex_init( &self->packets_mutex, NULL );
830 pthread_mutex_init( &self->open_mutex, NULL );
831 pthread_mutex_lock( &self->audio_mutex );
832 pthread_mutex_lock( &self->video_mutex );
834 mlt_events_block( properties, self->parent );
837 AVInputFormat *format = NULL;
838 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
839 AVDictionary *params = NULL;
841 AVFormatParameters params;
842 memset( ¶ms, 0, sizeof(params) );
844 char *filename = parse_url( profile, URL, &format, ¶ms );
846 // Now attempt to open the file or device with filename
847 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
848 error = avformat_open_input( &self->video_format, filename, format, ¶ms ) < 0;
850 // If the URL is a network stream URL, then we probably need to open with full URL
851 error = avformat_open_input( &self->video_format, URL, format, ¶ms ) < 0;
853 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
855 // If the URL is a network stream URL, then we probably need to open with full URL
856 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
859 // Set MLT properties onto video AVFormatContext
860 if ( !error && self->video_format )
862 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
863 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
864 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
865 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
869 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
870 av_dict_free( ¶ms );
872 // Cleanup AVFormatParameters
873 if ( params.standard )
874 free( (void*) params.standard );
877 // If successful, then try to get additional info
878 if ( !error && self->video_format )
880 // Get the stream info
881 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
882 error = avformat_find_stream_info( self->video_format, NULL ) < 0;
884 error = av_find_stream_info( self->video_format ) < 0;
887 // Continue if no error
888 if ( !error && self->video_format )
890 // Find default audio and video streams
891 find_default_streams( self );
892 error = get_basic_info( self, profile, filename );
894 // Initialize position info
895 self->first_pts = -1;
896 self->last_position = POSITION_INITIAL;
898 if ( !self->audio_format )
900 // We're going to cheat here - for seekable A/V files, we will have separate contexts
901 // to support independent seeking of audio from video.
902 // TODO: Is this really necessary?
903 if ( self->audio_index != -1 && self->video_index != -1 )
905 if ( self->seekable )
907 // And open again for our audio context
908 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
909 avformat_open_input( &self->audio_format, filename, NULL, NULL );
910 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
911 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
912 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
913 avformat_find_stream_info( self->audio_format, NULL );
915 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
916 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
917 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
918 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
919 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
921 av_find_stream_info( self->audio_format );
926 self->audio_format = self->video_format;
929 else if ( self->audio_index != -1 )
931 // We only have an audio context
932 self->audio_format = self->video_format;
933 self->video_format = NULL;
935 else if ( self->video_index == -1 )
937 // Something has gone wrong
940 if ( self->audio_format && !self->audio_streams )
941 get_audio_streams_info( self );
949 self->apackets = mlt_deque_init();
950 self->vpackets = mlt_deque_init();
953 if ( self->dummy_context )
955 pthread_mutex_lock( &self->open_mutex );
956 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
957 avformat_close_input( &self->dummy_context );
959 av_close_input_file( self->dummy_context );
961 self->dummy_context = NULL;
962 pthread_mutex_unlock( &self->open_mutex );
965 // Unlock the service
968 pthread_mutex_unlock( &self->audio_mutex );
969 pthread_mutex_unlock( &self->video_mutex );
971 mlt_events_unblock( properties, self->parent );
976 static void reopen_video( producer_avformat self, mlt_producer producer )
978 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
979 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
980 pthread_mutex_lock( &self->audio_mutex );
981 pthread_mutex_lock( &self->open_mutex );
983 if ( self->video_codec )
984 avcodec_close( self->video_codec );
985 self->video_codec = NULL;
986 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
987 if ( self->dummy_context )
988 avformat_close_input( &self->dummy_context );
989 if ( self->video_format )
990 avformat_close_input( &self->video_format );
992 if ( self->dummy_context )
993 av_close_input_file( self->dummy_context );
994 if ( self->video_format )
995 av_close_input_file( self->video_format );
997 self->dummy_context = NULL;
998 self->video_format = NULL;
999 pthread_mutex_unlock( &self->open_mutex );
1001 int audio_index = self->audio_index;
1002 int video_index = self->video_index;
1004 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1005 mlt_properties_get( properties, "resource" ), 0 );
1007 self->audio_index = audio_index;
1008 if ( self->video_format && video_index > -1 )
1010 self->video_index = video_index;
1011 video_codec_init( self, video_index, properties );
1014 pthread_mutex_unlock( &self->audio_mutex );
1015 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1018 static int seek_video( producer_avformat self, mlt_position position,
1019 int64_t req_position, int must_decode, int use_new_seek, int *ignore )
1021 mlt_producer producer = self->parent;
1024 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
1026 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1028 // Fetch the video format context
1029 AVFormatContext *context = self->video_format;
1031 // Get the video stream
1032 AVStream *stream = context->streams[ self->video_index ];
1034 // Get codec context
1035 AVCodecContext *codec_context = stream->codec;
1037 // We may want to use the source fps if available
1038 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1039 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1041 if ( self->av_frame && position + 1 == self->video_expected )
1043 // We're paused - use last image
1046 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
1048 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1049 *ignore = ( int )( ( position - self->video_expected ) / mlt_producer_get_fps( producer ) * source_fps );
1050 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1052 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
1054 if ( use_new_seek && self->last_position == POSITION_INITIAL )
1056 // find first key frame
1061 while ( ret >= 0 && toscan-- > 0 )
1063 ret = av_read_frame( context, &pkt );
1064 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
1066 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) );
1067 self->first_pts = pkt.pts;
1070 av_free_packet( &pkt );
1073 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1076 // Calculate the timestamp for the requested frame
1080 timestamp = ( req_position - 0.1 / source_fps ) /
1081 ( av_q2d( stream->time_base ) * source_fps );
1082 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pos %"PRId64" pts %"PRId64"\n", req_position, timestamp );
1083 if ( self->first_pts > 0 )
1084 timestamp += self->first_pts;
1085 else if ( context->start_time != AV_NOPTS_VALUE )
1086 timestamp += context->start_time;
1087 if ( req_position <= 0 )
1092 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
1093 if ( context->start_time != AV_NOPTS_VALUE )
1094 timestamp += context->start_time;
1097 timestamp -= AV_TIME_BASE;
1098 if ( timestamp < 0 )
1100 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
1101 timestamp, position, self->video_expected, self->last_position );
1103 // Seek to the timestamp
1106 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1107 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1109 else if ( req_position > 0 || self->last_position <= 0 )
1111 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
1115 // Re-open video stream when rewinding to beginning from somewhere else.
1116 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1117 // not reliably seeking to the first frame across formats.
1118 reopen_video( self, producer );
1121 // Remove the cached info relating to the previous position
1122 self->current_position = POSITION_INVALID;
1123 self->last_position = POSITION_INVALID;
1124 av_freep( &self->av_frame );
1128 // flush any pictures still in decode buffer
1129 avcodec_flush_buffers( codec_context );
1136 /** Convert a frame position to a time code.
1139 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1141 return ( double )position / mlt_producer_get_fps( producer );
1144 // Collect information about all audio streams
1146 static void get_audio_streams_info( producer_avformat self )
1148 // Fetch the audio format context
1149 AVFormatContext *context = self->audio_format;
1153 i < context->nb_streams;
1156 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1158 AVCodecContext *codec_context = context->streams[i]->codec;
1159 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1161 // If we don't have a codec and we can't initialise it, we can't do much more...
1162 pthread_mutex_lock( &self->open_mutex );
1163 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1164 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1166 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1169 self->audio_streams++;
1170 self->audio_max_stream = i;
1171 self->total_channels += codec_context->channels;
1172 if ( codec_context->channels > self->max_channel )
1173 self->max_channel = codec_context->channels;
1174 if ( codec_context->sample_rate > self->max_frequency )
1175 self->max_frequency = codec_context->sample_rate;
1176 avcodec_close( codec_context );
1178 pthread_mutex_unlock( &self->open_mutex );
1181 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1182 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1184 // Other audio-specific initializations
1185 self->resample_factor = 1.0;
1188 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1190 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1192 const int *new_coefficients;
1194 int brightness, contrast, saturation;
1196 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1197 &brightness, &contrast, &saturation ) != -1 )
1199 // Don't change these from defaults unless explicitly told to.
1200 if ( use_full_range >= 0 )
1201 full_range = use_full_range;
1202 switch ( colorspace )
1208 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1211 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1214 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1217 new_coefficients = coefficients;
1220 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1221 brightness, contrast, saturation );
1226 static mlt_image_format pick_format( enum PixelFormat pix_fmt )
1234 return mlt_image_rgb24a;
1235 case PIX_FMT_YUV420P:
1236 case PIX_FMT_YUVJ420P:
1237 case PIX_FMT_YUVA420P:
1238 return mlt_image_yuv420p;
1242 case PIX_FMT_MONOWHITE:
1243 case PIX_FMT_MONOBLACK:
1246 return mlt_image_rgb24;
1248 return mlt_image_yuv422;
1252 static void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
1253 mlt_image_format *format, int width, int height, int colorspace, uint8_t **alpha )
1256 int full_range = -1;
1257 int flags = SWS_BICUBIC | SWS_ACCURATE_RND;
1260 flags |= SWS_CPU_CAPS_MMX;
1263 flags |= SWS_CPU_CAPS_MMX2;
1266 // extract alpha from planar formats
1267 if ( ( pix_fmt == PIX_FMT_YUVA420P
1268 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(35<<8)+101)
1269 || pix_fmt == PIX_FMT_YUVA444P
1272 *format != mlt_image_rgb24a && *format != mlt_image_opengl &&
1273 frame->data[3] && frame->linesize[3] )
1278 dst = *alpha = mlt_pool_alloc( width * height );
1279 src = frame->data[3];
1281 for ( i = 0; i < height; dst += width, src += frame->linesize[3], i++ )
1282 memcpy( dst, src, FFMIN( width, frame->linesize[3] ) );
1285 if ( *format == mlt_image_yuv420p )
1287 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1288 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1290 output.data[0] = buffer;
1291 output.data[1] = buffer + width * height;
1292 output.data[2] = buffer + ( 5 * width * height ) / 4;
1293 output.linesize[0] = width;
1294 output.linesize[1] = width >> 1;
1295 output.linesize[2] = width >> 1;
1296 set_luma_transfer( context, colorspace, full_range );
1297 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1298 output.data, output.linesize);
1299 sws_freeContext( context );
1301 else if ( *format == mlt_image_rgb24 )
1303 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1304 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1306 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1307 set_luma_transfer( context, colorspace, full_range );
1308 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1309 output.data, output.linesize);
1310 sws_freeContext( context );
1312 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1314 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1315 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1317 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1318 set_luma_transfer( context, colorspace, full_range );
1319 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1320 output.data, output.linesize);
1321 sws_freeContext( context );
1325 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1326 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1328 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1329 set_luma_transfer( context, colorspace, full_range );
1330 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1331 output.data, output.linesize);
1332 sws_freeContext( context );
1335 if ( *format == mlt_image_yuv420p )
1338 pict.data[0] = buffer;
1339 pict.data[1] = buffer + width * height;
1340 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1341 pict.linesize[0] = width;
1342 pict.linesize[1] = width >> 1;
1343 pict.linesize[2] = width >> 1;
1344 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1346 else if ( *format == mlt_image_rgb24 )
1349 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1350 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1352 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
1355 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1356 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1361 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1362 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1367 /** Allocate the image buffer and set it on the frame.
1370 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1374 if ( codec_context->width == 0 || codec_context->height == 0 )
1376 *width = codec_context->width;
1377 *height = codec_context->height;
1378 size = mlt_image_format_size( *format, *width, *height, NULL );
1379 *buffer = mlt_pool_alloc( size );
1381 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1388 /** Get an image from a frame.
1391 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1394 producer_avformat self = mlt_frame_pop_service( frame );
1395 mlt_producer producer = self->parent;
1397 // Get the properties from the frame
1398 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1400 // Obtain the frame number of this frame
1401 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1403 // Get the producer properties
1404 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1406 pthread_mutex_lock( &self->video_mutex );
1408 // Fetch the video format context
1409 AVFormatContext *context = self->video_format;
1411 // Get the video stream
1412 AVStream *stream = context->streams[ self->video_index ];
1414 // Get codec context
1415 AVCodecContext *codec_context = stream->codec;
1417 uint8_t *alpha = NULL;
1418 int got_picture = 0;
1421 // Get the image cache
1422 if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1424 self->image_cache = mlt_cache_init();
1426 if ( self->image_cache )
1428 mlt_frame original = mlt_cache_get_frame( self->image_cache, mlt_frame_get_position( frame ) );
1431 // Set the resolution
1432 *width = codec_context->width;
1433 *height = codec_context->height;
1435 // Workaround 1088 encodings missing cropping info.
1436 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1440 *buffer = mlt_properties_get_data( MLT_FRAME_PROPERTIES( original ), "alpha", &size );
1442 mlt_frame_set_alpha( frame, *buffer, size, NULL );
1443 *buffer = mlt_properties_get_data( MLT_FRAME_PROPERTIES( original ), "image", &size );
1444 mlt_frame_set_image( frame, *buffer, size, NULL );
1445 mlt_properties_set_data( frame_properties, "avformat.image_cache", original, 0, (mlt_destructor) mlt_frame_close, NULL );
1448 goto exit_get_image;
1456 // Special case ffwd handling
1459 // We may want to use the source fps if available
1460 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1461 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1463 // This is the physical frame position in the source
1464 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1466 // Determines if we have to decode all frames in a sequence
1467 // Temporary hack to improve intra frame only
1468 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1469 strcmp( codec_context->codec->name, "dnxhd" ) &&
1470 strcmp( codec_context->codec->name, "dvvideo" ) &&
1471 strcmp( codec_context->codec->name, "huffyuv" ) &&
1472 strcmp( codec_context->codec->name, "mjpeg" ) &&
1473 strcmp( codec_context->codec->name, "rawvideo" ) );
1475 // Turn on usage of new seek API and PTS for seeking
1476 int use_new_seek = self->seekable &&
1477 codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1478 if ( mlt_properties_get( properties, "new_seek" ) )
1479 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1480 double delay = mlt_properties_get_double( properties, "video_delay" );
1482 // Seek if necessary
1483 const char *interp = mlt_properties_get( frame_properties, "rescale.interp" );
1484 int preseek = must_decode
1485 #if defined(FFUDIV) && LIBAVFORMAT_VERSION_INT >= ((53<<16)+(24<<8)+2)
1486 && ( !use_new_seek || ( interp && strcmp( interp, "nearest" ) ) )
1488 && codec_context->has_b_frames;
1489 int paused = seek_video( self, position, req_position, preseek, use_new_seek, &ignore );
1491 // Seek might have reopened the file
1492 context = self->video_format;
1493 stream = context->streams[ self->video_index ];
1494 codec_context = stream->codec;
1495 if ( *format == mlt_image_none ||
1496 codec_context->pix_fmt == PIX_FMT_ARGB ||
1497 codec_context->pix_fmt == PIX_FMT_RGBA ||
1498 codec_context->pix_fmt == PIX_FMT_ABGR ||
1499 codec_context->pix_fmt == PIX_FMT_BGRA )
1500 *format = pick_format( codec_context->pix_fmt );
1502 // Duplicate the last image if necessary
1503 if ( self->av_frame && self->av_frame->linesize[0]
1504 && ( paused || self->current_position >= req_position ) )
1507 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1509 // Workaround 1088 encodings missing cropping info.
1510 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1513 if ( self->vdpau && self->vdpau->buffer )
1516 picture.data[0] = self->vdpau->buffer;
1517 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1518 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1519 picture.linesize[0] = codec_context->width;
1520 picture.linesize[1] = codec_context->width / 2;
1521 picture.linesize[2] = codec_context->width / 2;
1522 convert_image( (AVFrame*) &picture, *buffer,
1523 PIX_FMT_YUV420P, format, *width, *height, self->colorspace, &alpha );
1527 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1528 format, *width, *height, self->colorspace, &alpha );
1535 int64_t int_position = 0;
1536 int decode_errors = 0;
1538 av_init_packet( &pkt );
1540 // Construct an AVFrame for YUV422 conversion
1541 if ( !self->av_frame )
1542 self->av_frame = avcodec_alloc_frame( );
1544 while( ret >= 0 && !got_picture )
1547 pthread_mutex_lock( &self->packets_mutex );
1548 if ( mlt_deque_count( self->vpackets ) )
1550 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1556 ret = av_read_frame( context, &pkt );
1557 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->audio_index )
1559 if ( !av_dup_packet( &pkt ) )
1561 AVPacket *tmp = malloc( sizeof(AVPacket) );
1563 mlt_deque_push_back( self->apackets, tmp );
1567 pthread_mutex_unlock( &self->packets_mutex );
1569 // We only deal with video from the selected video_index
1570 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1572 // Determine time code of the packet
1575 int64_t pts = pkt.pts;
1576 if ( self->first_pts > 0 )
1577 pts -= self->first_pts;
1578 else if ( context->start_time != AV_NOPTS_VALUE )
1579 pts -= context->start_time;
1580 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.1 );
1581 if ( pkt.pts == AV_NOPTS_VALUE )
1583 self->invalid_pts_counter++;
1584 if ( self->invalid_pts_counter > 20 )
1586 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1587 mlt_properties_set_int( properties, "new_seek", 0 );
1588 int_position = req_position;
1594 self->invalid_pts_counter = 0;
1596 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1597 pkt.pts, req_position, self->current_position, int_position );
1601 if ( pkt.dts != AV_NOPTS_VALUE )
1603 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pkt.dts + delay ) * source_fps + 0.5 );
1604 if ( context->start_time != AV_NOPTS_VALUE )
1605 int_position -= ( int64_t )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1606 if ( int_position == self->last_position )
1607 int_position = self->last_position + 1;
1609 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1610 pkt.dts, req_position, self->current_position, int_position );
1611 // Make a dumb assumption on streams that contain wild timestamps
1612 if ( abs( req_position - int_position ) > 999 )
1614 int_position = req_position;
1615 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1618 self->last_position = int_position;
1621 if ( must_decode || int_position >= req_position )
1626 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1628 vdpau_decoder_init( self );
1630 self->vdpau->is_decoded = 0;
1633 codec_context->reordered_opaque = pkt.pts;
1634 if ( int_position >= req_position )
1635 codec_context->skip_loop_filter = AVDISCARD_NONE;
1636 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1637 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1639 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1641 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1644 if ( ++decode_errors <= 10 )
1657 // Determine time code of the packet
1658 int64_t pts = self->av_frame->reordered_opaque;
1659 if ( self->first_pts > 0 )
1660 pts -= self->first_pts;
1661 else if ( context->start_time != AV_NOPTS_VALUE )
1662 pts -= context->start_time;
1663 int_position = ( int64_t )( ( av_q2d( stream->time_base) * pts + delay ) * source_fps + 0.1 );
1664 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %"PRId64", key %d\n", int_position, self->av_frame->key_frame );
1667 if ( int_position < req_position )
1672 else if ( int_position >= req_position )
1675 codec_context->skip_loop_filter = AVDISCARD_NONE;
1677 else if ( ignore -- )
1682 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1685 // Now handle the picture if we have one
1688 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1690 // Workaround 1088 encodings missing cropping info.
1691 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1696 if ( self->vdpau->is_decoded )
1698 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1700 uint32_t pitches[3];
1701 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1703 if ( !self->vdpau->buffer )
1704 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1705 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1706 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1707 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1708 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1709 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1710 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1712 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1713 if ( status == VDP_STATUS_OK )
1715 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1716 format, *width, *height, self->colorspace, &alpha );
1720 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1721 image_size = self->vdpau->is_decoded = 0;
1726 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1727 image_size = got_picture = 0;
1732 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1733 format, *width, *height, self->colorspace, &alpha );
1734 self->top_field_first |= self->av_frame->top_field_first;
1735 self->current_position = int_position;
1742 if ( self->seekable || pkt.stream_index != self->audio_index )
1743 av_free_packet( &pkt );
1749 mlt_frame_set_alpha( frame, alpha, (*width) * (*height), mlt_pool_release );
1751 if ( image_size > 0 && self->image_cache )
1752 mlt_cache_put_frame( self->image_cache, frame );
1754 // Try to duplicate last image if there was a decoding failure
1755 // TODO: with multithread decoding a partial frame decoding resulting
1756 // in failure also resets av_frame making test below fail.
1757 if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1760 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1762 // Workaround 1088 encodings missing cropping info.
1763 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1766 if ( self->vdpau && self->vdpau->buffer )
1769 picture.data[0] = self->vdpau->buffer;
1770 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1771 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1772 picture.linesize[0] = codec_context->width;
1773 picture.linesize[1] = codec_context->width / 2;
1774 picture.linesize[2] = codec_context->width / 2;
1775 convert_image( (AVFrame*) &picture, *buffer,
1776 PIX_FMT_YUV420P, format, *width, *height, self->colorspace, &alpha );
1780 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1781 format, *width, *height, self->colorspace, &alpha );
1786 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1787 self->video_expected = position + 1;
1791 pthread_mutex_unlock( &self->video_mutex );
1793 // Set the progressive flag
1794 if ( mlt_properties_get( properties, "force_progressive" ) )
1795 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1796 else if ( self->av_frame )
1797 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1799 // Set the field order property for this frame
1800 if ( mlt_properties_get( properties, "force_tff" ) )
1801 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1803 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1805 // Set immutable properties of the selected track's (or overridden) source attributes.
1806 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1807 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1808 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1809 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1811 return !got_picture;
1814 /** Process properties as AVOptions and apply to AV context obj
1817 static void apply_properties( void *obj, mlt_properties properties, int flags )
1820 int count = mlt_properties_count( properties );
1821 for ( i = 0; i < count; i++ )
1823 const char *opt_name = mlt_properties_get_name( properties, i );
1824 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
1825 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1827 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1829 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1832 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1833 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1834 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1835 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1836 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1837 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1839 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1845 /** Initialize the video codec context.
1848 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1850 // Initialise the codec if necessary
1851 if ( !self->video_codec )
1853 // Get the video stream
1854 AVStream *stream = self->video_format->streams[ index ];
1856 // Get codec context
1857 AVCodecContext *codec_context = stream->codec;
1860 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1862 if ( codec_context->codec_id == CODEC_ID_H264 )
1864 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1866 if ( vdpau_init( self ) )
1868 self->video_codec = codec_context;
1869 if ( !vdpau_decoder_init( self ) )
1874 codec = avcodec_find_decoder( codec_context->codec_id );
1878 // Initialise multi-threading
1879 int thread_count = mlt_properties_get_int( properties, "threads" );
1880 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1881 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1882 if ( thread_count > 1 )
1883 codec_context->thread_count = thread_count;
1885 // If we don't have a codec and we can't initialise it, we can't do much more...
1886 pthread_mutex_lock( &self->open_mutex );
1887 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1888 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1890 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1893 // Now store the codec with its destructor
1894 self->video_codec = codec_context;
1898 // Remember that we can't use this later
1899 self->video_index = -1;
1900 pthread_mutex_unlock( &self->open_mutex );
1903 pthread_mutex_unlock( &self->open_mutex );
1905 // Process properties as AVOptions
1906 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1907 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1908 if ( codec->priv_class && codec_context->priv_data )
1909 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1912 // Reset some image properties
1913 mlt_properties_set_int( properties, "width", self->video_codec->width );
1914 mlt_properties_set_int( properties, "height", self->video_codec->height );
1915 // For DV, we'll just use the saved aspect ratio
1916 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1917 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1919 // Determine the fps first from the codec
1920 double source_fps = (double) self->video_codec->time_base.den /
1921 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1923 if ( mlt_properties_get( properties, "force_fps" ) )
1925 source_fps = mlt_properties_get_double( properties, "force_fps" );
1926 stream->time_base = av_d2q( source_fps, 1024 );
1927 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1928 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1932 // If the muxer reports a frame rate different than the codec
1933 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1934 double muxer_fps = av_q2d( stream->avg_frame_rate );
1935 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1936 muxer_fps = av_q2d( stream->r_frame_rate );
1938 double muxer_fps = av_q2d( stream->r_frame_rate );
1940 // Choose the lesser - the wrong tends to be off by some multiple of 10
1941 source_fps = FFMIN( source_fps, muxer_fps );
1942 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1944 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1945 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1947 else if ( muxer_fps > 0 )
1949 AVRational frame_rate = stream->r_frame_rate;
1950 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1951 // avg_frame_rate gives some approximate value that does not well match the media.
1952 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1953 // results in some very choppy output, but some value slightly different works
1955 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1956 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1957 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1959 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1960 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1964 source_fps = mlt_producer_get_fps( self->parent );
1965 AVRational frame_rate = av_d2q( source_fps, 255 );
1966 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1967 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1971 // Set the YUV colorspace from override or detect
1972 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1973 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1974 if ( ! self->colorspace )
1976 switch ( self->video_codec->colorspace )
1978 case AVCOL_SPC_SMPTE240M:
1979 self->colorspace = 240;
1981 case AVCOL_SPC_BT470BG:
1982 case AVCOL_SPC_SMPTE170M:
1983 self->colorspace = 601;
1985 case AVCOL_SPC_BT709:
1986 self->colorspace = 709;
1989 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1990 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1995 // Let apps get chosen colorspace
1996 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1998 return self->video_codec && self->video_index > -1;
2001 /** Set up video handling.
2004 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
2007 mlt_producer producer = self->parent;
2009 // Get the properties
2010 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2012 // Fetch the video format context
2013 AVFormatContext *context = self->video_format;
2015 // Get the video_index
2016 int index = mlt_properties_get_int( properties, "video_index" );
2018 // Reopen the file if necessary
2019 if ( !context && index > -1 )
2021 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2022 mlt_properties_get( properties, "resource" ), 1 );
2023 context = self->video_format;
2026 // Exception handling for video_index
2027 if ( context && index >= (int) context->nb_streams )
2029 // Get the last video stream
2030 for ( index = context->nb_streams - 1;
2031 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
2033 mlt_properties_set_int( properties, "video_index", index );
2035 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
2037 // Invalidate the video stream
2039 mlt_properties_set_int( properties, "video_index", index );
2042 // Update the video properties if the index changed
2043 if ( index != self->video_index )
2045 // Reset the video properties if the index changed
2046 self->video_index = index;
2047 pthread_mutex_lock( &self->open_mutex );
2048 if ( self->video_codec )
2049 avcodec_close( self->video_codec );
2050 self->video_codec = NULL;
2051 pthread_mutex_unlock( &self->open_mutex );
2054 // Get the frame properties
2055 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2058 if ( context && index > -1 && video_codec_init( self, index, properties ) )
2060 // Set the frame properties
2061 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
2062 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
2063 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
2065 // Set the width and height
2066 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
2067 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
2068 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
2069 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
2070 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
2071 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
2073 // Workaround 1088 encodings missing cropping info.
2074 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
2076 mlt_properties_set_int( properties, "meta.media.height", 1080 );
2079 // Add our image operation
2080 mlt_frame_push_service( frame, self );
2081 mlt_frame_push_get_image( frame, producer_get_image );
2085 // If something failed, use test card image
2086 mlt_properties_set_int( frame_properties, "test_image", 1 );
2090 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
2094 // Seek if necessary
2095 if ( self->seekable && position != self->audio_expected )
2097 if ( position + 1 == self->audio_expected )
2099 // We're paused - silence required
2102 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
2104 // Fast forward - seeking is inefficient for small distances - just ignore following frames
2105 *ignore = position - self->audio_expected;
2107 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
2109 AVFormatContext *context = self->audio_format;
2110 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
2111 if ( context->start_time != AV_NOPTS_VALUE )
2112 timestamp += context->start_time;
2113 if ( timestamp < 0 )
2116 // Set to the real timecode
2117 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
2120 // Clear the usage in the audio buffer
2121 int i = MAX_AUDIO_STREAMS + 1;
2123 self->audio_used[i - 1] = 0;
2129 static int sample_bytes( AVCodecContext *context )
2131 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2132 return av_get_bytes_per_sample( context->sample_fmt );
2133 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2134 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2136 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2140 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2142 // Fetch the audio_format
2143 AVFormatContext *context = self->audio_format;
2145 // Get the current stream index
2146 int index = pkt.stream_index;
2148 // Get codec context
2149 AVCodecContext *codec_context = self->audio_codec[ index ];
2151 // Obtain the resample context if it exists (not always needed)
2152 ReSampleContext *resample = self->audio_resample[ index ];
2154 // Obtain the audio buffers
2155 uint8_t *audio_buffer = self->audio_buffer[ index ];
2156 uint8_t *decode_buffer = self->decode_buffer[ index ];
2158 int audio_used = self->audio_used[ index ];
2159 uint8_t *ptr = pkt.data;
2163 while ( ptr && ret >= 0 && len > 0 )
2165 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2166 int data_size = self->audio_buffer_size[ index ];
2169 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2170 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2171 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2172 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2174 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2178 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2182 pkt.size = len -= ret;
2183 pkt.data = ptr += ret;
2185 // If decoded successfully
2186 if ( data_size > 0 )
2188 // Figure out how many samples will be needed after resampling
2189 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2190 int samples_needed = self->resample_factor * convert_samples;
2192 // Resize audio buffer to prevent overflow
2193 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2195 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2196 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2200 // Copy to audio buffer while resampling
2201 uint8_t *source = decode_buffer;
2202 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2203 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2207 // Straight copy to audio buffer
2208 memcpy( &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ], decode_buffer, data_size );
2209 audio_used += convert_samples;
2213 while ( *ignore && audio_used )
2216 audio_used -= audio_used > samples ? samples : audio_used;
2217 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2218 audio_used * sizeof_sample );
2223 // If we're behind, ignore this packet
2224 // Skip this on non-seekable, audio-only inputs.
2225 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2227 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
2228 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2229 int64_t int_position = ( int64_t )( current_pts * fps + 0.5 );
2230 if ( context->start_time != AV_NOPTS_VALUE )
2231 int_position -= ( int64_t )( fps * context->start_time / AV_TIME_BASE + 0.5 );
2233 if ( int_position > 0 )
2235 if ( int_position < req_position )
2236 // We are behind, so skip some
2237 *ignore = req_position - int_position;
2238 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2239 // We are ahead, so seek backwards some more
2240 seek_audio( self, req_position, timecode - 1.0, ignore );
2244 self->audio_used[ index ] = audio_used;
2249 /** Get the audio from a frame.
2251 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2254 producer_avformat self = mlt_frame_pop_audio( frame );
2256 pthread_mutex_lock( &self->audio_mutex );
2258 // Obtain the frame number of this frame
2259 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
2261 // Calculate the real time code
2262 double real_timecode = producer_time_of_frame( self->parent, position );
2264 // Get the producer fps
2265 double fps = mlt_producer_get_fps( self->parent );
2267 // Number of frames to ignore (for ffwd)
2268 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2270 // Flag for paused (silence)
2271 int paused = seek_audio( self, position, real_timecode, &ignore[0] );
2273 // Initialize ignore for all streams from the seek return value
2274 int i = MAX_AUDIO_STREAMS;
2276 ignore[i] = ignore[0];
2278 // Fetch the audio_format
2279 AVFormatContext *context = self->audio_format;
2281 int sizeof_sample = sizeof( int16_t );
2283 // Determine the tracks to use
2284 int index = self->audio_index;
2285 int index_max = self->audio_index + 1;
2286 if ( self->audio_index == INT_MAX )
2289 index_max = context->nb_streams;
2290 *channels = self->total_channels;
2291 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2292 *frequency = FFMAX( self->max_frequency, *frequency );
2295 // Initialize the resamplers and buffers
2296 for ( ; index < index_max; index++ )
2298 // Get codec context
2299 AVCodecContext *codec_context = self->audio_codec[ index ];
2301 if ( codec_context && !self->audio_buffer[ index ] )
2303 // Check for resample and create if necessary
2304 if ( codec_context->channels <= 2 )
2306 // Determine by how much resampling will increase number of samples
2307 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2308 resample_factor *= (double) *frequency / codec_context->sample_rate;
2309 if ( resample_factor > self->resample_factor )
2310 self->resample_factor = resample_factor;
2312 // Create the resampler
2313 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2314 self->audio_resample[ index ] = av_audio_resample_init(
2315 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2316 codec_context->channels, *frequency, codec_context->sample_rate,
2317 AV_SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2319 self->audio_resample[ index ] = audio_resample_init(
2320 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2321 codec_context->channels, *frequency, codec_context->sample_rate );
2326 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2327 sizeof_sample = sample_bytes( codec_context );
2330 // Check for audio buffer and create if necessary
2331 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2332 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2334 // Check for decoder buffer and create if necessary
2335 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2339 // Get the audio if required
2346 av_init_packet( &pkt );
2348 // If not resampling, give consumer more than requested.
2349 // It requested number samples based on requested frame rate.
2350 // Do not clean this up with a samples *= ...!
2351 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2352 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2354 while ( ret >= 0 && !got_audio )
2356 // Check if the buffer already contains the samples required
2357 if ( self->audio_index != INT_MAX &&
2358 self->audio_used[ self->audio_index ] >= *samples &&
2359 ignore[ self->audio_index ] == 0 )
2364 else if ( self->audio_index == INT_MAX )
2366 // Check if there is enough audio for all streams
2368 for ( index = 0; got_audio && index < context->nb_streams; index++ )
2369 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2376 pthread_mutex_lock( &self->packets_mutex );
2377 if ( mlt_deque_count( self->apackets ) )
2379 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2385 ret = av_read_frame( context, &pkt );
2386 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2388 if ( !av_dup_packet( &pkt ) )
2390 AVPacket *tmp = malloc( sizeof(AVPacket) );
2392 mlt_deque_push_back( self->vpackets, tmp );
2396 pthread_mutex_unlock( &self->packets_mutex );
2398 // We only deal with audio from the selected audio index
2399 index = pkt.stream_index;
2400 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2401 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2403 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2404 self->audio_codec[index]->channels : *channels;
2405 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2408 if ( self->seekable || index != self->video_index )
2409 av_free_packet( &pkt );
2413 // Set some additional return values
2414 *format = mlt_audio_s16;
2415 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2417 index = self->audio_index;
2418 *channels = self->audio_codec[ index ]->channels;
2419 *frequency = self->audio_codec[ index ]->sample_rate;
2420 *format = self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_S32 ? mlt_audio_s32le
2421 : self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_FLT ? mlt_audio_f32le
2423 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2425 else if ( self->audio_index == INT_MAX )
2427 // This only works if all audio tracks have the same sample format.
2428 for ( index = 0; index < index_max; index++ )
2429 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2431 *format = self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_S32 ? mlt_audio_s32le
2432 : self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_FLT ? mlt_audio_f32le
2434 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2439 // Allocate and set the frame's audio buffer
2440 int size = mlt_audio_format_size( *format, *samples, *channels );
2441 *buffer = mlt_pool_alloc( size );
2442 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2444 // Interleave tracks if audio_index=all
2445 if ( self->audio_index == INT_MAX )
2447 uint8_t *dest = *buffer;
2449 for ( i = 0; i < *samples; i++ )
2451 for ( index = 0; index < index_max; index++ )
2452 if ( self->audio_codec[ index ] )
2454 int current_channels = self->audio_codec[ index ]->channels;
2455 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2456 memcpy( dest, src, current_channels * sizeof_sample );
2457 dest += current_channels * sizeof_sample;
2460 for ( index = 0; index < index_max; index++ )
2461 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2463 int current_channels = self->audio_codec[ index ]->channels;
2464 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2465 self->audio_used[index] -= *samples;
2466 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2469 // Copy a single track to the output buffer
2472 index = self->audio_index;
2474 // Now handle the audio if we have enough
2475 if ( self->audio_used[ index ] > 0 )
2477 uint8_t *src = self->audio_buffer[ index ];
2478 // copy samples from audio_buffer
2479 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2480 memcpy( *buffer, src, size * *channels * sizeof_sample );
2481 // supply the remaining requested samples as silence
2482 if ( *samples > self->audio_used[ index ] )
2483 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2484 // reposition the samples within audio_buffer
2485 self->audio_used[ index ] -= size;
2486 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2490 // Otherwise fill with silence
2491 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2497 // Get silence and don't touch the context
2498 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2501 // Regardless of speed (other than paused), we expect to get the next frame
2503 self->audio_expected = position + 1;
2505 pthread_mutex_unlock( &self->audio_mutex );
2510 /** Initialize the audio codec context.
2513 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2515 // Initialise the codec if necessary
2516 if ( !self->audio_codec[ index ] )
2518 // Get codec context
2519 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2522 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2524 // If we don't have a codec and we can't initialise it, we can't do much more...
2525 pthread_mutex_lock( &self->open_mutex );
2526 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2527 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2529 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2532 // Now store the codec with its destructor
2533 if ( self->audio_codec[ index ] )
2534 avcodec_close( self->audio_codec[ index ] );
2535 self->audio_codec[ index ] = codec_context;
2539 // Remember that we can't use self later
2540 self->audio_index = -1;
2542 pthread_mutex_unlock( &self->open_mutex );
2544 // Process properties as AVOptions
2545 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2546 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
2547 if ( codec && codec->priv_class && codec_context->priv_data )
2548 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2551 return self->audio_codec[ index ] && self->audio_index > -1;
2554 /** Set up audio handling.
2557 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2560 mlt_producer producer = self->parent;
2562 // Get the properties
2563 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2565 // Fetch the audio format context
2566 AVFormatContext *context = self->audio_format;
2568 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2570 // Get the audio_index
2571 int index = mlt_properties_get_int( properties, "audio_index" );
2573 // Handle all audio tracks
2574 if ( self->audio_index > -1 &&
2575 mlt_properties_get( properties, "audio_index" ) &&
2576 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2579 // Reopen the file if necessary
2580 if ( !context && self->audio_index > -1 && index > -1 )
2582 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2583 mlt_properties_get( properties, "resource" ), 1 );
2584 context = self->audio_format;
2587 // Exception handling for audio_index
2588 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2590 for ( index = context->nb_streams - 1;
2591 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2593 mlt_properties_set_int( properties, "audio_index", index );
2595 if ( context && index > -1 && index < INT_MAX &&
2596 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2598 index = self->audio_index;
2599 mlt_properties_set_int( properties, "audio_index", index );
2602 // Update the audio properties if the index changed
2603 if ( context && index > -1 && index != self->audio_index )
2605 pthread_mutex_lock( &self->open_mutex );
2606 if ( self->audio_codec[ self->audio_index ] )
2607 avcodec_close( self->audio_codec[ self->audio_index ] );
2608 self->audio_codec[ self->audio_index ] = NULL;
2609 pthread_mutex_unlock( &self->open_mutex );
2611 if ( self->audio_index != -1 )
2612 self->audio_index = index;
2617 if ( context && index == INT_MAX )
2619 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2620 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2621 for ( index = 0; index < context->nb_streams; index++ )
2623 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2624 audio_codec_init( self, index, properties );
2627 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2629 // Set the frame properties
2630 if ( index < INT_MAX )
2632 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2633 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2636 if ( context && index > -1 )
2638 // Add our audio operation
2639 mlt_frame_push_audio( frame, self );
2640 mlt_frame_push_audio( frame, producer_get_audio );
2644 /** Our get frame implementation.
2647 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2649 // Access the private data
2650 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2651 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2652 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2657 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2658 producer->child = self;
2659 self->parent = producer;
2660 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2661 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2664 // Create an empty frame
2665 *frame = mlt_frame_init( service);
2669 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2673 mlt_cache_item_close( cache_item );
2677 // Update timecode on the frame we're creating
2678 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2681 producer_set_up_video( self, *frame );
2684 producer_set_up_audio( self, *frame );
2686 // Set the position of this producer
2687 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2688 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", position );
2690 // Calculate the next timecode
2691 mlt_producer_prepare_next( producer );
2696 static void producer_avformat_close( producer_avformat self )
2698 mlt_log_debug( NULL, "producer_avformat_close\n" );
2700 // Cleanup av contexts
2701 av_free( self->av_frame );
2702 pthread_mutex_lock( &self->open_mutex );
2704 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2706 if ( self->audio_resample[i] )
2707 audio_resample_close( self->audio_resample[i] );
2708 mlt_pool_release( self->audio_buffer[i] );
2709 av_free( self->decode_buffer[i] );
2710 if ( self->audio_codec[i] )
2711 avcodec_close( self->audio_codec[i] );
2712 self->audio_codec[i] = NULL;
2714 if ( self->video_codec )
2715 avcodec_close( self->video_codec );
2716 self->video_codec = NULL;
2718 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2719 if ( self->dummy_context )
2720 avformat_close_input( &self->dummy_context );
2721 if ( self->seekable && self->audio_format )
2722 avformat_close_input( &self->audio_format );
2723 if ( self->video_format )
2724 avformat_close_input( &self->video_format );
2726 if ( self->dummy_context )
2727 av_close_input_file( self->dummy_context );
2728 if ( self->seekable && self->audio_format )
2729 av_close_input_file( self->audio_format );
2730 if ( self->video_format )
2731 av_close_input_file( self->video_format );
2733 pthread_mutex_unlock( &self->open_mutex );
2735 vdpau_producer_close( self );
2737 if ( self->image_cache )
2738 mlt_cache_close( self->image_cache );
2740 // Cleanup the mutexes
2741 pthread_mutex_destroy( &self->audio_mutex );
2742 pthread_mutex_destroy( &self->video_mutex );
2743 pthread_mutex_destroy( &self->packets_mutex );
2744 pthread_mutex_destroy( &self->open_mutex );
2746 // Cleanup the packet queues
2748 if ( self->apackets )
2750 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2752 av_free_packet( pkt );
2755 mlt_deque_close( self->apackets );
2756 self->apackets = NULL;
2758 if ( self->vpackets )
2760 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2762 av_free_packet( pkt );
2765 mlt_deque_close( self->vpackets );
2766 self->vpackets = NULL;
2772 static void producer_close( mlt_producer parent )
2774 // Remove this instance from the cache
2775 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2778 parent->close = NULL;
2779 mlt_producer_close( parent );