2 * producer_avformat.c -- avformat producer
3 * Copyright (C) 2003-2012 Ushodaya Enterprises Limited
4 * Author: Charles Yates <charles.yates@pandora.be>
5 * Author: Dan Dennedy <dan@dennedy.org>
6 * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include <framework/mlt_producer.h>
25 #include <framework/mlt_frame.h>
26 #include <framework/mlt_profile.h>
27 #include <framework/mlt_log.h>
28 #include <framework/mlt_deque.h>
29 #include <framework/mlt_factory.h>
30 #include <framework/mlt_cache.h>
32 // ffmpeg Header files
33 #include <libavformat/avformat.h>
35 # include <libswscale/swscale.h>
38 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
39 # include <libavutil/samplefmt.h>
41 # define AV_SAMPLE_FMT_S16 SAMPLE_FMT_S16
42 # define AV_SAMPLE_FMT_S32 SAMPLE_FMT_S32
43 # define AV_SAMPLE_FMT_FLT SAMPLE_FMT_FLT
44 # if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
45 const char *avcodec_get_sample_fmt_name(int sample_fmt);
50 # include <libavcodec/vdpau.h>
52 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
53 # include <libavutil/pixdesc.h>
55 #if (LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0))
56 # include <libavutil/dict.h>
59 // System header files
65 #if LIBAVUTIL_VERSION_INT < (50<<16)
66 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
67 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
70 #if LIBAVCODEC_VERSION_MAJOR >= 53
71 #include <libavutil/opt.h>
72 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
73 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
74 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
76 #include <libavcodec/opt.h>
79 #define POSITION_INITIAL (-2)
80 #define POSITION_INVALID (-1)
82 #define MAX_AUDIO_STREAMS (10)
83 #define MAX_VDPAU_SURFACES (10)
85 struct producer_avformat_s
88 AVFormatContext *dummy_context;
89 AVFormatContext *audio_format;
90 AVFormatContext *video_format;
91 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
92 AVCodecContext *video_codec;
94 ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
95 mlt_position audio_expected;
96 mlt_position video_expected;
100 int64_t last_position;
102 int64_t current_position;
103 mlt_position nonseek_position;
106 uint8_t *audio_buffer[ MAX_AUDIO_STREAMS ];
107 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
108 uint8_t *decode_buffer[ MAX_AUDIO_STREAMS ];
109 int audio_used[ MAX_AUDIO_STREAMS ];
111 int audio_max_stream;
115 unsigned int invalid_pts_counter;
116 double resample_factor;
117 mlt_cache image_cache;
118 mlt_cache alpha_cache;
120 pthread_mutex_t video_mutex;
121 pthread_mutex_t audio_mutex;
124 pthread_mutex_t packets_mutex;
125 pthread_mutex_t open_mutex;
130 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
144 typedef struct producer_avformat_s *producer_avformat;
146 // Forward references.
147 static int list_components( char* file );
148 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock );
149 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
150 static void producer_avformat_close( producer_avformat );
151 static void producer_close( mlt_producer parent );
152 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
153 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
154 static void apply_properties( void *obj, mlt_properties properties, int flags );
155 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
156 static void get_audio_streams_info( producer_avformat self );
162 /** Constructor for libavformat.
165 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
167 if ( list_components( file ) )
170 mlt_producer producer = NULL;
172 // Check that we have a non-NULL argument
175 // Construct the producer
176 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
177 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
180 if ( mlt_producer_init( producer, self ) == 0 )
182 self->parent = producer;
184 // Get the properties
185 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
187 // Set the resource property (required for all producers)
188 mlt_properties_set( properties, "resource", file );
190 // Register transport implementation with the producer
191 producer->close = (mlt_destructor) producer_close;
193 // Register our get_frame implementation
194 producer->get_frame = producer_get_frame;
196 if ( strcmp( service, "avformat-novalidate" ) )
199 if ( producer_open( self, profile, file, 1 ) != 0 )
202 mlt_producer_close( producer );
205 else if ( self->seekable )
207 // Close the file to release resources for large playlists - reopen later as needed
208 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
209 if ( self->audio_format )
210 avformat_close_input( &self->audio_format );
211 if ( self->video_format )
212 avformat_close_input( &self->video_format );
214 if ( self->audio_format )
215 av_close_input_file( self->audio_format );
216 if ( self->video_format )
217 av_close_input_file( self->video_format );
219 self->audio_format = NULL;
220 self->video_format = NULL;
225 // Default the user-selectable indices from the auto-detected indices
226 mlt_properties_set_int( properties, "audio_index", self->audio_index );
227 mlt_properties_set_int( properties, "video_index", self->video_index );
229 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
231 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
238 int list_components( char* file )
242 // Report information about available demuxers and codecs as YAML Tiny
243 if ( file && strstr( file, "f-list" ) )
245 fprintf( stderr, "---\nformats:\n" );
246 AVInputFormat *format = NULL;
247 while ( ( format = av_iformat_next( format ) ) )
248 fprintf( stderr, " - %s\n", format->name );
249 fprintf( stderr, "...\n" );
252 if ( file && strstr( file, "acodec-list" ) )
254 fprintf( stderr, "---\naudio_codecs:\n" );
255 AVCodec *codec = NULL;
256 while ( ( codec = av_codec_next( codec ) ) )
257 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
258 fprintf( stderr, " - %s\n", codec->name );
259 fprintf( stderr, "...\n" );
262 if ( file && strstr( file, "vcodec-list" ) )
264 fprintf( stderr, "---\nvideo_codecs:\n" );
265 AVCodec *codec = NULL;
266 while ( ( codec = av_codec_next( codec ) ) )
267 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
268 fprintf( stderr, " - %s\n", codec->name );
269 fprintf( stderr, "...\n" );
276 /** Find the default streams.
279 static mlt_properties find_default_streams( producer_avformat self )
283 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
284 AVDictionaryEntry *tag = NULL;
286 AVMetadataTag *tag = NULL;
288 AVFormatContext *context = self->video_format;
289 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
291 // Default to the first audio and video streams found
292 self->audio_index = -1;
293 self->video_index = -1;
295 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
297 // Allow for multiple audio and video streams in the file and select first of each (if available)
298 for( i = 0; i < context->nb_streams; i++ )
300 // Get the codec context
301 AVStream *stream = context->streams[ i ];
302 if ( ! stream ) continue;
303 AVCodecContext *codec_context = stream->codec;
304 if ( ! codec_context ) continue;
305 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
306 if ( ! codec ) continue;
308 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
310 // Determine the type and obtain the first index of each type
311 switch( codec_context->codec_type )
313 case CODEC_TYPE_VIDEO:
314 // Use first video stream
315 if ( self->video_index < 0 )
316 self->video_index = i;
317 mlt_properties_set( meta_media, key, "video" );
318 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
319 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
320 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
321 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
322 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
323 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
325 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
328 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
329 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
330 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
332 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
333 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
334 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
335 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
336 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(3<<8)+0)
337 mlt_properties_set( meta_media, key, av_get_pix_fmt_name( codec_context->pix_fmt ) );
339 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
341 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
342 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
343 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
344 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
345 switch ( codec_context->colorspace )
347 case AVCOL_SPC_SMPTE240M:
348 mlt_properties_set_int( meta_media, key, 240 );
350 case AVCOL_SPC_BT470BG:
351 case AVCOL_SPC_SMPTE170M:
352 mlt_properties_set_int( meta_media, key, 601 );
354 case AVCOL_SPC_BT709:
355 mlt_properties_set_int( meta_media, key, 709 );
358 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
359 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
364 case CODEC_TYPE_AUDIO:
365 // Use first audio stream
366 if ( self->audio_index < 0 )
367 self->audio_index = i;
368 mlt_properties_set( meta_media, key, "audio" );
369 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
370 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
371 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
372 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
373 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
374 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
376 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
377 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
378 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
379 mlt_properties_set_int( meta_media, key, codec_context->channels );
384 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
385 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
386 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
387 mlt_properties_set( meta_media, key, codec->name );
388 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
389 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
390 mlt_properties_set( meta_media, key, codec->long_name );
392 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
393 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
394 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
395 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
396 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
397 // mlt_properties_set_int( meta_media, key, codec_context->profile );
398 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
399 // mlt_properties_set_int( meta_media, key, codec_context->level );
402 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
403 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
404 while ( ( tag = av_dict_get( stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
406 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
409 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
411 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
412 mlt_properties_set( meta_media, key, tag->value );
417 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
418 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
419 while ( ( tag = av_dict_get( context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
421 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
424 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
426 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
427 mlt_properties_set( meta_media, key, tag->value );
431 if ( context->title && strcmp( context->title, "" ) )
432 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
433 if ( context->author && strcmp( context->author, "" ) )
434 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
435 if ( context->copyright && strcmp( context->copyright, "" ) )
436 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
437 if ( context->comment )
438 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
439 if ( context->album )
440 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
442 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
443 if ( context->track )
444 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
450 static inline int dv_is_pal( AVPacket *pkt )
452 return pkt->data[3] & 0x80;
455 static int dv_is_wide( AVPacket *pkt )
457 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
459 for ( ; i < pkt->size; i += 5 /* packet size */ )
461 if ( pkt->data[ i ] == 0x61 )
463 uint8_t x = pkt->data[ i + 2 ] & 0x7;
464 return ( x == 2 ) || ( x == 7 );
470 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
472 double aspect_ratio = 1.0;
474 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
478 if ( dv_is_pal( pkt ) )
480 if ( dv_is_wide( pkt ) )
482 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
483 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
487 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
488 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
493 if ( dv_is_wide( pkt ) )
495 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
496 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
500 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
501 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
508 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
509 stream->sample_aspect_ratio;
511 codec_context->sample_aspect_ratio;
513 // Override FFmpeg's notion of DV aspect ratios, which are
514 // based upon a width of 704. Since we do not have a normaliser
515 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
516 // we just coerce the values to facilitate a passive behaviour through
517 // the rescale normaliser when using equivalent producers and consumers.
518 // = display_aspect / (width * height)
519 if ( ar.num == 10 && ar.den == 11 )
522 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
523 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
525 else if ( ar.num == 59 && ar.den == 54 )
528 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
529 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
531 else if ( ar.num == 40 && ar.den == 33 )
534 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
535 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
537 else if ( ar.num == 118 && ar.den == 81 )
540 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
541 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
547 AVRational codec_sar = codec_context->sample_aspect_ratio;
548 AVRational stream_sar =
549 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
550 stream->sample_aspect_ratio;
554 if ( codec_sar.num > 0 )
556 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
557 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
559 else if ( stream_sar.num > 0 )
561 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
562 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
566 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
567 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
570 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
571 aspect_ratio = av_q2d( ar );
572 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
577 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
578 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVDictionary **params )
580 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
583 if ( !URL ) return NULL;
586 char *protocol = strdup( URL );
587 char *url = strchr( protocol, ':' );
589 // Only if there is not a protocol specification that avformat can handle
590 #if LIBAVFORMAT_VERSION_MAJOR >= 53
591 if ( url && avio_check( URL, 0 ) < 0 )
593 if ( url && !url_exist( URL ) )
596 // Truncate protocol string
598 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
601 *format = av_find_input_format( protocol );
603 // Eat the format designator
608 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
609 // support for legacy width and height parameters
613 // These are required by video4linux2 (defaults)
614 params->width = profile->width;
615 params->height = profile->height;
616 if ( !strstr( URL, "&frame_rate" ) )
617 params->time_base = (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
618 params->channels = 2;
619 params->sample_rate = 48000;
623 url = strchr( url, '?' );
627 char *name = strdup( ++url );
628 char *value = strchr( name, '=' );
630 // Also accept : as delimiter for backwards compatibility.
631 value = strchr( name, ':' );
636 char *t = strchr( value, '&' );
639 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
640 // translate old parameters to new av_dict names
641 if ( !strcmp( name, "frame_rate" ) )
642 av_dict_set( params, "framerate", value, 0 );
643 else if ( !strcmp( name, "pix_fmt" ) )
644 av_dict_set( params, "pixel_format", value, 0 );
645 else if ( !strcmp( name, "width" ) )
646 width = strdup( value );
647 else if ( !strcmp( name, "height" ) )
648 height = strdup( value );
650 // generic demux/device option support
651 av_dict_set( params, name, value, 0 );
653 if ( !strcmp( name, "frame_rate" ) )
654 params->time_base.den = atoi( value );
655 else if ( !strcmp( name, "frame_rate_base" ) )
656 params->time_base.num = atoi( value );
657 else if ( !strcmp( name, "sample_rate" ) )
658 params->sample_rate = atoi( value );
659 else if ( !strcmp( name, "channel" ) )
660 params->channel = atoi( value );
661 else if ( !strcmp( name, "channels" ) )
662 params->channels = atoi( value );
663 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
664 else if ( !strcmp( name, "pix_fmt" ) )
665 params->pix_fmt = av_get_pix_fmt( value );
667 else if ( !strcmp( name, "width" ) )
668 params->width = atoi( value );
669 else if ( !strcmp( name, "height" ) )
670 params->height = atoi( value );
671 else if ( !strcmp( name, "standard" ) )
672 params->standard = strdup( value );
676 url = strchr( url, '&' );
678 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
679 // continued support for legacy width and height parameters
680 if ( width && height )
682 char *s = malloc( strlen( width ) + strlen( height ) + 2 );
686 av_dict_set( params, "video_size", s, 0 );
689 if ( width ) free( width );
690 if ( height ) free ( height );
693 result = strdup( result );
697 result = strdup( URL );
703 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
707 // Get the properties
708 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
710 AVFormatContext *format = self->video_format;
712 // We will treat everything with the producer fps.
713 // TODO: make this more flexible.
714 double fps = mlt_profile_fps( profile );
717 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
719 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
720 // when producer_open is called after initial call when restoring or reseting the producer.
721 if ( format->duration != AV_NOPTS_VALUE )
723 // This isn't going to be accurate for all formats
724 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
725 mlt_properties_set_position( properties, "out", frames - 1 );
726 mlt_properties_set_position( properties, "length", frames );
727 mlt_properties_set_int( properties, "_length_computed", 1 );
731 // Set live sources to run forever
732 mlt_properties_set_position( properties, "length", INT_MAX );
733 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
734 mlt_properties_set( properties, "eof", "loop" );
735 mlt_properties_set_int( properties, "_length_computed", 1 );
739 // Check if we're seekable
740 // avdevices are typically AVFMT_NOFILE and not seekable
741 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
744 // protocols can indicate if they support seeking
745 #if LIBAVFORMAT_VERSION_MAJOR >= 53
746 self->seekable = format->pb->seekable;
748 URLContext *uc = url_fileno( format->pb );
750 self->seekable = !uc->is_streamed;
753 if ( self->seekable )
755 // Do a more rigourous test of seekable on a disposable context
756 self->seekable = av_seek_frame( format, -1, format->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
757 mlt_properties_set_int( properties, "seekable", self->seekable );
758 self->dummy_context = format;
759 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
760 self->video_format = NULL;
761 avformat_open_input( &self->video_format, filename, NULL, NULL );
762 avformat_find_stream_info( self->video_format, NULL );
764 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
765 av_find_stream_info( self->video_format );
767 format = self->video_format;
770 // Fetch the width, height and aspect ratio
771 if ( self->video_index != -1 )
773 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
774 mlt_properties_set_int( properties, "width", codec_context->width );
775 mlt_properties_set_int( properties, "height", codec_context->height );
777 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
779 // Fetch the first frame of DV so we can read it directly
784 ret = av_read_frame( format, &pkt );
785 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
787 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
794 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
798 // Verify that we can convert this to YUV 4:2:2
799 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
800 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
801 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
803 sws_freeContext( context );
814 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
816 // Return an error code (0 == no error)
818 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
823 pthread_mutex_init( &self->audio_mutex, NULL );
824 pthread_mutex_init( &self->video_mutex, NULL );
825 pthread_mutex_init( &self->packets_mutex, NULL );
826 pthread_mutex_init( &self->open_mutex, NULL );
827 pthread_mutex_lock( &self->audio_mutex );
828 pthread_mutex_lock( &self->video_mutex );
830 mlt_events_block( properties, self->parent );
833 AVInputFormat *format = NULL;
834 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
835 AVDictionary *params = NULL;
837 AVFormatParameters params;
838 memset( ¶ms, 0, sizeof(params) );
840 char *filename = parse_url( profile, URL, &format, ¶ms );
842 // Now attempt to open the file or device with filename
843 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
844 error = avformat_open_input( &self->video_format, filename, format, ¶ms ) < 0;
846 // If the URL is a network stream URL, then we probably need to open with full URL
847 error = avformat_open_input( &self->video_format, URL, format, ¶ms ) < 0;
849 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
851 // If the URL is a network stream URL, then we probably need to open with full URL
852 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
855 // Set MLT properties onto video AVFormatContext
856 if ( !error && self->video_format )
858 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
859 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
860 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
861 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
865 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
866 av_dict_free( ¶ms );
868 // Cleanup AVFormatParameters
869 if ( params.standard )
870 free( (void*) params.standard );
873 // If successful, then try to get additional info
874 if ( !error && self->video_format )
876 // Get the stream info
877 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
878 error = avformat_find_stream_info( self->video_format, NULL ) < 0;
880 error = av_find_stream_info( self->video_format ) < 0;
883 // Continue if no error
884 if ( !error && self->video_format )
886 // Find default audio and video streams
887 find_default_streams( self );
888 error = get_basic_info( self, profile, filename );
890 // Initialize position info
891 self->first_pts = -1;
892 self->last_position = POSITION_INITIAL;
894 if ( !self->audio_format )
896 // We're going to cheat here - for seekable A/V files, we will have separate contexts
897 // to support independent seeking of audio from video.
898 // TODO: Is this really necessary?
899 if ( self->audio_index != -1 && self->video_index != -1 )
901 if ( self->seekable )
903 // And open again for our audio context
904 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
905 avformat_open_input( &self->audio_format, filename, NULL, NULL );
906 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
907 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
908 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
909 avformat_find_stream_info( self->audio_format, NULL );
911 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
912 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
913 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
914 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
915 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
917 av_find_stream_info( self->audio_format );
922 self->audio_format = self->video_format;
925 else if ( self->audio_index != -1 )
927 // We only have an audio context
928 self->audio_format = self->video_format;
929 self->video_format = NULL;
931 else if ( self->video_index == -1 )
933 // Something has gone wrong
936 if ( self->audio_format && !self->audio_streams )
937 get_audio_streams_info( self );
945 self->apackets = mlt_deque_init();
946 self->vpackets = mlt_deque_init();
949 if ( self->dummy_context )
951 pthread_mutex_lock( &self->open_mutex );
952 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
953 avformat_close_input( &self->dummy_context );
955 av_close_input_file( self->dummy_context );
957 self->dummy_context = NULL;
958 pthread_mutex_unlock( &self->open_mutex );
961 // Unlock the service
964 pthread_mutex_unlock( &self->audio_mutex );
965 pthread_mutex_unlock( &self->video_mutex );
967 mlt_events_unblock( properties, self->parent );
972 static void reopen_video( producer_avformat self, mlt_producer producer )
974 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
975 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
976 pthread_mutex_lock( &self->audio_mutex );
977 pthread_mutex_lock( &self->open_mutex );
979 if ( self->video_codec )
980 avcodec_close( self->video_codec );
981 self->video_codec = NULL;
982 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
983 if ( self->dummy_context )
984 avformat_close_input( &self->dummy_context );
985 if ( self->video_format )
986 avformat_close_input( &self->video_format );
988 if ( self->dummy_context )
989 av_close_input_file( self->dummy_context );
990 if ( self->video_format )
991 av_close_input_file( self->video_format );
993 self->dummy_context = NULL;
994 self->video_format = NULL;
995 pthread_mutex_unlock( &self->open_mutex );
997 int audio_index = self->audio_index;
998 int video_index = self->video_index;
1000 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1001 mlt_properties_get( properties, "resource" ), 0 );
1003 self->audio_index = audio_index;
1004 if ( self->video_format && video_index > -1 )
1006 self->video_index = video_index;
1007 video_codec_init( self, video_index, properties );
1010 pthread_mutex_unlock( &self->audio_mutex );
1011 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1014 static int seek_video( producer_avformat self, mlt_position position,
1015 int64_t req_position, int must_decode, int use_new_seek, int *ignore )
1017 mlt_producer producer = self->parent;
1020 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
1022 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1024 // Fetch the video format context
1025 AVFormatContext *context = self->video_format;
1027 // Get the video stream
1028 AVStream *stream = context->streams[ self->video_index ];
1030 // Get codec context
1031 AVCodecContext *codec_context = stream->codec;
1033 // We may want to use the source fps if available
1034 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1035 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1037 if ( self->av_frame && position + 1 == self->video_expected )
1039 // We're paused - use last image
1042 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
1044 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1045 *ignore = ( int )( ( position - self->video_expected ) / mlt_producer_get_fps( producer ) * source_fps );
1046 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1048 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
1050 if ( use_new_seek && self->last_position == POSITION_INITIAL )
1052 // find first key frame
1057 while ( ret >= 0 && toscan-- > 0 )
1059 ret = av_read_frame( context, &pkt );
1060 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
1062 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n", pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
1063 self->first_pts = pkt.pts;
1066 av_free_packet( &pkt );
1069 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1072 // Calculate the timestamp for the requested frame
1076 timestamp = ( req_position - 0.1 / source_fps ) /
1077 ( av_q2d( stream->time_base ) * source_fps );
1078 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pos %"PRId64" pts %"PRId64"\n", req_position, timestamp );
1079 if ( self->first_pts > 0 )
1080 timestamp += self->first_pts;
1081 else if ( context->start_time != AV_NOPTS_VALUE )
1082 timestamp += context->start_time;
1086 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
1087 if ( context->start_time != AV_NOPTS_VALUE )
1088 timestamp += context->start_time;
1091 timestamp -= AV_TIME_BASE;
1092 if ( timestamp < 0 )
1094 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
1095 timestamp, position, self->video_expected, self->last_position );
1097 // Seek to the timestamp
1100 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1101 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1103 else if ( req_position > 0 || self->last_position <= 0 )
1105 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
1109 // Re-open video stream when rewinding to beginning from somewhere else.
1110 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1111 // not reliably seeking to the first frame across formats.
1112 reopen_video( self, producer );
1115 // Remove the cached info relating to the previous position
1116 self->current_position = POSITION_INVALID;
1117 self->last_position = POSITION_INVALID;
1118 av_freep( &self->av_frame );
1122 // flush any pictures still in decode buffer
1123 avcodec_flush_buffers( codec_context );
1130 /** Convert a frame position to a time code.
1133 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1135 return ( double )position / mlt_producer_get_fps( producer );
1138 // Collect information about all audio streams
1140 static void get_audio_streams_info( producer_avformat self )
1142 // Fetch the audio format context
1143 AVFormatContext *context = self->audio_format;
1147 i < context->nb_streams;
1150 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1152 AVCodecContext *codec_context = context->streams[i]->codec;
1153 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1155 // If we don't have a codec and we can't initialise it, we can't do much more...
1156 pthread_mutex_lock( &self->open_mutex );
1157 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1158 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1160 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1163 self->audio_streams++;
1164 self->audio_max_stream = i;
1165 self->total_channels += codec_context->channels;
1166 if ( codec_context->channels > self->max_channel )
1167 self->max_channel = codec_context->channels;
1168 if ( codec_context->sample_rate > self->max_frequency )
1169 self->max_frequency = codec_context->sample_rate;
1170 avcodec_close( codec_context );
1172 pthread_mutex_unlock( &self->open_mutex );
1175 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1176 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1178 // Other audio-specific initializations
1179 self->resample_factor = 1.0;
1182 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1184 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1186 const int *new_coefficients;
1188 int brightness, contrast, saturation;
1190 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1191 &brightness, &contrast, &saturation ) != -1 )
1193 // Don't change these from defaults unless explicitly told to.
1194 if ( use_full_range >= 0 )
1195 full_range = use_full_range;
1196 switch ( colorspace )
1202 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1205 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1208 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1211 new_coefficients = coefficients;
1214 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1215 brightness, contrast, saturation );
1220 static mlt_image_format pick_format( enum PixelFormat pix_fmt )
1228 return mlt_image_rgb24a;
1229 case PIX_FMT_YUV420P:
1230 case PIX_FMT_YUVJ420P:
1231 case PIX_FMT_YUVA420P:
1232 return mlt_image_yuv420p;
1236 case PIX_FMT_MONOWHITE:
1237 case PIX_FMT_MONOBLACK:
1240 return mlt_image_rgb24;
1242 return mlt_image_yuv422;
1246 static void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
1247 mlt_image_format *format, int width, int height, int colorspace, uint8_t **alpha )
1250 int full_range = -1;
1251 int flags = SWS_BICUBIC | SWS_ACCURATE_RND;
1254 flags |= SWS_CPU_CAPS_MMX;
1257 flags |= SWS_CPU_CAPS_MMX2;
1260 // extract alpha from planar formats
1261 if ( ( pix_fmt == PIX_FMT_YUVA420P || pix_fmt == PIX_FMT_YUVA444P ) &&
1262 *format != mlt_image_rgb24a && *format != mlt_image_opengl &&
1263 frame->data[3] && frame->linesize[3] )
1268 dst = *alpha = mlt_pool_alloc( width * height );
1269 src = frame->data[3];
1271 for ( i = 0; i < height; dst += width, src += frame->linesize[3], i++ )
1272 memcpy( dst, src, FFMIN( width, frame->linesize[3] ) );
1275 if ( *format == mlt_image_yuv420p )
1277 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1278 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1280 output.data[0] = buffer;
1281 output.data[1] = buffer + width * height;
1282 output.data[2] = buffer + ( 5 * width * height ) / 4;
1283 output.linesize[0] = width;
1284 output.linesize[1] = width >> 1;
1285 output.linesize[2] = width >> 1;
1286 set_luma_transfer( context, colorspace, full_range );
1287 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1288 output.data, output.linesize);
1289 sws_freeContext( context );
1291 else if ( *format == mlt_image_rgb24 )
1293 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1294 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1296 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1297 set_luma_transfer( context, colorspace, full_range );
1298 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1299 output.data, output.linesize);
1300 sws_freeContext( context );
1302 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1304 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1305 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1307 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1308 set_luma_transfer( context, colorspace, full_range );
1309 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1310 output.data, output.linesize);
1311 sws_freeContext( context );
1315 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1316 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1318 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1319 set_luma_transfer( context, colorspace, full_range );
1320 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1321 output.data, output.linesize);
1322 sws_freeContext( context );
1325 if ( *format == mlt_image_yuv420p )
1328 pict.data[0] = buffer;
1329 pict.data[1] = buffer + width * height;
1330 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1331 pict.linesize[0] = width;
1332 pict.linesize[1] = width >> 1;
1333 pict.linesize[2] = width >> 1;
1334 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1336 else if ( *format == mlt_image_rgb24 )
1339 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1340 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1342 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
1345 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1346 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1351 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1352 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1357 /** Allocate the image buffer and set it on the frame.
1360 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1364 if ( codec_context->width == 0 || codec_context->height == 0 )
1366 *width = codec_context->width;
1367 *height = codec_context->height;
1368 size = mlt_image_format_size( *format, *width, *height, NULL );
1369 *buffer = mlt_pool_alloc( size );
1371 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1378 /** Get an image from a frame.
1381 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1384 producer_avformat self = mlt_frame_pop_service( frame );
1385 mlt_producer producer = self->parent;
1387 // Get the properties from the frame
1388 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1390 // Obtain the frame number of this frame
1391 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1393 // Get the producer properties
1394 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1396 pthread_mutex_lock( &self->video_mutex );
1398 // Fetch the video format context
1399 AVFormatContext *context = self->video_format;
1401 // Get the video stream
1402 AVStream *stream = context->streams[ self->video_index ];
1404 // Get codec context
1405 AVCodecContext *codec_context = stream->codec;
1407 uint8_t *alpha = NULL;
1409 // Get the image cache
1410 if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1412 self->image_cache = mlt_cache_init();
1413 self->alpha_cache = mlt_cache_init();
1415 if ( self->image_cache )
1417 mlt_cache_item item = mlt_cache_get( self->image_cache, (void*) position );
1418 uint8_t *original = mlt_cache_item_data( item, (int*) format );
1421 // Set the resolution
1422 *width = codec_context->width;
1423 *height = codec_context->height;
1425 // Workaround 1088 encodings missing cropping info.
1426 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1430 int size = mlt_image_format_size( *format, *width, *height, NULL );
1433 *buffer = mlt_pool_alloc( size );
1434 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1435 memcpy( *buffer, original, size );
1436 mlt_cache_item_close( item );
1441 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1442 mlt_frame_set_image( frame, *buffer, size, NULL );
1444 self->got_picture = 1;
1447 item = mlt_cache_get( self->alpha_cache, (void*) position );
1448 original = mlt_cache_item_data( item, &size );
1451 alpha = mlt_pool_alloc( size );
1452 memcpy( alpha, original, size );
1453 mlt_cache_item_close( item );
1456 goto exit_get_image;
1465 // Special case ffwd handling
1468 // We may want to use the source fps if available
1469 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1470 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1472 // This is the physical frame position in the source
1473 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1475 // Determines if we have to decode all frames in a sequence
1476 // Temporary hack to improve intra frame only
1477 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1478 strcmp( codec_context->codec->name, "dnxhd" ) &&
1479 strcmp( codec_context->codec->name, "dvvideo" ) &&
1480 strcmp( codec_context->codec->name, "huffyuv" ) &&
1481 strcmp( codec_context->codec->name, "mjpeg" ) &&
1482 strcmp( codec_context->codec->name, "rawvideo" ) );
1484 // Turn on usage of new seek API and PTS for seeking
1485 int use_new_seek = self->seekable &&
1486 codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1487 if ( mlt_properties_get( properties, "new_seek" ) )
1488 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1489 double delay = mlt_properties_get_double( properties, "video_delay" );
1491 // Seek if necessary
1492 int paused = seek_video( self, position, req_position, must_decode, use_new_seek, &ignore );
1494 // Seek might have reopened the file
1495 context = self->video_format;
1496 stream = context->streams[ self->video_index ];
1497 codec_context = stream->codec;
1498 if ( *format == mlt_image_none ||
1499 codec_context->pix_fmt == PIX_FMT_ARGB ||
1500 codec_context->pix_fmt == PIX_FMT_RGBA ||
1501 codec_context->pix_fmt == PIX_FMT_ABGR ||
1502 codec_context->pix_fmt == PIX_FMT_BGRA )
1503 *format = pick_format( codec_context->pix_fmt );
1505 // Duplicate the last image if necessary
1506 if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture
1508 || self->current_position == req_position
1509 || ( !use_new_seek && 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 );
1536 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1541 int64_t int_position = 0;
1542 int decode_errors = 0;
1543 int got_picture = 0;
1545 av_init_packet( &pkt );
1547 // Construct an AVFrame for YUV422 conversion
1548 if ( !self->av_frame )
1549 self->av_frame = avcodec_alloc_frame( );
1551 while( ret >= 0 && !got_picture )
1554 pthread_mutex_lock( &self->packets_mutex );
1555 if ( mlt_deque_count( self->vpackets ) )
1557 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1563 ret = av_read_frame( context, &pkt );
1564 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->audio_index )
1566 if ( !av_dup_packet( &pkt ) )
1568 AVPacket *tmp = malloc( sizeof(AVPacket) );
1570 mlt_deque_push_back( self->apackets, tmp );
1574 pthread_mutex_unlock( &self->packets_mutex );
1576 // We only deal with video from the selected video_index
1577 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1579 // Determine time code of the packet
1582 int64_t pts = pkt.pts;
1583 if ( self->first_pts > 0 )
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.1 );
1588 if ( pkt.pts == AV_NOPTS_VALUE )
1590 self->invalid_pts_counter++;
1591 if ( self->invalid_pts_counter > 20 )
1593 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1594 mlt_properties_set_int( properties, "new_seek", 0 );
1595 int_position = req_position;
1601 self->invalid_pts_counter = 0;
1603 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1604 pkt.pts, req_position, self->current_position, int_position );
1608 if ( pkt.dts != AV_NOPTS_VALUE )
1610 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pkt.dts + delay ) * source_fps + 0.5 );
1611 if ( context->start_time != AV_NOPTS_VALUE )
1612 int_position -= ( int64_t )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1613 if ( int_position == self->last_position )
1614 int_position = self->last_position + 1;
1616 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1617 pkt.dts, req_position, self->current_position, int_position );
1618 // Make a dumb assumption on streams that contain wild timestamps
1619 if ( abs( req_position - int_position ) > 999 )
1621 int_position = req_position;
1622 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1625 self->last_position = int_position;
1628 if ( must_decode || int_position >= req_position )
1633 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1635 vdpau_decoder_init( self );
1637 self->vdpau->is_decoded = 0;
1640 codec_context->reordered_opaque = pkt.pts;
1641 if ( int_position >= req_position )
1642 codec_context->skip_loop_filter = AVDISCARD_NONE;
1643 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1644 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1646 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1648 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1651 if ( ++decode_errors <= 10 )
1664 // Determine time code of the packet
1665 int64_t pts = self->av_frame->reordered_opaque;
1666 if ( self->first_pts > 0 )
1667 pts -= self->first_pts;
1668 else if ( context->start_time != AV_NOPTS_VALUE )
1669 pts -= context->start_time;
1670 int_position = ( int64_t )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1671 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %"PRId64", key %d\n", int_position, self->av_frame->key_frame );
1674 if ( int_position < req_position )
1679 else if ( int_position >= req_position )
1682 codec_context->skip_loop_filter = AVDISCARD_NONE;
1684 else if ( ignore -- )
1689 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1692 // Now handle the picture if we have one
1695 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1697 // Workaround 1088 encodings missing cropping info.
1698 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1703 if ( self->vdpau->is_decoded )
1705 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1707 uint32_t pitches[3];
1708 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1710 if ( !self->vdpau->buffer )
1711 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1712 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1713 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1714 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1715 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1716 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1717 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1719 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1720 if ( status == VDP_STATUS_OK )
1722 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1723 format, *width, *height, self->colorspace, &alpha );
1727 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1728 image_size = self->vdpau->is_decoded = 0;
1733 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1734 image_size = got_picture = 0;
1739 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1740 format, *width, *height, self->colorspace, &alpha );
1741 self->top_field_first |= self->av_frame->top_field_first;
1742 self->current_position = int_position;
1743 self->got_picture = 1;
1750 if ( self->seekable || pkt.stream_index != self->audio_index )
1751 av_free_packet( &pkt );
1755 if ( self->got_picture && image_size > 0 && self->image_cache )
1757 // Copy buffer to image cache
1758 uint8_t *image = mlt_pool_alloc( image_size );
1759 memcpy( image, *buffer, image_size );
1760 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1763 int alpha_size = (*width) * (*height);
1764 image = mlt_pool_alloc( alpha_size );
1765 memcpy( image, alpha, alpha_size );
1766 mlt_cache_put( self->alpha_cache, (void*) position, image, alpha_size, mlt_pool_release );
1769 // Try to duplicate last image if there was a decoding failure
1770 else if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1773 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1775 // Workaround 1088 encodings missing cropping info.
1776 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1779 if ( self->vdpau && self->vdpau->buffer )
1782 picture.data[0] = self->vdpau->buffer;
1783 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1784 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1785 picture.linesize[0] = codec_context->width;
1786 picture.linesize[1] = codec_context->width / 2;
1787 picture.linesize[2] = codec_context->width / 2;
1788 convert_image( (AVFrame*) &picture, *buffer,
1789 PIX_FMT_YUV420P, format, *width, *height, self->colorspace, &alpha );
1793 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1794 format, *width, *height, self->colorspace, &alpha );
1795 self->got_picture = 1;
1798 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1801 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1802 self->video_expected = position + 1;
1806 pthread_mutex_unlock( &self->video_mutex );
1808 // Set the progressive flag
1809 if ( mlt_properties_get( properties, "force_progressive" ) )
1810 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1811 else if ( self->av_frame )
1812 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1814 // Set the field order property for this frame
1815 if ( mlt_properties_get( properties, "force_tff" ) )
1816 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1818 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1820 // Set immutable properties of the selected track's (or overridden) source attributes.
1821 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1822 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1823 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1824 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1828 mlt_frame_set_alpha( frame, alpha, (*width) * (*height), mlt_pool_release );
1830 return !self->got_picture;
1833 /** Process properties as AVOptions and apply to AV context obj
1836 static void apply_properties( void *obj, mlt_properties properties, int flags )
1839 int count = mlt_properties_count( properties );
1840 for ( i = 0; i < count; i++ )
1842 const char *opt_name = mlt_properties_get_name( properties, i );
1843 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
1844 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1846 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1848 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1851 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1852 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1853 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1854 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1855 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1856 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1858 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1864 /** Initialize the video codec context.
1867 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1869 // Initialise the codec if necessary
1870 if ( !self->video_codec )
1872 // Get the video stream
1873 AVStream *stream = self->video_format->streams[ index ];
1875 // Get codec context
1876 AVCodecContext *codec_context = stream->codec;
1879 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1881 if ( codec_context->codec_id == CODEC_ID_H264 )
1883 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1885 if ( vdpau_init( self ) )
1887 self->video_codec = codec_context;
1888 if ( !vdpau_decoder_init( self ) )
1893 codec = avcodec_find_decoder( codec_context->codec_id );
1897 // Initialise multi-threading
1898 int thread_count = mlt_properties_get_int( properties, "threads" );
1899 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1900 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1901 if ( thread_count > 1 )
1902 codec_context->thread_count = thread_count;
1904 // If we don't have a codec and we can't initialise it, we can't do much more...
1905 pthread_mutex_lock( &self->open_mutex );
1906 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1907 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1909 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1912 // Now store the codec with its destructor
1913 self->video_codec = codec_context;
1917 // Remember that we can't use this later
1918 self->video_index = -1;
1919 pthread_mutex_unlock( &self->open_mutex );
1922 pthread_mutex_unlock( &self->open_mutex );
1924 // Process properties as AVOptions
1925 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1926 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1927 if ( codec->priv_class && codec_context->priv_data )
1928 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1931 // Reset some image properties
1932 mlt_properties_set_int( properties, "width", self->video_codec->width );
1933 mlt_properties_set_int( properties, "height", self->video_codec->height );
1934 // For DV, we'll just use the saved aspect ratio
1935 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1936 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1938 // Determine the fps first from the codec
1939 double source_fps = (double) self->video_codec->time_base.den /
1940 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1942 if ( mlt_properties_get( properties, "force_fps" ) )
1944 source_fps = mlt_properties_get_double( properties, "force_fps" );
1945 stream->time_base = av_d2q( source_fps, 1024 );
1946 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1947 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1951 // If the muxer reports a frame rate different than the codec
1952 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1953 double muxer_fps = av_q2d( stream->avg_frame_rate );
1954 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1955 muxer_fps = av_q2d( stream->r_frame_rate );
1957 double muxer_fps = av_q2d( stream->r_frame_rate );
1959 // Choose the lesser - the wrong tends to be off by some multiple of 10
1960 source_fps = FFMIN( source_fps, muxer_fps );
1961 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1963 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1964 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1966 else if ( muxer_fps > 0 )
1968 AVRational frame_rate = stream->r_frame_rate;
1969 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1970 // avg_frame_rate gives some approximate value that does not well match the media.
1971 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1972 // results in some very choppy output, but some value slightly different works
1974 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1975 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1976 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1978 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1979 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1980 source_fps = av_q2d( frame_rate );
1984 source_fps = mlt_producer_get_fps( self->parent );
1985 AVRational frame_rate = av_d2q( source_fps, 255 );
1986 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1987 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1991 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1992 if ( source_fps > 0 )
1993 mlt_properties_set_double( properties, "source_fps", source_fps );
1995 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
1997 // Set the YUV colorspace from override or detect
1998 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1999 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
2000 if ( ! self->colorspace )
2002 switch ( self->video_codec->colorspace )
2004 case AVCOL_SPC_SMPTE240M:
2005 self->colorspace = 240;
2007 case AVCOL_SPC_BT470BG:
2008 case AVCOL_SPC_SMPTE170M:
2009 self->colorspace = 601;
2011 case AVCOL_SPC_BT709:
2012 self->colorspace = 709;
2015 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
2016 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
2021 // Let apps get chosen colorspace
2022 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
2024 return self->video_codec && self->video_index > -1;
2027 /** Set up video handling.
2030 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
2033 mlt_producer producer = self->parent;
2035 // Get the properties
2036 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2038 // Fetch the video format context
2039 AVFormatContext *context = self->video_format;
2041 // Get the video_index
2042 int index = mlt_properties_get_int( properties, "video_index" );
2044 // Reopen the file if necessary
2045 if ( !context && index > -1 )
2047 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2048 mlt_properties_get( properties, "resource" ), 1 );
2049 context = self->video_format;
2052 // Exception handling for video_index
2053 if ( context && index >= (int) context->nb_streams )
2055 // Get the last video stream
2056 for ( index = context->nb_streams - 1;
2057 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
2059 mlt_properties_set_int( properties, "video_index", index );
2061 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
2063 // Invalidate the video stream
2065 mlt_properties_set_int( properties, "video_index", index );
2068 // Update the video properties if the index changed
2069 if ( index != self->video_index )
2071 // Reset the video properties if the index changed
2072 self->video_index = index;
2073 pthread_mutex_lock( &self->open_mutex );
2074 if ( self->video_codec )
2075 avcodec_close( self->video_codec );
2076 self->video_codec = NULL;
2077 pthread_mutex_unlock( &self->open_mutex );
2080 // Get the frame properties
2081 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2084 if ( context && index > -1 && video_codec_init( self, index, properties ) )
2086 // Set the frame properties
2087 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
2088 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
2089 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
2091 // Set the width and height
2092 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
2093 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
2094 // real_width and real_height are deprecated in favor of meta.media.width and .height
2095 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
2096 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
2097 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
2098 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
2099 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
2100 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
2102 // Workaround 1088 encodings missing cropping info.
2103 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
2105 mlt_properties_set_int( properties, "meta.media.height", 1080 );
2106 mlt_properties_set_int( frame_properties, "real_height", 1080 );
2109 // Add our image operation
2110 mlt_frame_push_service( frame, self );
2111 mlt_frame_push_get_image( frame, producer_get_image );
2115 // If something failed, use test card image
2116 mlt_properties_set_int( frame_properties, "test_image", 1 );
2120 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
2124 // Seek if necessary
2125 if ( self->seekable && position != self->audio_expected )
2127 if ( position + 1 == self->audio_expected )
2129 // We're paused - silence required
2132 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
2134 // Fast forward - seeking is inefficient for small distances - just ignore following frames
2135 *ignore = position - self->audio_expected;
2137 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
2139 AVFormatContext *context = self->audio_format;
2140 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
2141 if ( context->start_time != AV_NOPTS_VALUE )
2142 timestamp += context->start_time;
2143 if ( timestamp < 0 )
2146 // Set to the real timecode
2147 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
2150 // Clear the usage in the audio buffer
2151 int i = MAX_AUDIO_STREAMS + 1;
2153 self->audio_used[i - 1] = 0;
2159 static int sample_bytes( AVCodecContext *context )
2161 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2162 return av_get_bytes_per_sample( context->sample_fmt );
2163 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2164 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2166 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2170 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2172 // Fetch the audio_format
2173 AVFormatContext *context = self->audio_format;
2175 // Get the current stream index
2176 int index = pkt.stream_index;
2178 // Get codec context
2179 AVCodecContext *codec_context = self->audio_codec[ index ];
2181 // Obtain the resample context if it exists (not always needed)
2182 ReSampleContext *resample = self->audio_resample[ index ];
2184 // Obtain the audio buffers
2185 uint8_t *audio_buffer = self->audio_buffer[ index ];
2186 uint8_t *decode_buffer = self->decode_buffer[ index ];
2188 int audio_used = self->audio_used[ index ];
2189 uint8_t *ptr = pkt.data;
2193 while ( ptr && ret >= 0 && len > 0 )
2195 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2196 int data_size = self->audio_buffer_size[ index ];
2199 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2200 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2201 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2202 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2204 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2208 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2212 pkt.size = len -= ret;
2213 pkt.data = ptr += ret;
2215 // If decoded successfully
2216 if ( data_size > 0 )
2218 // Figure out how many samples will be needed after resampling
2219 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2220 int samples_needed = self->resample_factor * convert_samples;
2222 // Resize audio buffer to prevent overflow
2223 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2225 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2226 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2230 // Copy to audio buffer while resampling
2231 uint8_t *source = decode_buffer;
2232 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2233 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2237 // Straight copy to audio buffer
2238 memcpy( &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ], decode_buffer, data_size );
2239 audio_used += convert_samples;
2243 while ( *ignore && audio_used )
2246 audio_used -= audio_used > samples ? samples : audio_used;
2247 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2248 audio_used * sizeof_sample );
2253 // If we're behind, ignore this packet
2254 // Skip this on non-seekable, audio-only inputs.
2255 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2257 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
2258 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2259 int64_t int_position = ( int64_t )( current_pts * fps + 0.5 );
2260 if ( context->start_time != AV_NOPTS_VALUE )
2261 int_position -= ( int64_t )( fps * context->start_time / AV_TIME_BASE + 0.5 );
2263 if ( int_position > 0 )
2265 if ( int_position < req_position )
2266 // We are behind, so skip some
2267 *ignore = req_position - int_position;
2268 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2269 // We are ahead, so seek backwards some more
2270 seek_audio( self, req_position, timecode - 1.0, ignore );
2274 self->audio_used[ index ] = audio_used;
2279 /** Get the audio from a frame.
2281 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2284 producer_avformat self = mlt_frame_pop_audio( frame );
2286 pthread_mutex_lock( &self->audio_mutex );
2288 // Obtain the frame number of this frame
2289 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
2291 // Calculate the real time code
2292 double real_timecode = producer_time_of_frame( self->parent, position );
2294 // Get the producer fps
2295 double fps = mlt_producer_get_fps( self->parent );
2297 // Number of frames to ignore (for ffwd)
2298 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2300 // Flag for paused (silence)
2301 int paused = seek_audio( self, position, real_timecode, &ignore[0] );
2303 // Initialize ignore for all streams from the seek return value
2304 int i = MAX_AUDIO_STREAMS;
2306 ignore[i] = ignore[0];
2308 // Fetch the audio_format
2309 AVFormatContext *context = self->audio_format;
2311 int sizeof_sample = sizeof( int16_t );
2313 // Determine the tracks to use
2314 int index = self->audio_index;
2315 int index_max = self->audio_index + 1;
2316 if ( self->audio_index == INT_MAX )
2319 index_max = context->nb_streams;
2320 *channels = self->total_channels;
2321 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2322 *frequency = FFMAX( self->max_frequency, *frequency );
2325 // Initialize the resamplers and buffers
2326 for ( ; index < index_max; index++ )
2328 // Get codec context
2329 AVCodecContext *codec_context = self->audio_codec[ index ];
2331 if ( codec_context && !self->audio_buffer[ index ] )
2333 // Check for resample and create if necessary
2334 if ( codec_context->channels <= 2 )
2336 // Determine by how much resampling will increase number of samples
2337 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2338 resample_factor *= (double) *frequency / codec_context->sample_rate;
2339 if ( resample_factor > self->resample_factor )
2340 self->resample_factor = resample_factor;
2342 // Create the resampler
2343 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2344 self->audio_resample[ index ] = av_audio_resample_init(
2345 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2346 codec_context->channels, *frequency, codec_context->sample_rate,
2347 AV_SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2349 self->audio_resample[ index ] = audio_resample_init(
2350 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2351 codec_context->channels, *frequency, codec_context->sample_rate );
2356 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2357 sizeof_sample = sample_bytes( codec_context );
2360 // Check for audio buffer and create if necessary
2361 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2362 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2364 // Check for decoder buffer and create if necessary
2365 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2369 // Get the audio if required
2376 av_init_packet( &pkt );
2378 // If not resampling, give consumer more than requested.
2379 // It requested number samples based on requested frame rate.
2380 // Do not clean this up with a samples *= ...!
2381 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2382 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2384 while ( ret >= 0 && !got_audio )
2386 // Check if the buffer already contains the samples required
2387 if ( self->audio_index != INT_MAX &&
2388 self->audio_used[ self->audio_index ] >= *samples &&
2389 ignore[ self->audio_index ] == 0 )
2394 else if ( self->audio_index == INT_MAX )
2396 // Check if there is enough audio for all streams
2398 for ( index = 0; got_audio && index < context->nb_streams; index++ )
2399 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2406 pthread_mutex_lock( &self->packets_mutex );
2407 if ( mlt_deque_count( self->apackets ) )
2409 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2415 ret = av_read_frame( context, &pkt );
2416 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2418 if ( !av_dup_packet( &pkt ) )
2420 AVPacket *tmp = malloc( sizeof(AVPacket) );
2422 mlt_deque_push_back( self->vpackets, tmp );
2426 pthread_mutex_unlock( &self->packets_mutex );
2428 // We only deal with audio from the selected audio index
2429 index = pkt.stream_index;
2430 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2431 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2433 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2434 self->audio_codec[index]->channels : *channels;
2435 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2438 if ( self->seekable || index != self->video_index )
2439 av_free_packet( &pkt );
2443 // Set some additional return values
2444 *format = mlt_audio_s16;
2445 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2447 index = self->audio_index;
2448 *channels = self->audio_codec[ index ]->channels;
2449 *frequency = self->audio_codec[ index ]->sample_rate;
2450 *format = self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_S32 ? mlt_audio_s32le
2451 : self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_FLT ? mlt_audio_f32le
2453 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2455 else if ( self->audio_index == INT_MAX )
2457 // This only works if all audio tracks have the same sample format.
2458 for ( index = 0; index < index_max; index++ )
2459 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2461 *format = self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_S32 ? mlt_audio_s32le
2462 : self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_FLT ? mlt_audio_f32le
2464 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2469 // Allocate and set the frame's audio buffer
2470 int size = mlt_audio_format_size( *format, *samples, *channels );
2471 *buffer = mlt_pool_alloc( size );
2472 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2474 // Interleave tracks if audio_index=all
2475 if ( self->audio_index == INT_MAX )
2477 uint8_t *dest = *buffer;
2479 for ( i = 0; i < *samples; i++ )
2481 for ( index = 0; index < index_max; index++ )
2482 if ( self->audio_codec[ index ] )
2484 int current_channels = self->audio_codec[ index ]->channels;
2485 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2486 memcpy( dest, src, current_channels * sizeof_sample );
2487 dest += current_channels * sizeof_sample;
2490 for ( index = 0; index < index_max; index++ )
2491 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2493 int current_channels = self->audio_codec[ index ]->channels;
2494 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2495 self->audio_used[index] -= *samples;
2496 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2499 // Copy a single track to the output buffer
2502 index = self->audio_index;
2504 // Now handle the audio if we have enough
2505 if ( self->audio_used[ index ] > 0 )
2507 uint8_t *src = self->audio_buffer[ index ];
2508 // copy samples from audio_buffer
2509 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2510 memcpy( *buffer, src, size * *channels * sizeof_sample );
2511 // supply the remaining requested samples as silence
2512 if ( *samples > self->audio_used[ index ] )
2513 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2514 // reposition the samples within audio_buffer
2515 self->audio_used[ index ] -= size;
2516 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2520 // Otherwise fill with silence
2521 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2527 // Get silence and don't touch the context
2528 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2531 // Regardless of speed (other than paused), we expect to get the next frame
2533 self->audio_expected = position + 1;
2535 pthread_mutex_unlock( &self->audio_mutex );
2540 /** Initialize the audio codec context.
2543 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2545 // Initialise the codec if necessary
2546 if ( !self->audio_codec[ index ] )
2548 // Get codec context
2549 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2552 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2554 // If we don't have a codec and we can't initialise it, we can't do much more...
2555 pthread_mutex_lock( &self->open_mutex );
2556 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2557 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2559 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2562 // Now store the codec with its destructor
2563 if ( self->audio_codec[ index ] )
2564 avcodec_close( self->audio_codec[ index ] );
2565 self->audio_codec[ index ] = codec_context;
2569 // Remember that we can't use self later
2570 self->audio_index = -1;
2572 pthread_mutex_unlock( &self->open_mutex );
2574 // Process properties as AVOptions
2575 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2576 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
2577 if ( codec && codec->priv_class && codec_context->priv_data )
2578 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2581 return self->audio_codec[ index ] && self->audio_index > -1;
2584 /** Set up audio handling.
2587 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2590 mlt_producer producer = self->parent;
2592 // Get the properties
2593 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2595 // Fetch the audio format context
2596 AVFormatContext *context = self->audio_format;
2598 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2600 // Get the audio_index
2601 int index = mlt_properties_get_int( properties, "audio_index" );
2603 // Handle all audio tracks
2604 if ( self->audio_index > -1 &&
2605 mlt_properties_get( properties, "audio_index" ) &&
2606 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2609 // Reopen the file if necessary
2610 if ( !context && self->audio_index > -1 && index > -1 )
2612 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2613 mlt_properties_get( properties, "resource" ), 1 );
2614 context = self->audio_format;
2617 // Exception handling for audio_index
2618 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2620 for ( index = context->nb_streams - 1;
2621 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2623 mlt_properties_set_int( properties, "audio_index", index );
2625 if ( context && index > -1 && index < INT_MAX &&
2626 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2628 index = self->audio_index;
2629 mlt_properties_set_int( properties, "audio_index", index );
2632 // Update the audio properties if the index changed
2633 if ( context && index > -1 && index != self->audio_index )
2635 pthread_mutex_lock( &self->open_mutex );
2636 if ( self->audio_codec[ self->audio_index ] )
2637 avcodec_close( self->audio_codec[ self->audio_index ] );
2638 self->audio_codec[ self->audio_index ] = NULL;
2639 pthread_mutex_unlock( &self->open_mutex );
2641 if ( self->audio_index != -1 )
2642 self->audio_index = index;
2647 if ( context && index == INT_MAX )
2649 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2650 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2651 for ( index = 0; index < context->nb_streams; index++ )
2653 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2654 audio_codec_init( self, index, properties );
2657 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2659 // Set the frame properties
2660 if ( index < INT_MAX )
2662 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2663 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2666 if ( context && index > -1 )
2668 // Add our audio operation
2669 mlt_frame_push_audio( frame, self );
2670 mlt_frame_push_audio( frame, producer_get_audio );
2674 /** Our get frame implementation.
2677 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2679 // Access the private data
2680 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2681 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2682 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2687 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2688 producer->child = self;
2689 self->parent = producer;
2690 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2691 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2694 // Create an empty frame
2695 *frame = mlt_frame_init( service);
2699 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2703 mlt_cache_item_close( cache_item );
2707 // Update timecode on the frame we're creating
2708 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2711 producer_set_up_video( self, *frame );
2714 producer_set_up_audio( self, *frame );
2716 // Set the position of this producer
2717 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2718 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", position );
2720 // Calculate the next timecode
2721 mlt_producer_prepare_next( producer );
2726 static void producer_avformat_close( producer_avformat self )
2728 mlt_log_debug( NULL, "producer_avformat_close\n" );
2730 // Cleanup av contexts
2731 av_free( self->av_frame );
2732 pthread_mutex_lock( &self->open_mutex );
2734 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2736 if ( self->audio_resample[i] )
2737 audio_resample_close( self->audio_resample[i] );
2738 mlt_pool_release( self->audio_buffer[i] );
2739 av_free( self->decode_buffer[i] );
2740 if ( self->audio_codec[i] )
2741 avcodec_close( self->audio_codec[i] );
2742 self->audio_codec[i] = NULL;
2744 if ( self->video_codec )
2745 avcodec_close( self->video_codec );
2746 self->video_codec = NULL;
2748 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2749 if ( self->dummy_context )
2750 avformat_close_input( &self->dummy_context );
2751 if ( self->seekable && self->audio_format )
2752 avformat_close_input( &self->audio_format );
2753 if ( self->video_format )
2754 avformat_close_input( &self->video_format );
2756 if ( self->dummy_context )
2757 av_close_input_file( self->dummy_context );
2758 if ( self->seekable && self->audio_format )
2759 av_close_input_file( self->audio_format );
2760 if ( self->video_format )
2761 av_close_input_file( self->video_format );
2763 pthread_mutex_unlock( &self->open_mutex );
2765 vdpau_producer_close( self );
2767 if ( self->image_cache )
2768 mlt_cache_close( self->image_cache );
2769 if ( self->alpha_cache )
2770 mlt_cache_close( self->alpha_cache );
2772 // Cleanup the mutexes
2773 pthread_mutex_destroy( &self->audio_mutex );
2774 pthread_mutex_destroy( &self->video_mutex );
2775 pthread_mutex_destroy( &self->packets_mutex );
2776 pthread_mutex_destroy( &self->open_mutex );
2778 // Cleanup the packet queues
2780 if ( self->apackets )
2782 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2784 av_free_packet( pkt );
2787 mlt_deque_close( self->apackets );
2788 self->apackets = NULL;
2790 if ( self->vpackets )
2792 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2794 av_free_packet( pkt );
2797 mlt_deque_close( self->vpackets );
2798 self->vpackets = NULL;
2804 static void producer_close( mlt_producer parent )
2806 // Remove this instance from the cache
2807 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2810 parent->close = NULL;
2811 mlt_producer_close( parent );