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;
95 ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
96 mlt_position audio_expected;
97 mlt_position video_expected;
101 int64_t last_position;
103 int64_t current_position;
104 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 unsigned int invalid_dts_counter;
117 double resample_factor;
118 mlt_cache image_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;
197 pthread_mutex_init( &self->audio_mutex, NULL );
198 pthread_mutex_init( &self->video_mutex, NULL );
199 pthread_mutex_init( &self->packets_mutex, NULL );
200 pthread_mutex_init( &self->open_mutex, NULL );
203 self->apackets = mlt_deque_init();
204 self->vpackets = mlt_deque_init();
206 if ( strcmp( service, "avformat-novalidate" ) )
209 if ( producer_open( self, profile, file, 1 ) != 0 )
212 mlt_producer_close( producer );
214 producer_avformat_close( self );
216 else if ( self->seekable )
218 // Close the file to release resources for large playlists - reopen later as needed
219 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
220 if ( self->audio_format )
221 avformat_close_input( &self->audio_format );
222 if ( self->video_format )
223 avformat_close_input( &self->video_format );
225 if ( self->audio_format )
226 av_close_input_file( self->audio_format );
227 if ( self->video_format )
228 av_close_input_file( self->video_format );
230 self->audio_format = NULL;
231 self->video_format = NULL;
236 // Default the user-selectable indices from the auto-detected indices
237 mlt_properties_set_int( properties, "audio_index", self->audio_index );
238 mlt_properties_set_int( properties, "video_index", self->video_index );
240 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
242 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
249 int list_components( char* file )
253 // Report information about available demuxers and codecs as YAML Tiny
254 if ( file && strstr( file, "f-list" ) )
256 fprintf( stderr, "---\nformats:\n" );
257 AVInputFormat *format = NULL;
258 while ( ( format = av_iformat_next( format ) ) )
259 fprintf( stderr, " - %s\n", format->name );
260 fprintf( stderr, "...\n" );
263 if ( file && strstr( file, "acodec-list" ) )
265 fprintf( stderr, "---\naudio_codecs:\n" );
266 AVCodec *codec = NULL;
267 while ( ( codec = av_codec_next( codec ) ) )
268 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
269 fprintf( stderr, " - %s\n", codec->name );
270 fprintf( stderr, "...\n" );
273 if ( file && strstr( file, "vcodec-list" ) )
275 fprintf( stderr, "---\nvideo_codecs:\n" );
276 AVCodec *codec = NULL;
277 while ( ( codec = av_codec_next( codec ) ) )
278 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
279 fprintf( stderr, " - %s\n", codec->name );
280 fprintf( stderr, "...\n" );
287 /** Find the default streams.
290 static mlt_properties find_default_streams( producer_avformat self )
294 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
295 AVDictionaryEntry *tag = NULL;
297 AVMetadataTag *tag = NULL;
299 AVFormatContext *context = self->video_format;
300 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
302 // Default to the first audio and video streams found
303 self->audio_index = -1;
304 self->video_index = -1;
306 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
308 // Allow for multiple audio and video streams in the file and select first of each (if available)
309 for( i = 0; i < context->nb_streams; i++ )
311 // Get the codec context
312 AVStream *stream = context->streams[ i ];
313 if ( ! stream ) continue;
314 AVCodecContext *codec_context = stream->codec;
315 if ( ! codec_context ) continue;
316 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
317 if ( ! codec ) continue;
319 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
321 // Determine the type and obtain the first index of each type
322 switch( codec_context->codec_type )
324 case CODEC_TYPE_VIDEO:
325 // Use first video stream
326 if ( self->video_index < 0 )
327 self->video_index = i;
328 mlt_properties_set( meta_media, key, "video" );
329 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
330 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
331 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
332 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
333 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
334 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
336 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
339 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
340 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
341 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
343 snprintf( key, sizeof(key), "meta.media.%d.codec.width", i );
344 mlt_properties_set_int( meta_media, key, codec_context->width );
345 snprintf( key, sizeof(key), "meta.media.%d.codec.height", i );
346 mlt_properties_set_int( meta_media, key, codec_context->height );
347 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
348 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
349 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
350 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
351 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(3<<8)+0)
352 mlt_properties_set( meta_media, key, av_get_pix_fmt_name( codec_context->pix_fmt ) );
354 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
356 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
357 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
358 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
359 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
360 switch ( codec_context->colorspace )
362 case AVCOL_SPC_SMPTE240M:
363 mlt_properties_set_int( meta_media, key, 240 );
365 case AVCOL_SPC_BT470BG:
366 case AVCOL_SPC_SMPTE170M:
367 mlt_properties_set_int( meta_media, key, 601 );
369 case AVCOL_SPC_BT709:
370 mlt_properties_set_int( meta_media, key, 709 );
373 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
374 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
379 case CODEC_TYPE_AUDIO:
380 if ( !codec_context->channels )
382 // Use first audio stream
383 if ( self->audio_index < 0 )
384 self->audio_index = i;
385 mlt_properties_set( meta_media, key, "audio" );
386 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
387 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
388 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
389 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
390 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
391 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
393 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
394 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
395 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
396 mlt_properties_set_int( meta_media, key, codec_context->channels );
401 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
402 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
403 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
404 mlt_properties_set( meta_media, key, codec->name );
405 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
406 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
407 mlt_properties_set( meta_media, key, codec->long_name );
409 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
410 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
411 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
412 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
413 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
414 // mlt_properties_set_int( meta_media, key, codec_context->profile );
415 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
416 // mlt_properties_set_int( meta_media, key, codec_context->level );
419 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
420 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
421 while ( ( tag = av_dict_get( stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
423 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
426 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
428 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
429 mlt_properties_set( meta_media, key, tag->value );
434 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
435 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
436 while ( ( tag = av_dict_get( context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
438 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
441 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
443 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
444 mlt_properties_set( meta_media, key, tag->value );
448 if ( context->title && strcmp( context->title, "" ) )
449 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
450 if ( context->author && strcmp( context->author, "" ) )
451 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
452 if ( context->copyright && strcmp( context->copyright, "" ) )
453 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
454 if ( context->comment )
455 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
456 if ( context->album )
457 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
459 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
460 if ( context->track )
461 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
467 static inline int dv_is_pal( AVPacket *pkt )
469 return pkt->data[3] & 0x80;
472 static int dv_is_wide( AVPacket *pkt )
474 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
476 for ( ; i < pkt->size; i += 5 /* packet size */ )
478 if ( pkt->data[ i ] == 0x61 )
480 uint8_t x = pkt->data[ i + 2 ] & 0x7;
481 return ( x == 2 ) || ( x == 7 );
487 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
489 double aspect_ratio = 1.0;
491 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
495 if ( dv_is_pal( pkt ) )
497 if ( dv_is_wide( pkt ) )
499 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
500 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
504 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
505 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
510 if ( dv_is_wide( pkt ) )
512 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
513 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
517 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
518 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
525 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
526 stream->sample_aspect_ratio;
528 codec_context->sample_aspect_ratio;
530 // Override FFmpeg's notion of DV aspect ratios, which are
531 // based upon a width of 704. Since we do not have a normaliser
532 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
533 // we just coerce the values to facilitate a passive behaviour through
534 // the rescale normaliser when using equivalent producers and consumers.
535 // = display_aspect / (width * height)
536 if ( ar.num == 10 && ar.den == 11 )
539 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
540 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
542 else if ( ar.num == 59 && ar.den == 54 )
545 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
546 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
548 else if ( ar.num == 40 && ar.den == 33 )
551 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
552 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
554 else if ( ar.num == 118 && ar.den == 81 )
557 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
558 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
564 AVRational codec_sar = codec_context->sample_aspect_ratio;
565 AVRational stream_sar =
566 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
567 stream->sample_aspect_ratio;
571 if ( codec_sar.num > 0 )
573 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
574 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
576 else if ( stream_sar.num > 0 )
578 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
579 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
583 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
584 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
587 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
588 aspect_ratio = av_q2d( ar );
589 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
594 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
595 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVDictionary **params )
597 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
600 if ( !URL ) return NULL;
603 char *protocol = strdup( URL );
604 char *url = strchr( protocol, ':' );
606 // Only if there is not a protocol specification that avformat can handle
607 #if LIBAVFORMAT_VERSION_MAJOR >= 53
608 if ( url && avio_check( URL, 0 ) < 0 )
610 if ( url && !url_exist( URL ) )
613 // Truncate protocol string
615 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
618 *format = av_find_input_format( protocol );
620 // Eat the format designator
625 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
626 // support for legacy width and height parameters
630 // These are required by video4linux2 (defaults)
631 params->width = profile->width;
632 params->height = profile->height;
633 if ( !strstr( URL, "&frame_rate" ) )
634 params->time_base = (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
635 params->channels = 2;
636 params->sample_rate = 48000;
640 url = strchr( url, '?' );
644 char *name = strdup( ++url );
645 char *value = strchr( name, '=' );
647 // Also accept : as delimiter for backwards compatibility.
648 value = strchr( name, ':' );
653 char *t = strchr( value, '&' );
656 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
657 // translate old parameters to new av_dict names
658 if ( !strcmp( name, "frame_rate" ) )
659 av_dict_set( params, "framerate", value, 0 );
660 else if ( !strcmp( name, "pix_fmt" ) )
661 av_dict_set( params, "pixel_format", value, 0 );
662 else if ( !strcmp( name, "width" ) )
663 width = strdup( value );
664 else if ( !strcmp( name, "height" ) )
665 height = strdup( value );
667 // generic demux/device option support
668 av_dict_set( params, name, value, 0 );
670 if ( !strcmp( name, "frame_rate" ) )
671 params->time_base.den = atoi( value );
672 else if ( !strcmp( name, "frame_rate_base" ) )
673 params->time_base.num = atoi( value );
674 else if ( !strcmp( name, "sample_rate" ) )
675 params->sample_rate = atoi( value );
676 else if ( !strcmp( name, "channel" ) )
677 params->channel = atoi( value );
678 else if ( !strcmp( name, "channels" ) )
679 params->channels = atoi( value );
680 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
681 else if ( !strcmp( name, "pix_fmt" ) )
682 params->pix_fmt = av_get_pix_fmt( value );
684 else if ( !strcmp( name, "width" ) )
685 params->width = atoi( value );
686 else if ( !strcmp( name, "height" ) )
687 params->height = atoi( value );
688 else if ( !strcmp( name, "standard" ) )
689 params->standard = strdup( value );
693 url = strchr( url, '&' );
695 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
696 // continued support for legacy width and height parameters
697 if ( width && height )
699 char *s = malloc( strlen( width ) + strlen( height ) + 2 );
703 av_dict_set( params, "video_size", s, 0 );
706 if ( width ) free( width );
707 if ( height ) free ( height );
710 result = strdup( result );
714 result = strdup( URL );
720 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
724 // Get the properties
725 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
727 AVFormatContext *format = self->video_format;
729 // We will treat everything with the producer fps.
730 // TODO: make this more flexible.
731 double fps = mlt_profile_fps( profile );
734 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
736 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
737 // when producer_open is called after initial call when restoring or reseting the producer.
738 if ( format->duration != AV_NOPTS_VALUE )
740 // This isn't going to be accurate for all formats
741 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
742 mlt_properties_set_position( properties, "out", frames - 1 );
743 mlt_properties_set_position( properties, "length", frames );
744 mlt_properties_set_int( properties, "_length_computed", 1 );
748 // Set live sources to run forever
749 mlt_properties_set_position( properties, "length", INT_MAX );
750 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
751 mlt_properties_set( properties, "eof", "loop" );
752 mlt_properties_set_int( properties, "_length_computed", 1 );
756 // Check if we're seekable
757 // avdevices are typically AVFMT_NOFILE and not seekable
758 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
761 // protocols can indicate if they support seeking
762 #if LIBAVFORMAT_VERSION_MAJOR >= 53
763 self->seekable = format->pb->seekable;
765 URLContext *uc = url_fileno( format->pb );
767 self->seekable = !uc->is_streamed;
770 if ( self->seekable )
772 // Do a more rigourous test of seekable on a disposable context
773 self->seekable = av_seek_frame( format, -1, format->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
774 mlt_properties_set_int( properties, "seekable", self->seekable );
775 self->dummy_context = format;
776 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
777 self->video_format = NULL;
778 avformat_open_input( &self->video_format, filename, NULL, NULL );
779 avformat_find_stream_info( self->video_format, NULL );
781 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
782 av_find_stream_info( self->video_format );
784 format = self->video_format;
787 // Fetch the width, height and aspect ratio
788 if ( self->video_index != -1 )
790 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
791 mlt_properties_set_int( properties, "width", codec_context->width );
792 mlt_properties_set_int( properties, "height", codec_context->height );
794 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
796 // Fetch the first frame of DV so we can read it directly
801 ret = av_read_frame( format, &pkt );
802 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
804 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
805 av_free_packet(&pkt);
809 av_free_packet(&pkt);
814 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
818 // Verify that we can convert this to YUV 4:2:2
819 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
820 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
821 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
823 sws_freeContext( context );
834 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
836 // Return an error code (0 == no error)
838 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
843 pthread_mutex_lock( &self->audio_mutex );
844 pthread_mutex_lock( &self->video_mutex );
846 mlt_events_block( properties, self->parent );
849 AVInputFormat *format = NULL;
850 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
851 AVDictionary *params = NULL;
853 AVFormatParameters params;
854 memset( ¶ms, 0, sizeof(params) );
856 char *filename = parse_url( profile, URL, &format, ¶ms );
858 // Now attempt to open the file or device with filename
859 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
860 error = avformat_open_input( &self->video_format, filename, format, ¶ms ) < 0;
862 // If the URL is a network stream URL, then we probably need to open with full URL
863 error = avformat_open_input( &self->video_format, URL, format, ¶ms ) < 0;
865 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
867 // If the URL is a network stream URL, then we probably need to open with full URL
868 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
871 // Set MLT properties onto video AVFormatContext
872 if ( !error && self->video_format )
874 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
875 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
876 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
877 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
881 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
882 av_dict_free( ¶ms );
884 // Cleanup AVFormatParameters
885 if ( params.standard )
886 free( (void*) params.standard );
889 // If successful, then try to get additional info
890 if ( !error && self->video_format )
892 // Get the stream info
893 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
894 error = avformat_find_stream_info( self->video_format, NULL ) < 0;
896 error = av_find_stream_info( self->video_format ) < 0;
899 // Continue if no error
900 if ( !error && self->video_format )
902 // Find default audio and video streams
903 find_default_streams( self );
904 error = get_basic_info( self, profile, filename );
906 // Initialize position info
907 self->first_pts = AV_NOPTS_VALUE;
908 self->last_position = POSITION_INITIAL;
910 if ( !self->audio_format )
912 // We're going to cheat here - for seekable A/V files, we will have separate contexts
913 // to support independent seeking of audio from video.
914 // TODO: Is this really necessary?
915 if ( self->audio_index != -1 && self->video_index != -1 )
917 if ( self->seekable )
919 // And open again for our audio context
920 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
921 avformat_open_input( &self->audio_format, filename, NULL, NULL );
922 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
923 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
924 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
925 avformat_find_stream_info( self->audio_format, NULL );
927 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
928 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
929 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
930 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
931 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
933 av_find_stream_info( self->audio_format );
938 self->audio_format = self->video_format;
941 else if ( self->audio_index != -1 )
943 // We only have an audio context
944 self->audio_format = self->video_format;
945 self->video_format = NULL;
947 else if ( self->video_index == -1 )
949 // Something has gone wrong
952 if ( self->audio_format && !self->audio_streams )
953 get_audio_streams_info( self );
960 if ( self->dummy_context )
962 pthread_mutex_lock( &self->open_mutex );
963 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
964 avformat_close_input( &self->dummy_context );
966 av_close_input_file( self->dummy_context );
968 self->dummy_context = NULL;
969 pthread_mutex_unlock( &self->open_mutex );
972 // Unlock the service
975 pthread_mutex_unlock( &self->audio_mutex );
976 pthread_mutex_unlock( &self->video_mutex );
978 mlt_events_unblock( properties, self->parent );
983 static void reopen_video( producer_avformat self, mlt_producer producer )
985 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
986 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
987 pthread_mutex_lock( &self->audio_mutex );
988 pthread_mutex_lock( &self->open_mutex );
990 if ( self->video_codec )
991 avcodec_close( self->video_codec );
992 self->video_codec = NULL;
993 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
994 if ( self->dummy_context )
995 avformat_close_input( &self->dummy_context );
996 if ( self->video_format )
997 avformat_close_input( &self->video_format );
999 if ( self->dummy_context )
1000 av_close_input_file( self->dummy_context );
1001 if ( self->video_format )
1002 av_close_input_file( self->video_format );
1004 self->dummy_context = NULL;
1005 self->video_format = NULL;
1006 pthread_mutex_unlock( &self->open_mutex );
1008 int audio_index = self->audio_index;
1009 int video_index = self->video_index;
1011 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1012 mlt_properties_get( properties, "resource" ), 0 );
1014 self->audio_index = audio_index;
1015 if ( self->video_format && video_index > -1 )
1017 self->video_index = video_index;
1018 video_codec_init( self, video_index, properties );
1021 pthread_mutex_unlock( &self->audio_mutex );
1022 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1025 static int64_t best_pts( producer_avformat self, int64_t pts, int64_t dts )
1027 self->invalid_pts_counter += pts == AV_NOPTS_VALUE;
1028 self->invalid_dts_counter += dts == AV_NOPTS_VALUE;
1029 if ( ( self->invalid_pts_counter <= self->invalid_dts_counter
1030 || dts == AV_NOPTS_VALUE ) && pts != AV_NOPTS_VALUE )
1036 static int seek_video( producer_avformat self, mlt_position position,
1037 int64_t req_position, int preseek )
1039 mlt_producer producer = self->parent;
1042 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
1044 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1046 // Fetch the video format context
1047 AVFormatContext *context = self->video_format;
1049 // Get the video stream
1050 AVStream *stream = context->streams[ self->video_index ];
1052 // Get codec context
1053 AVCodecContext *codec_context = stream->codec;
1055 // We may want to use the source fps if available
1056 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1057 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1060 if ( self->last_position == POSITION_INITIAL )
1066 while ( ret >= 0 && toscan-- > 0 )
1068 ret = av_read_frame( context, &pkt );
1069 if ( ret >= 0 && pkt.stream_index == self->video_index && ( pkt.flags & PKT_FLAG_KEY ) )
1071 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1072 "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n",
1073 pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
1074 self->first_pts = best_pts( self, pkt.pts, pkt.dts );
1075 if ( self->first_pts != AV_NOPTS_VALUE )
1078 av_free_packet( &pkt );
1080 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1083 if ( self->av_frame && position + 1 == self->video_expected )
1085 // We're paused - use last image
1088 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
1090 // Calculate the timestamp for the requested frame
1091 int64_t timestamp = req_position / ( av_q2d( stream->time_base ) * source_fps );
1092 if ( req_position <= 0 )
1094 else if ( self->first_pts != AV_NOPTS_VALUE )
1095 timestamp += self->first_pts;
1096 else if ( context->start_time != AV_NOPTS_VALUE )
1097 timestamp += context->start_time;
1098 if ( preseek && av_q2d( stream->time_base ) != 0 )
1099 timestamp -= 2 / av_q2d( stream->time_base );
1100 if ( timestamp < 0 )
1102 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
1103 timestamp, position, self->video_expected, self->last_position );
1105 // Seek to the timestamp
1106 // NOTE: reopen_video is disabled at this time because it is causing trouble with A/V sync.
1107 if ( 1 || req_position > 0 || self->last_position <= 0 )
1109 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1110 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1112 // flush any pictures still in decode buffer
1113 avcodec_flush_buffers( codec_context );
1117 // Re-open video stream when rewinding to beginning from somewhere else.
1118 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1119 // not reliably seeking to the first frame across formats.
1120 reopen_video( self, producer );
1123 // Remove the cached info relating to the previous position
1124 self->current_position = POSITION_INVALID;
1125 self->last_position = POSITION_INVALID;
1126 av_freep( &self->av_frame );
1132 /** Convert a frame position to a time code.
1135 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1137 return ( double )position / mlt_producer_get_fps( producer );
1140 // Collect information about all audio streams
1142 static void get_audio_streams_info( producer_avformat self )
1144 // Fetch the audio format context
1145 AVFormatContext *context = self->audio_format;
1149 i < context->nb_streams;
1152 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1154 AVCodecContext *codec_context = context->streams[i]->codec;
1155 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1157 // If we don't have a codec and we can't initialise it, we can't do much more...
1158 pthread_mutex_lock( &self->open_mutex );
1159 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1160 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1162 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1165 self->audio_streams++;
1166 self->audio_max_stream = i;
1167 self->total_channels += codec_context->channels;
1168 if ( codec_context->channels > self->max_channel )
1169 self->max_channel = codec_context->channels;
1170 if ( codec_context->sample_rate > self->max_frequency )
1171 self->max_frequency = codec_context->sample_rate;
1172 avcodec_close( codec_context );
1174 pthread_mutex_unlock( &self->open_mutex );
1177 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1178 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1180 // Other audio-specific initializations
1181 self->resample_factor = 1.0;
1184 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1186 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1188 const int *new_coefficients;
1190 int brightness, contrast, saturation;
1192 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1193 &brightness, &contrast, &saturation ) != -1 )
1195 // Don't change these from defaults unless explicitly told to.
1196 if ( use_full_range >= 0 )
1197 full_range = use_full_range;
1198 switch ( colorspace )
1204 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1207 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1210 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1213 new_coefficients = coefficients;
1216 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1217 brightness, contrast, saturation );
1222 static mlt_image_format pick_format( enum PixelFormat pix_fmt )
1230 return mlt_image_rgb24a;
1231 case PIX_FMT_YUV420P:
1232 case PIX_FMT_YUVJ420P:
1233 case PIX_FMT_YUVA420P:
1234 return mlt_image_yuv420p;
1238 case PIX_FMT_MONOWHITE:
1239 case PIX_FMT_MONOBLACK:
1242 return mlt_image_rgb24;
1244 return mlt_image_yuv422;
1248 static void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
1249 mlt_image_format *format, int width, int height, int colorspace, uint8_t **alpha )
1252 int full_range = -1;
1253 int flags = SWS_BICUBIC | SWS_ACCURATE_RND;
1256 flags |= SWS_CPU_CAPS_MMX;
1259 flags |= SWS_CPU_CAPS_MMX2;
1262 // extract alpha from planar formats
1263 if ( ( pix_fmt == PIX_FMT_YUVA420P
1264 #if defined(FFUDIV) && LIBAVUTIL_VERSION_INT >= ((51<<16)+(35<<8)+101)
1265 || pix_fmt == PIX_FMT_YUVA444P
1268 *format != mlt_image_rgb24a && *format != mlt_image_opengl &&
1269 frame->data[3] && frame->linesize[3] )
1274 dst = *alpha = mlt_pool_alloc( width * height );
1275 src = frame->data[3];
1277 for ( i = 0; i < height; dst += width, src += frame->linesize[3], i++ )
1278 memcpy( dst, src, FFMIN( width, frame->linesize[3] ) );
1281 if ( *format == mlt_image_yuv420p )
1283 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1284 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1286 output.data[0] = buffer;
1287 output.data[1] = buffer + width * height;
1288 output.data[2] = buffer + ( 5 * width * height ) / 4;
1289 output.linesize[0] = width;
1290 output.linesize[1] = width >> 1;
1291 output.linesize[2] = width >> 1;
1292 set_luma_transfer( context, colorspace, full_range );
1293 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1294 output.data, output.linesize);
1295 sws_freeContext( context );
1297 else if ( *format == mlt_image_rgb24 )
1299 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1300 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1302 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1303 set_luma_transfer( context, colorspace, full_range );
1304 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1305 output.data, output.linesize);
1306 sws_freeContext( context );
1308 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1310 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1311 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1313 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1314 set_luma_transfer( context, colorspace, full_range );
1315 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1316 output.data, output.linesize);
1317 sws_freeContext( context );
1321 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1322 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1324 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1325 set_luma_transfer( context, colorspace, full_range );
1326 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1327 output.data, output.linesize);
1328 sws_freeContext( context );
1331 if ( *format == mlt_image_yuv420p )
1334 pict.data[0] = buffer;
1335 pict.data[1] = buffer + width * height;
1336 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1337 pict.linesize[0] = width;
1338 pict.linesize[1] = width >> 1;
1339 pict.linesize[2] = width >> 1;
1340 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1342 else if ( *format == mlt_image_rgb24 )
1345 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1346 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1348 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1351 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1352 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1357 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1358 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1363 /** Allocate the image buffer and set it on the frame.
1366 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1370 if ( codec_context->width == 0 || codec_context->height == 0 )
1372 *width = codec_context->width;
1373 *height = codec_context->height;
1374 size = mlt_image_format_size( *format, *width, *height, NULL );
1375 *buffer = mlt_pool_alloc( size );
1377 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1384 /** Get an image from a frame.
1387 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1390 producer_avformat self = mlt_frame_pop_service( frame );
1391 mlt_producer producer = self->parent;
1393 // Get the properties from the frame
1394 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1396 // Obtain the frame number of this frame
1397 mlt_position position = mlt_frame_original_position( frame );
1399 // Get the producer properties
1400 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1402 pthread_mutex_lock( &self->video_mutex );
1404 // Fetch the video format context
1405 AVFormatContext *context = self->video_format;
1407 // Get the video stream
1408 AVStream *stream = context->streams[ self->video_index ];
1410 // Get codec context
1411 AVCodecContext *codec_context = stream->codec;
1413 uint8_t *alpha = NULL;
1414 int got_picture = 0;
1417 // Get the image cache
1418 if ( ! self->image_cache )
1420 // if cache size supplied by environment variable
1421 int cache_supplied = getenv( "MLT_AVFORMAT_CACHE" ) != NULL;
1422 int cache_size = cache_supplied? atoi( getenv( "MLT_AVFORMAT_CACHE" ) ) : 0;
1424 // cache size supplied via property
1425 if ( mlt_properties_get( properties, "cache" ) )
1428 cache_size = mlt_properties_get_int( properties, "cache" );
1430 if ( mlt_properties_get_int( properties, "noimagecache" ) )
1432 // create cache if not disabled
1433 if ( !cache_supplied || cache_size > 0 )
1434 self->image_cache = mlt_cache_init();
1435 // set cache size if supplied
1436 if ( self->image_cache && cache_supplied )
1437 mlt_cache_set_size( self->image_cache, cache_size );
1439 if ( self->image_cache )
1441 mlt_frame original = mlt_cache_get_frame( self->image_cache, position );
1444 mlt_properties orig_props = MLT_FRAME_PROPERTIES( original );
1447 *buffer = mlt_properties_get_data( orig_props, "alpha", &size );
1449 mlt_frame_set_alpha( frame, *buffer, size, NULL );
1450 *buffer = mlt_properties_get_data( orig_props, "image", &size );
1451 mlt_frame_set_image( frame, *buffer, size, NULL );
1452 mlt_properties_set_data( frame_properties, "avformat.image_cache", original, 0, (mlt_destructor) mlt_frame_close, NULL );
1453 *format = mlt_properties_get_int( orig_props, "format" );
1455 // Set the resolution
1456 *width = codec_context->width;
1457 *height = codec_context->height;
1459 // Workaround 1088 encodings missing cropping info.
1460 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1464 goto exit_get_image;
1469 // We may want to use the source fps if available
1470 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1471 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1473 // This is the physical frame position in the source
1474 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1476 // Determines if we have to decode all frames in a sequence
1477 // Temporary hack to improve intra frame only
1478 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1479 strcmp( codec_context->codec->name, "dnxhd" ) &&
1480 strcmp( codec_context->codec->name, "dvvideo" ) &&
1481 strcmp( codec_context->codec->name, "huffyuv" ) &&
1482 strcmp( codec_context->codec->name, "mjpeg" ) &&
1483 strcmp( codec_context->codec->name, "rawvideo" ) );
1485 double delay = mlt_properties_get_double( properties, "video_delay" );
1487 // Seek if necessary
1488 const char *interp = mlt_properties_get( frame_properties, "rescale.interp" );
1489 int preseek = must_decode
1490 #if defined(FFUDIV) && LIBAVFORMAT_VERSION_INT >= ((53<<16)+(24<<8)+2)
1491 && ( interp && strcmp( interp, "nearest" ) )
1493 && codec_context->has_b_frames;
1494 int paused = seek_video( self, position, req_position, preseek );
1496 // Seek might have reopened the file
1497 context = self->video_format;
1498 stream = context->streams[ self->video_index ];
1499 codec_context = stream->codec;
1500 if ( *format == mlt_image_none ||
1501 codec_context->pix_fmt == PIX_FMT_ARGB ||
1502 codec_context->pix_fmt == PIX_FMT_RGBA ||
1503 codec_context->pix_fmt == PIX_FMT_ABGR ||
1504 codec_context->pix_fmt == PIX_FMT_BGRA )
1505 *format = pick_format( codec_context->pix_fmt );
1507 // Duplicate the last image if necessary
1508 if ( self->av_frame && self->av_frame->linesize[0]
1509 && ( paused || self->current_position >= req_position ) )
1512 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1514 // Workaround 1088 encodings missing cropping info.
1515 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1518 if ( self->vdpau && self->vdpau->buffer )
1521 picture.data[0] = self->vdpau->buffer;
1522 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1523 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1524 picture.linesize[0] = codec_context->width;
1525 picture.linesize[1] = codec_context->width / 2;
1526 picture.linesize[2] = codec_context->width / 2;
1527 convert_image( (AVFrame*) &picture, *buffer,
1528 PIX_FMT_YUV420P, format, *width, *height, self->colorspace, &alpha );
1532 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1533 format, *width, *height, self->colorspace, &alpha );
1540 int64_t int_position = 0;
1541 int decode_errors = 0;
1543 // Construct an AVFrame for YUV422 conversion
1544 if ( !self->av_frame )
1545 self->av_frame = avcodec_alloc_frame( );
1547 while( ret >= 0 && !got_picture )
1550 if ( self->pkt.stream_index == self->video_index )
1551 av_free_packet( &self->pkt );
1552 av_init_packet( &self->pkt );
1553 pthread_mutex_lock( &self->packets_mutex );
1554 if ( mlt_deque_count( self->vpackets ) )
1556 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1562 ret = av_read_frame( context, &self->pkt );
1563 if ( ret >= 0 && !self->seekable && self->pkt.stream_index == self->audio_index )
1565 if ( !av_dup_packet( &self->pkt ) )
1567 AVPacket *tmp = malloc( sizeof(AVPacket) );
1569 mlt_deque_push_back( self->apackets, tmp );
1573 pthread_mutex_unlock( &self->packets_mutex );
1575 // We only deal with video from the selected video_index
1576 if ( ret >= 0 && self->pkt.stream_index == self->video_index && self->pkt.size > 0 )
1578 int64_t pts = best_pts( self, self->pkt.pts, self->pkt.dts );
1579 if ( pts != AV_NOPTS_VALUE )
1581 if ( !self->seekable && self->first_pts == AV_NOPTS_VALUE )
1582 self->first_pts = pts;
1583 if ( self->first_pts != AV_NOPTS_VALUE )
1584 pts -= self->first_pts;
1585 else if ( context->start_time != AV_NOPTS_VALUE )
1586 pts -= context->start_time;
1587 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.5 );
1588 if ( int_position == self->last_position )
1589 int_position = self->last_position + 1;
1591 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1592 "V pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1593 self->pkt.pts, self->pkt.dts, req_position, self->current_position, int_position );
1595 // Make a dumb assumption on streams that contain wild timestamps
1596 if ( abs( req_position - int_position ) > 999 )
1598 int_position = req_position;
1599 mlt_log_warning( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!\n" );
1601 self->last_position = int_position;
1604 if ( must_decode || int_position >= req_position )
1609 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1611 vdpau_decoder_init( self );
1613 self->vdpau->is_decoded = 0;
1616 codec_context->reordered_opaque = int_position;
1617 if ( int_position >= req_position )
1618 codec_context->skip_loop_filter = AVDISCARD_NONE;
1619 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1620 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &self->pkt );
1622 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, self->pkt.data, self->pkt.size );
1624 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1627 if ( ++decode_errors <= 10 )
1638 // Get position of reordered frame
1639 int_position = self->av_frame->reordered_opaque;
1640 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(106<<8)+0))
1641 pts = best_pts( self, self->av_frame->pkt_pts, self->av_frame->pkt_dts );
1642 if ( pts != AV_NOPTS_VALUE )
1644 if ( self->first_pts != AV_NOPTS_VALUE )
1645 pts -= self->first_pts;
1646 else if ( context->start_time != AV_NOPTS_VALUE )
1647 pts -= context->start_time;
1648 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.5 );
1652 if ( int_position < req_position )
1654 else if ( int_position >= req_position )
1655 codec_context->skip_loop_filter = AVDISCARD_NONE;
1657 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, self->pkt.flags & PKT_FLAG_KEY );
1660 // Now handle the picture if we have one
1663 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1665 // Workaround 1088 encodings missing cropping info.
1666 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1671 if ( self->vdpau->is_decoded )
1673 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1675 uint32_t pitches[3];
1676 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1678 if ( !self->vdpau->buffer )
1679 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1680 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1681 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1682 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1683 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1684 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1685 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1687 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1688 if ( status == VDP_STATUS_OK )
1690 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1691 format, *width, *height, self->colorspace, &alpha );
1695 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1696 image_size = self->vdpau->is_decoded = 0;
1701 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1702 image_size = got_picture = 0;
1707 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1708 format, *width, *height, self->colorspace, &alpha );
1709 self->top_field_first |= self->av_frame->top_field_first;
1710 self->current_position = int_position;
1718 // Free packet data if not video and not live audio packet
1719 if ( self->pkt.stream_index != self->video_index &&
1720 !( !self->seekable && self->pkt.stream_index == self->audio_index ) )
1721 av_free_packet( &self->pkt );
1727 mlt_frame_set_alpha( frame, alpha, (*width) * (*height), mlt_pool_release );
1729 if ( image_size > 0 && self->image_cache )
1731 mlt_properties_set_int( frame_properties, "format", *format );
1732 mlt_cache_put_frame( self->image_cache, frame );
1735 // Try to duplicate last image if there was a decoding failure
1736 // TODO: with multithread decoding a partial frame decoding resulting
1737 // in failure also resets av_frame making test below fail.
1738 if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1741 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1743 // Workaround 1088 encodings missing cropping info.
1744 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1747 if ( self->vdpau && self->vdpau->buffer )
1750 picture.data[0] = self->vdpau->buffer;
1751 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1752 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1753 picture.linesize[0] = codec_context->width;
1754 picture.linesize[1] = codec_context->width / 2;
1755 picture.linesize[2] = codec_context->width / 2;
1756 convert_image( (AVFrame*) &picture, *buffer,
1757 PIX_FMT_YUV420P, format, *width, *height, self->colorspace, &alpha );
1761 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1762 format, *width, *height, self->colorspace, &alpha );
1767 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1768 self->video_expected = position + 1;
1772 pthread_mutex_unlock( &self->video_mutex );
1774 // Set the progressive flag
1775 if ( mlt_properties_get( properties, "force_progressive" ) )
1776 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1777 else if ( self->av_frame )
1778 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1780 // Set the field order property for this frame
1781 if ( mlt_properties_get( properties, "force_tff" ) )
1782 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1784 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1786 // Set immutable properties of the selected track's (or overridden) source attributes.
1787 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1788 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1789 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1790 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1792 return !got_picture;
1795 /** Process properties as AVOptions and apply to AV context obj
1798 static void apply_properties( void *obj, mlt_properties properties, int flags )
1801 int count = mlt_properties_count( properties );
1802 for ( i = 0; i < count; i++ )
1804 const char *opt_name = mlt_properties_get_name( properties, i );
1805 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
1806 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1808 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1810 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1813 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1814 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1815 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1816 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1817 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1818 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1820 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1826 /** Initialize the video codec context.
1829 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1831 // Initialise the codec if necessary
1832 if ( !self->video_codec )
1834 // Get the video stream
1835 AVStream *stream = self->video_format->streams[ index ];
1837 // Get codec context
1838 AVCodecContext *codec_context = stream->codec;
1841 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1843 if ( codec_context->codec_id == CODEC_ID_H264 )
1845 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1847 if ( vdpau_init( self ) )
1849 self->video_codec = codec_context;
1850 if ( !vdpau_decoder_init( self ) )
1855 codec = avcodec_find_decoder( codec_context->codec_id );
1859 // Initialise multi-threading
1860 int thread_count = mlt_properties_get_int( properties, "threads" );
1861 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1862 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1863 if ( thread_count > 1 )
1864 codec_context->thread_count = thread_count;
1866 // If we don't have a codec and we can't initialise it, we can't do much more...
1867 pthread_mutex_lock( &self->open_mutex );
1868 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1869 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1871 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1874 // Now store the codec with its destructor
1875 self->video_codec = codec_context;
1879 // Remember that we can't use this later
1880 self->video_index = -1;
1881 pthread_mutex_unlock( &self->open_mutex );
1884 pthread_mutex_unlock( &self->open_mutex );
1886 // Process properties as AVOptions
1887 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1888 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1889 if ( codec->priv_class && codec_context->priv_data )
1890 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1893 // Reset some image properties
1894 if ( self->video_codec )
1896 mlt_properties_set_int( properties, "width", self->video_codec->width );
1897 mlt_properties_set_int( properties, "height", self->video_codec->height );
1899 // For DV, we'll just use the saved aspect ratio
1900 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1901 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1903 // Determine the fps first from the codec
1904 double source_fps = (double) self->video_codec->time_base.den /
1905 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1907 if ( mlt_properties_get( properties, "force_fps" ) )
1909 source_fps = mlt_properties_get_double( properties, "force_fps" );
1910 stream->time_base = av_d2q( source_fps, 1024 );
1911 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1912 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1916 // If the muxer reports a frame rate different than the codec
1917 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1918 double muxer_fps = av_q2d( stream->avg_frame_rate );
1919 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1920 muxer_fps = av_q2d( stream->r_frame_rate );
1922 double muxer_fps = av_q2d( stream->r_frame_rate );
1924 // Choose the lesser - the wrong tends to be off by some multiple of 10
1925 source_fps = FFMIN( source_fps, muxer_fps );
1926 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1928 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1929 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1931 else if ( muxer_fps > 0 )
1933 AVRational frame_rate = stream->r_frame_rate;
1934 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1935 // avg_frame_rate gives some approximate value that does not well match the media.
1936 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1937 // results in some very choppy output, but some value slightly different works
1939 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1940 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1941 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1943 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1944 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1948 source_fps = mlt_producer_get_fps( self->parent );
1949 AVRational frame_rate = av_d2q( source_fps, 255 );
1950 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1951 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1955 // Set the YUV colorspace from override or detect
1956 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1957 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1958 if ( ! self->colorspace )
1960 switch ( self->video_codec->colorspace )
1962 case AVCOL_SPC_SMPTE240M:
1963 self->colorspace = 240;
1965 case AVCOL_SPC_BT470BG:
1966 case AVCOL_SPC_SMPTE170M:
1967 self->colorspace = 601;
1969 case AVCOL_SPC_BT709:
1970 self->colorspace = 709;
1973 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1974 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1979 // Let apps get chosen colorspace
1980 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1982 return self->video_codec && self->video_index > -1;
1985 /** Set up video handling.
1988 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1991 mlt_producer producer = self->parent;
1993 // Get the properties
1994 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1996 // Fetch the video format context
1997 AVFormatContext *context = self->video_format;
1999 // Get the video_index
2000 int index = mlt_properties_get_int( properties, "video_index" );
2002 // Reopen the file if necessary
2003 if ( !context && index > -1 )
2005 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2006 mlt_properties_get( properties, "resource" ), 1 );
2007 context = self->video_format;
2010 // Exception handling for video_index
2011 if ( context && index >= (int) context->nb_streams )
2013 // Get the last video stream
2014 for ( index = context->nb_streams - 1;
2015 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
2017 mlt_properties_set_int( properties, "video_index", index );
2019 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
2021 // Invalidate the video stream
2023 mlt_properties_set_int( properties, "video_index", index );
2026 // Update the video properties if the index changed
2027 if ( index != self->video_index )
2029 // Reset the video properties if the index changed
2030 self->video_index = index;
2031 pthread_mutex_lock( &self->open_mutex );
2032 if ( self->video_codec )
2033 avcodec_close( self->video_codec );
2034 self->video_codec = NULL;
2035 pthread_mutex_unlock( &self->open_mutex );
2038 // Get the frame properties
2039 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2042 if ( context && index > -1 && video_codec_init( self, index, properties ) )
2044 // Set the frame properties
2045 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
2046 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
2047 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
2049 // Set the width and height
2050 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
2051 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
2052 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
2053 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
2054 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
2055 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
2057 // Workaround 1088 encodings missing cropping info.
2058 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
2060 mlt_properties_set_int( properties, "meta.media.height", 1080 );
2063 // Add our image operation
2064 mlt_frame_push_service( frame, self );
2065 mlt_frame_push_get_image( frame, producer_get_image );
2069 // If something failed, use test card image
2070 mlt_properties_set_int( frame_properties, "test_image", 1 );
2074 static int seek_audio( producer_avformat self, mlt_position position, double timecode )
2078 // Seek if necessary
2079 if ( self->seekable && position != self->audio_expected )
2081 if ( position + 1 == self->audio_expected )
2083 // We're paused - silence required
2086 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
2088 AVFormatContext *context = self->audio_format;
2089 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
2090 if ( context->start_time != AV_NOPTS_VALUE )
2091 timestamp += context->start_time;
2092 if ( timestamp < 0 )
2095 // Set to the real timecode
2096 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
2099 // Clear the usage in the audio buffer
2100 int i = MAX_AUDIO_STREAMS + 1;
2102 self->audio_used[i - 1] = 0;
2108 static int sample_bytes( AVCodecContext *context )
2110 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2111 return av_get_bytes_per_sample( context->sample_fmt );
2112 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2113 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2115 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2119 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2121 // Fetch the audio_format
2122 AVFormatContext *context = self->audio_format;
2124 // Get the current stream index
2125 int index = pkt.stream_index;
2127 // Get codec context
2128 AVCodecContext *codec_context = self->audio_codec[ index ];
2130 // Obtain the resample context if it exists (not always needed)
2131 ReSampleContext *resample = self->audio_resample[ index ];
2133 // Obtain the audio buffers
2134 uint8_t *audio_buffer = self->audio_buffer[ index ];
2135 uint8_t *decode_buffer = self->decode_buffer[ index ];
2137 int audio_used = self->audio_used[ index ];
2138 uint8_t *ptr = pkt.data;
2142 while ( ptr && ret >= 0 && len > 0 )
2144 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2145 int data_size = self->audio_buffer_size[ index ];
2148 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2149 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2150 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2151 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2153 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2157 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2161 pkt.size = len -= ret;
2162 pkt.data = ptr += ret;
2164 // If decoded successfully
2165 if ( data_size > 0 )
2167 // Figure out how many samples will be needed after resampling
2168 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2169 int samples_needed = self->resample_factor * convert_samples;
2171 // Resize audio buffer to prevent overflow
2172 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2174 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2175 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2179 // Copy to audio buffer while resampling
2180 uint8_t *source = decode_buffer;
2181 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2182 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2186 // Straight copy to audio buffer
2187 memcpy( &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ], decode_buffer, data_size );
2188 audio_used += convert_samples;
2192 while ( *ignore && audio_used )
2195 audio_used -= audio_used > samples ? samples : audio_used;
2196 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2197 audio_used * sizeof_sample );
2202 // If we're behind, ignore this packet
2203 // Skip this on non-seekable, audio-only inputs.
2204 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2206 int64_t pts = pkt.pts;
2207 if ( self->first_pts != 0 )
2208 pts -= self->first_pts;
2209 else if ( context->start_time != AV_NOPTS_VALUE )
2210 pts -= context->start_time;
2211 double timebase = av_q2d( context->streams[ index ]->time_base );
2212 int64_t int_position = ( int64_t )( timebase * pts * fps + 0.5 );
2213 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2215 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
2216 "A pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
2217 pkt.pts, pkt.dts, req_position, self->current_position, int_position );
2219 if ( int_position > 0 )
2221 if ( int_position < req_position )
2222 // We are behind, so skip some
2223 *ignore = req_position - int_position;
2224 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2225 // We are ahead, so seek backwards some more
2226 seek_audio( self, req_position, timecode - 1.0 );
2230 self->audio_used[ index ] = audio_used;
2235 /** Get the audio from a frame.
2237 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2240 producer_avformat self = mlt_frame_pop_audio( frame );
2242 pthread_mutex_lock( &self->audio_mutex );
2244 // Obtain the frame number of this frame
2245 mlt_position position = mlt_frame_original_position( frame );
2247 // Calculate the real time code
2248 double real_timecode = producer_time_of_frame( self->parent, position );
2250 // Get the producer fps
2251 double fps = mlt_producer_get_fps( self->parent );
2253 // Number of frames to ignore (for ffwd)
2254 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2256 // Flag for paused (silence)
2257 int paused = seek_audio( self, position, real_timecode );
2259 // Initialize ignore for all streams from the seek return value
2260 int i = MAX_AUDIO_STREAMS;
2262 ignore[i] = ignore[0];
2264 // Fetch the audio_format
2265 AVFormatContext *context = self->audio_format;
2267 int sizeof_sample = sizeof( int16_t );
2269 // Determine the tracks to use
2270 int index = self->audio_index;
2271 int index_max = self->audio_index + 1;
2272 if ( self->audio_index == INT_MAX )
2275 index_max = FFMIN( MAX_AUDIO_STREAMS, context->nb_streams );
2276 *channels = self->total_channels;
2277 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2278 *frequency = FFMAX( self->max_frequency, *frequency );
2281 // Initialize the resamplers and buffers
2282 for ( ; index < index_max && index < MAX_AUDIO_STREAMS; index++ )
2284 // Get codec context
2285 AVCodecContext *codec_context = self->audio_codec[ index ];
2287 if ( codec_context && !self->audio_buffer[ index ] )
2289 // Check for resample and create if necessary
2290 if ( codec_context->channels <= 2 )
2292 // Determine by how much resampling will increase number of samples
2293 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2294 resample_factor *= (double) *frequency / codec_context->sample_rate;
2295 if ( resample_factor > self->resample_factor )
2296 self->resample_factor = resample_factor;
2298 // Create the resampler
2299 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2300 self->audio_resample[ index ] = av_audio_resample_init(
2301 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2302 codec_context->channels, *frequency, codec_context->sample_rate,
2303 AV_SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2305 self->audio_resample[ index ] = audio_resample_init(
2306 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2307 codec_context->channels, *frequency, codec_context->sample_rate );
2312 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2313 sizeof_sample = sample_bytes( codec_context );
2316 // Check for audio buffer and create if necessary
2317 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2318 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2320 // Check for decoder buffer and create if necessary
2321 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2325 // Get the audio if required
2332 av_init_packet( &pkt );
2334 // If not resampling, give consumer more than requested.
2335 // It requested number samples based on requested frame rate.
2336 // Do not clean this up with a samples *= ...!
2337 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2338 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2340 while ( ret >= 0 && !got_audio )
2342 // Check if the buffer already contains the samples required
2343 if ( self->audio_index != INT_MAX &&
2344 self->audio_used[ self->audio_index ] >= *samples &&
2345 ignore[ self->audio_index ] == 0 )
2350 else if ( self->audio_index == INT_MAX )
2352 // Check if there is enough audio for all streams
2354 for ( index = 0; got_audio && index < index_max; index++ )
2355 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2362 pthread_mutex_lock( &self->packets_mutex );
2363 if ( mlt_deque_count( self->apackets ) )
2365 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2371 ret = av_read_frame( context, &pkt );
2372 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2374 if ( !av_dup_packet( &pkt ) )
2376 AVPacket *tmp = malloc( sizeof(AVPacket) );
2378 mlt_deque_push_back( self->vpackets, tmp );
2382 pthread_mutex_unlock( &self->packets_mutex );
2384 // We only deal with audio from the selected audio index
2385 index = pkt.stream_index;
2386 if ( index < MAX_AUDIO_STREAMS && ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2387 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2389 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2390 self->audio_codec[index]->channels : *channels;
2391 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2394 if ( self->seekable || index != self->video_index )
2395 av_free_packet( &pkt );
2399 // Set some additional return values
2400 *format = mlt_audio_s16;
2401 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2403 index = self->audio_index;
2404 *channels = self->audio_codec[ index ]->channels;
2405 *frequency = self->audio_codec[ index ]->sample_rate;
2406 *format = self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_S32 ? mlt_audio_s32le
2407 : self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_FLT ? mlt_audio_f32le
2409 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2411 else if ( self->audio_index == INT_MAX )
2413 // This only works if all audio tracks have the same sample format.
2414 for ( index = 0; index < index_max; index++ )
2415 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2417 *format = self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_S32 ? mlt_audio_s32le
2418 : self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_FLT ? mlt_audio_f32le
2420 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2425 // Allocate and set the frame's audio buffer
2426 int size = mlt_audio_format_size( *format, *samples, *channels );
2427 *buffer = mlt_pool_alloc( size );
2428 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2430 // Interleave tracks if audio_index=all
2431 if ( self->audio_index == INT_MAX )
2433 uint8_t *dest = *buffer;
2435 for ( i = 0; i < *samples; i++ )
2437 for ( index = 0; index < index_max; index++ )
2438 if ( self->audio_codec[ index ] )
2440 int current_channels = self->audio_codec[ index ]->channels;
2441 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2442 memcpy( dest, src, current_channels * sizeof_sample );
2443 dest += current_channels * sizeof_sample;
2446 for ( index = 0; index < index_max; index++ )
2447 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2449 int current_channels = self->audio_codec[ index ]->channels;
2450 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2451 self->audio_used[index] -= *samples;
2452 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2455 // Copy a single track to the output buffer
2458 index = self->audio_index;
2460 // Now handle the audio if we have enough
2461 if ( self->audio_used[ index ] > 0 )
2463 uint8_t *src = self->audio_buffer[ index ];
2464 // copy samples from audio_buffer
2465 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2466 memcpy( *buffer, src, size * *channels * sizeof_sample );
2467 // supply the remaining requested samples as silence
2468 if ( *samples > self->audio_used[ index ] )
2469 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2470 // reposition the samples within audio_buffer
2471 self->audio_used[ index ] -= size;
2472 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2476 // Otherwise fill with silence
2477 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2483 // Get silence and don't touch the context
2484 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2487 // Regardless of speed (other than paused), we expect to get the next frame
2489 self->audio_expected = position + 1;
2491 pthread_mutex_unlock( &self->audio_mutex );
2496 /** Initialize the audio codec context.
2499 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2501 // Initialise the codec if necessary
2502 if ( !self->audio_codec[ index ] )
2504 // Get codec context
2505 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2508 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2510 // If we don't have a codec and we can't initialise it, we can't do much more...
2511 pthread_mutex_lock( &self->open_mutex );
2512 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2513 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2515 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2518 // Now store the codec with its destructor
2519 if ( self->audio_codec[ index ] )
2520 avcodec_close( self->audio_codec[ index ] );
2521 self->audio_codec[ index ] = codec_context;
2525 // Remember that we can't use self later
2526 self->audio_index = -1;
2528 pthread_mutex_unlock( &self->open_mutex );
2530 // Process properties as AVOptions
2531 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2532 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
2533 if ( codec && codec->priv_class && codec_context->priv_data )
2534 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2537 return self->audio_codec[ index ] && self->audio_index > -1;
2540 /** Set up audio handling.
2543 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2546 mlt_producer producer = self->parent;
2548 // Get the properties
2549 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2551 // Fetch the audio format context
2552 AVFormatContext *context = self->audio_format;
2554 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2556 // Get the audio_index
2557 int index = mlt_properties_get_int( properties, "audio_index" );
2559 // Handle all audio tracks
2560 if ( self->audio_index > -1 &&
2561 mlt_properties_get( properties, "audio_index" ) &&
2562 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2565 // Reopen the file if necessary
2566 if ( !context && self->audio_index > -1 && index > -1 )
2568 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2569 mlt_properties_get( properties, "resource" ), 1 );
2570 context = self->audio_format;
2573 // Exception handling for audio_index
2574 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2576 for ( index = context->nb_streams - 1;
2577 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2579 mlt_properties_set_int( properties, "audio_index", index );
2581 if ( context && index > -1 && index < INT_MAX &&
2582 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2584 index = self->audio_index;
2585 mlt_properties_set_int( properties, "audio_index", index );
2588 // Update the audio properties if the index changed
2589 if ( context && index > -1 && index != self->audio_index )
2591 pthread_mutex_lock( &self->open_mutex );
2592 if ( self->audio_codec[ self->audio_index ] )
2593 avcodec_close( self->audio_codec[ self->audio_index ] );
2594 self->audio_codec[ self->audio_index ] = NULL;
2595 pthread_mutex_unlock( &self->open_mutex );
2597 if ( self->audio_index != -1 )
2598 self->audio_index = index;
2603 if ( context && index == INT_MAX )
2605 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2606 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2607 for ( index = 0; index < context->nb_streams; index++ )
2609 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2610 audio_codec_init( self, index, properties );
2613 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2615 // Set the frame properties
2616 if ( index < MAX_AUDIO_STREAMS )
2618 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2619 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2622 if ( context && index > -1 )
2624 // Add our audio operation
2625 mlt_frame_push_audio( frame, self );
2626 mlt_frame_push_audio( frame, producer_get_audio );
2630 /** Our get frame implementation.
2633 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2635 // Access the private data
2636 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2637 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2638 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2643 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2644 producer->child = self;
2645 self->parent = producer;
2646 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2647 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2650 // Create an empty frame
2651 *frame = mlt_frame_init( service);
2655 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2659 mlt_cache_item_close( cache_item );
2663 // Update timecode on the frame we're creating
2664 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2667 producer_set_up_video( self, *frame );
2670 producer_set_up_audio( self, *frame );
2672 // Set the position of this producer
2673 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2674 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "original_position", position );
2676 // Calculate the next timecode
2677 mlt_producer_prepare_next( producer );
2682 static void producer_avformat_close( producer_avformat self )
2684 mlt_log_debug( NULL, "producer_avformat_close\n" );
2686 // Cleanup av contexts
2687 av_free_packet( &self->pkt );
2688 av_free( self->av_frame );
2689 pthread_mutex_lock( &self->open_mutex );
2691 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2693 if ( self->audio_resample[i] )
2694 audio_resample_close( self->audio_resample[i] );
2695 mlt_pool_release( self->audio_buffer[i] );
2696 av_free( self->decode_buffer[i] );
2697 if ( self->audio_codec[i] )
2698 avcodec_close( self->audio_codec[i] );
2699 self->audio_codec[i] = NULL;
2701 if ( self->video_codec )
2702 avcodec_close( self->video_codec );
2703 self->video_codec = NULL;
2705 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2706 if ( self->dummy_context )
2707 avformat_close_input( &self->dummy_context );
2708 if ( self->seekable && self->audio_format )
2709 avformat_close_input( &self->audio_format );
2710 if ( self->video_format )
2711 avformat_close_input( &self->video_format );
2713 if ( self->dummy_context )
2714 av_close_input_file( self->dummy_context );
2715 if ( self->seekable && self->audio_format )
2716 av_close_input_file( self->audio_format );
2717 if ( self->video_format )
2718 av_close_input_file( self->video_format );
2720 pthread_mutex_unlock( &self->open_mutex );
2722 vdpau_producer_close( self );
2724 if ( self->image_cache )
2725 mlt_cache_close( self->image_cache );
2727 // Cleanup the mutexes
2728 pthread_mutex_destroy( &self->audio_mutex );
2729 pthread_mutex_destroy( &self->video_mutex );
2730 pthread_mutex_destroy( &self->packets_mutex );
2731 pthread_mutex_destroy( &self->open_mutex );
2733 // Cleanup the packet queues
2735 if ( self->apackets )
2737 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2739 av_free_packet( pkt );
2742 mlt_deque_close( self->apackets );
2743 self->apackets = NULL;
2745 if ( self->vpackets )
2747 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2749 av_free_packet( pkt );
2752 mlt_deque_close( self->vpackets );
2753 self->vpackets = NULL;
2759 static void producer_close( mlt_producer parent )
2761 // Remove this instance from the cache
2762 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2765 parent->close = NULL;
2766 mlt_producer_close( parent );