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>
37 #if LIBAVCODEC_VERSION_MAJOR >= 53
38 #include <libavutil/samplefmt.h>
39 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
40 const char *avcodec_get_sample_fmt_name(int sample_fmt);
43 # include <libavcodec/vdpau.h>
45 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
46 # include <libavutil/pixdesc.h>
48 #if (LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0))
49 # include <libavutil/dict.h>
52 // System header files
58 #if LIBAVUTIL_VERSION_INT < (50<<16)
59 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
60 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
63 #if LIBAVCODEC_VERSION_MAJOR >= 53
64 #include <libavutil/opt.h>
65 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
66 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
67 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
69 #include <libavcodec/opt.h>
72 #define POSITION_INITIAL (-2)
73 #define POSITION_INVALID (-1)
75 #define MAX_AUDIO_STREAMS (10)
76 #define MAX_VDPAU_SURFACES (10)
78 struct producer_avformat_s
81 AVFormatContext *dummy_context;
82 AVFormatContext *audio_format;
83 AVFormatContext *video_format;
84 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
85 AVCodecContext *video_codec;
87 ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
88 mlt_position audio_expected;
89 mlt_position video_expected;
93 int64_t last_position;
95 int64_t current_position;
96 mlt_position nonseek_position;
99 uint8_t *audio_buffer[ MAX_AUDIO_STREAMS ];
100 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
101 uint8_t *decode_buffer[ MAX_AUDIO_STREAMS ];
102 int audio_used[ MAX_AUDIO_STREAMS ];
104 int audio_max_stream;
108 unsigned int invalid_pts_counter;
109 double resample_factor;
110 mlt_cache image_cache;
112 pthread_mutex_t video_mutex;
113 pthread_mutex_t audio_mutex;
116 pthread_mutex_t packets_mutex;
117 pthread_mutex_t open_mutex;
122 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
136 typedef struct producer_avformat_s *producer_avformat;
138 // Forward references.
139 static int list_components( char* file );
140 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock );
141 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
142 static void producer_avformat_close( producer_avformat );
143 static void producer_close( mlt_producer parent );
144 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
145 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
146 static void apply_properties( void *obj, mlt_properties properties, int flags );
147 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
148 static void get_audio_streams_info( producer_avformat self );
154 /** Constructor for libavformat.
157 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
159 if ( list_components( file ) )
162 mlt_producer producer = NULL;
164 // Check that we have a non-NULL argument
167 // Construct the producer
168 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
169 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
172 if ( mlt_producer_init( producer, self ) == 0 )
174 self->parent = producer;
176 // Get the properties
177 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
179 // Set the resource property (required for all producers)
180 mlt_properties_set( properties, "resource", file );
182 // Register transport implementation with the producer
183 producer->close = (mlt_destructor) producer_close;
185 // Register our get_frame implementation
186 producer->get_frame = producer_get_frame;
188 if ( strcmp( service, "avformat-novalidate" ) )
191 if ( producer_open( self, profile, file, 1 ) != 0 )
194 mlt_producer_close( producer );
197 else if ( self->seekable )
199 // Close the file to release resources for large playlists - reopen later as needed
200 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
201 if ( self->audio_format )
202 avformat_close_input( &self->audio_format );
203 if ( self->video_format )
204 avformat_close_input( &self->video_format );
206 if ( self->audio_format )
207 av_close_input_file( self->audio_format );
208 if ( self->video_format )
209 av_close_input_file( self->video_format );
211 self->audio_format = NULL;
212 self->video_format = NULL;
217 // Default the user-selectable indices from the auto-detected indices
218 mlt_properties_set_int( properties, "audio_index", self->audio_index );
219 mlt_properties_set_int( properties, "video_index", self->video_index );
221 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
223 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
230 int list_components( char* file )
234 // Report information about available demuxers and codecs as YAML Tiny
235 if ( file && strstr( file, "f-list" ) )
237 fprintf( stderr, "---\nformats:\n" );
238 AVInputFormat *format = NULL;
239 while ( ( format = av_iformat_next( format ) ) )
240 fprintf( stderr, " - %s\n", format->name );
241 fprintf( stderr, "...\n" );
244 if ( file && strstr( file, "acodec-list" ) )
246 fprintf( stderr, "---\naudio_codecs:\n" );
247 AVCodec *codec = NULL;
248 while ( ( codec = av_codec_next( codec ) ) )
249 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
250 fprintf( stderr, " - %s\n", codec->name );
251 fprintf( stderr, "...\n" );
254 if ( file && strstr( file, "vcodec-list" ) )
256 fprintf( stderr, "---\nvideo_codecs:\n" );
257 AVCodec *codec = NULL;
258 while ( ( codec = av_codec_next( codec ) ) )
259 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
260 fprintf( stderr, " - %s\n", codec->name );
261 fprintf( stderr, "...\n" );
268 /** Find the default streams.
271 static mlt_properties find_default_streams( producer_avformat self )
275 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
276 AVDictionaryEntry *tag = NULL;
278 AVMetadataTag *tag = NULL;
280 AVFormatContext *context = self->video_format;
281 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
283 // Default to the first audio and video streams found
284 self->audio_index = -1;
285 self->video_index = -1;
287 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
289 // Allow for multiple audio and video streams in the file and select first of each (if available)
290 for( i = 0; i < context->nb_streams; i++ )
292 // Get the codec context
293 AVStream *stream = context->streams[ i ];
294 if ( ! stream ) continue;
295 AVCodecContext *codec_context = stream->codec;
296 if ( ! codec_context ) continue;
297 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
298 if ( ! codec ) continue;
300 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
302 // Determine the type and obtain the first index of each type
303 switch( codec_context->codec_type )
305 case CODEC_TYPE_VIDEO:
306 // Use first video stream
307 if ( self->video_index < 0 )
308 self->video_index = i;
309 mlt_properties_set( meta_media, key, "video" );
310 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
311 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
312 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
313 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
314 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
315 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
317 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
320 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
321 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
322 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
324 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
325 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
326 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
327 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
328 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(3<<8)+0)
329 mlt_properties_set( meta_media, key, av_get_pix_fmt_name( codec_context->pix_fmt ) );
331 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
333 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
334 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
335 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
336 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
337 switch ( codec_context->colorspace )
339 case AVCOL_SPC_SMPTE240M:
340 mlt_properties_set_int( meta_media, key, 240 );
342 case AVCOL_SPC_BT470BG:
343 case AVCOL_SPC_SMPTE170M:
344 mlt_properties_set_int( meta_media, key, 601 );
346 case AVCOL_SPC_BT709:
347 mlt_properties_set_int( meta_media, key, 709 );
350 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
351 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
356 case CODEC_TYPE_AUDIO:
357 // Use first audio stream
358 if ( self->audio_index < 0 )
359 self->audio_index = i;
360 mlt_properties_set( meta_media, key, "audio" );
361 #if LIBAVCODEC_VERSION_MAJOR >= 53
362 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
363 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
364 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
365 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
366 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
368 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
369 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
370 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
371 mlt_properties_set_int( meta_media, key, codec_context->channels );
376 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
377 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
378 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
379 mlt_properties_set( meta_media, key, codec->name );
380 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
381 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
382 mlt_properties_set( meta_media, key, codec->long_name );
384 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
385 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
386 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
387 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
388 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
389 // mlt_properties_set_int( meta_media, key, codec_context->profile );
390 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
391 // mlt_properties_set_int( meta_media, key, codec_context->level );
394 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
395 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
396 while ( ( tag = av_dict_get( stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
398 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
401 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
403 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
404 mlt_properties_set( meta_media, key, tag->value );
409 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
410 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
411 while ( ( tag = av_dict_get( context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
413 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
416 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
418 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
419 mlt_properties_set( meta_media, key, tag->value );
423 if ( context->title && strcmp( context->title, "" ) )
424 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
425 if ( context->author && strcmp( context->author, "" ) )
426 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
427 if ( context->copyright && strcmp( context->copyright, "" ) )
428 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
429 if ( context->comment )
430 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
431 if ( context->album )
432 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
434 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
435 if ( context->track )
436 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
442 static inline int dv_is_pal( AVPacket *pkt )
444 return pkt->data[3] & 0x80;
447 static int dv_is_wide( AVPacket *pkt )
449 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
451 for ( ; i < pkt->size; i += 5 /* packet size */ )
453 if ( pkt->data[ i ] == 0x61 )
455 uint8_t x = pkt->data[ i + 2 ] & 0x7;
456 return ( x == 2 ) || ( x == 7 );
462 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
464 double aspect_ratio = 1.0;
466 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
470 if ( dv_is_pal( pkt ) )
472 if ( dv_is_wide( pkt ) )
474 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
475 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
479 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
480 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
485 if ( dv_is_wide( pkt ) )
487 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
488 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
492 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
493 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
500 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
501 stream->sample_aspect_ratio;
503 codec_context->sample_aspect_ratio;
505 // Override FFmpeg's notion of DV aspect ratios, which are
506 // based upon a width of 704. Since we do not have a normaliser
507 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
508 // we just coerce the values to facilitate a passive behaviour through
509 // the rescale normaliser when using equivalent producers and consumers.
510 // = display_aspect / (width * height)
511 if ( ar.num == 10 && ar.den == 11 )
514 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
515 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
517 else if ( ar.num == 59 && ar.den == 54 )
520 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
521 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
523 else if ( ar.num == 40 && ar.den == 33 )
526 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
527 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
529 else if ( ar.num == 118 && ar.den == 81 )
532 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
533 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
539 AVRational codec_sar = codec_context->sample_aspect_ratio;
540 AVRational stream_sar =
541 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
542 stream->sample_aspect_ratio;
546 if ( codec_sar.num > 0 )
548 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
549 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
551 else if ( stream_sar.num > 0 )
553 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
554 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
558 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
559 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
562 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
563 aspect_ratio = av_q2d( ar );
564 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
569 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
570 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVDictionary **params )
572 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
575 if ( !URL ) return NULL;
578 char *protocol = strdup( URL );
579 char *url = strchr( protocol, ':' );
581 // Only if there is not a protocol specification that avformat can handle
582 #if LIBAVFORMAT_VERSION_MAJOR >= 53
583 if ( url && avio_check( URL, 0 ) < 0 )
585 if ( url && !url_exist( URL ) )
588 // Truncate protocol string
590 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
593 *format = av_find_input_format( protocol );
595 // Eat the format designator
600 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
601 // support for legacy width and height parameters
605 // These are required by video4linux2 (defaults)
606 params->width = profile->width;
607 params->height = profile->height;
608 if ( !strstr( URL, "&frame_rate" ) )
609 params->time_base = (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
610 params->channels = 2;
611 params->sample_rate = 48000;
615 url = strchr( url, '?' );
619 char *name = strdup( ++url );
620 char *value = strchr( name, '=' );
622 // Also accept : as delimiter for backwards compatibility.
623 value = strchr( name, ':' );
628 char *t = strchr( value, '&' );
631 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
632 // translate old parameters to new av_dict names
633 if ( !strcmp( name, "frame_rate" ) )
634 av_dict_set( params, "framerate", value, 0 );
635 else if ( !strcmp( name, "pix_fmt" ) )
636 av_dict_set( params, "pixel_format", value, 0 );
637 else if ( !strcmp( name, "width" ) )
638 width = strdup( value );
639 else if ( !strcmp( name, "height" ) )
640 height = strdup( value );
642 // generic demux/device option support
643 av_dict_set( params, name, value, 0 );
645 if ( !strcmp( name, "frame_rate" ) )
646 params->time_base.den = atoi( value );
647 else if ( !strcmp( name, "frame_rate_base" ) )
648 params->time_base.num = atoi( value );
649 else if ( !strcmp( name, "sample_rate" ) )
650 params->sample_rate = atoi( value );
651 else if ( !strcmp( name, "channel" ) )
652 params->channel = atoi( value );
653 else if ( !strcmp( name, "channels" ) )
654 params->channels = atoi( value );
655 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
656 else if ( !strcmp( name, "pix_fmt" ) )
657 params->pix_fmt = av_get_pix_fmt( value );
659 else if ( !strcmp( name, "width" ) )
660 params->width = atoi( value );
661 else if ( !strcmp( name, "height" ) )
662 params->height = atoi( value );
663 else if ( !strcmp( name, "standard" ) )
664 params->standard = strdup( value );
668 url = strchr( url, '&' );
670 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
671 // continued support for legacy width and height parameters
672 if ( width && height )
674 char *s = malloc( strlen( width ) + strlen( height ) + 2 );
678 av_dict_set( params, "video_size", s, 0 );
681 if ( width ) free( width );
682 if ( height ) free ( height );
685 result = strdup( result );
689 result = strdup( URL );
695 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
699 // Get the properties
700 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
702 AVFormatContext *format = self->video_format;
704 // We will treat everything with the producer fps.
705 // TODO: make this more flexible.
706 double fps = mlt_profile_fps( profile );
709 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
711 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
712 // when producer_open is called after initial call when restoring or reseting the producer.
713 if ( format->duration != AV_NOPTS_VALUE )
715 // This isn't going to be accurate for all formats
716 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
717 mlt_properties_set_position( properties, "out", frames - 1 );
718 mlt_properties_set_position( properties, "length", frames );
719 mlt_properties_set_int( properties, "_length_computed", 1 );
723 // Set live sources to run forever
724 mlt_properties_set_position( properties, "length", INT_MAX );
725 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
726 mlt_properties_set( properties, "eof", "loop" );
727 mlt_properties_set_int( properties, "_length_computed", 1 );
731 // Check if we're seekable
732 // avdevices are typically AVFMT_NOFILE and not seekable
733 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
736 // protocols can indicate if they support seeking
737 #if LIBAVFORMAT_VERSION_MAJOR >= 53
738 self->seekable = format->pb->seekable;
740 URLContext *uc = url_fileno( format->pb );
742 self->seekable = !uc->is_streamed;
745 if ( self->seekable )
747 // Do a more rigourous test of seekable on a disposable context
748 self->seekable = av_seek_frame( format, -1, format->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
749 mlt_properties_set_int( properties, "seekable", self->seekable );
750 self->dummy_context = format;
751 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
752 self->video_format = NULL;
753 avformat_open_input( &self->video_format, filename, NULL, NULL );
754 avformat_find_stream_info( self->video_format, NULL );
756 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
757 av_find_stream_info( self->video_format );
759 format = self->video_format;
762 // Fetch the width, height and aspect ratio
763 if ( self->video_index != -1 )
765 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
766 mlt_properties_set_int( properties, "width", codec_context->width );
767 mlt_properties_set_int( properties, "height", codec_context->height );
769 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
771 // Fetch the first frame of DV so we can read it directly
776 ret = av_read_frame( format, &pkt );
777 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
779 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
786 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
790 // Verify that we can convert this to YUV 4:2:2
791 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
792 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
793 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
795 sws_freeContext( context );
806 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
808 // Return an error code (0 == no error)
810 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
815 pthread_mutex_init( &self->audio_mutex, NULL );
816 pthread_mutex_init( &self->video_mutex, NULL );
817 pthread_mutex_init( &self->packets_mutex, NULL );
818 pthread_mutex_init( &self->open_mutex, NULL );
819 pthread_mutex_lock( &self->audio_mutex );
820 pthread_mutex_lock( &self->video_mutex );
822 mlt_events_block( properties, self->parent );
825 AVInputFormat *format = NULL;
826 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
827 AVDictionary *params = NULL;
829 AVFormatParameters params;
830 memset( ¶ms, 0, sizeof(params) );
832 char *filename = parse_url( profile, URL, &format, ¶ms );
834 // Now attempt to open the file or device with filename
835 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
836 error = avformat_open_input( &self->video_format, filename, format, ¶ms ) < 0;
838 // If the URL is a network stream URL, then we probably need to open with full URL
839 error = avformat_open_input( &self->video_format, URL, format, ¶ms ) < 0;
841 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
843 // If the URL is a network stream URL, then we probably need to open with full URL
844 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
847 // Set MLT properties onto video AVFormatContext
848 if ( !error && self->video_format )
850 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
851 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
852 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
853 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
857 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
858 av_dict_free( ¶ms );
860 // Cleanup AVFormatParameters
861 if ( params.standard )
862 free( (void*) params.standard );
865 // If successful, then try to get additional info
866 if ( !error && self->video_format )
868 // Get the stream info
869 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
870 error = avformat_find_stream_info( self->video_format, NULL ) < 0;
872 error = av_find_stream_info( self->video_format ) < 0;
875 // Continue if no error
876 if ( !error && self->video_format )
878 // Find default audio and video streams
879 find_default_streams( self );
880 error = get_basic_info( self, profile, filename );
882 // Initialize position info
883 self->first_pts = -1;
884 self->last_position = POSITION_INITIAL;
886 if ( !self->audio_format )
888 // We're going to cheat here - for seekable A/V files, we will have separate contexts
889 // to support independent seeking of audio from video.
890 // TODO: Is this really necessary?
891 if ( self->audio_index != -1 && self->video_index != -1 )
893 if ( self->seekable )
895 // And open again for our audio context
896 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
897 avformat_open_input( &self->audio_format, filename, NULL, NULL );
898 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
899 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
900 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
901 avformat_find_stream_info( self->audio_format, NULL );
903 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
904 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
905 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
906 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
907 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
909 av_find_stream_info( self->audio_format );
914 self->audio_format = self->video_format;
917 else if ( self->audio_index != -1 )
919 // We only have an audio context
920 self->audio_format = self->video_format;
921 self->video_format = NULL;
923 else if ( self->video_index == -1 )
925 // Something has gone wrong
928 if ( self->audio_format && !self->audio_streams )
929 get_audio_streams_info( self );
937 self->apackets = mlt_deque_init();
938 self->vpackets = mlt_deque_init();
941 if ( self->dummy_context )
943 pthread_mutex_lock( &self->open_mutex );
944 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
945 avformat_close_input( &self->dummy_context );
947 av_close_input_file( self->dummy_context );
949 self->dummy_context = NULL;
950 pthread_mutex_unlock( &self->open_mutex );
953 // Unlock the service
956 pthread_mutex_unlock( &self->audio_mutex );
957 pthread_mutex_unlock( &self->video_mutex );
959 mlt_events_unblock( properties, self->parent );
964 static void reopen_video( producer_avformat self, mlt_producer producer )
966 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
967 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
968 pthread_mutex_lock( &self->audio_mutex );
969 pthread_mutex_lock( &self->open_mutex );
971 if ( self->video_codec )
972 avcodec_close( self->video_codec );
973 self->video_codec = NULL;
974 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
975 if ( self->dummy_context )
976 avformat_close_input( &self->dummy_context );
977 if ( self->video_format )
978 avformat_close_input( &self->video_format );
980 if ( self->dummy_context )
981 av_close_input_file( self->dummy_context );
982 if ( self->video_format )
983 av_close_input_file( self->video_format );
985 self->dummy_context = NULL;
986 self->video_format = NULL;
987 pthread_mutex_unlock( &self->open_mutex );
989 int audio_index = self->audio_index;
990 int video_index = self->video_index;
992 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
993 mlt_properties_get( properties, "resource" ), 0 );
995 self->audio_index = audio_index;
996 if ( self->video_format && video_index > -1 )
998 self->video_index = video_index;
999 video_codec_init( self, video_index, properties );
1002 pthread_mutex_unlock( &self->audio_mutex );
1003 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1006 static int seek_video( producer_avformat self, mlt_position position,
1007 int64_t req_position, int must_decode, int use_new_seek, int *ignore )
1009 mlt_producer producer = self->parent;
1012 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
1014 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1016 // Fetch the video format context
1017 AVFormatContext *context = self->video_format;
1019 // Get the video stream
1020 AVStream *stream = context->streams[ self->video_index ];
1022 // Get codec context
1023 AVCodecContext *codec_context = stream->codec;
1025 // We may want to use the source fps if available
1026 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1027 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1029 if ( self->av_frame && position + 1 == self->video_expected )
1031 // We're paused - use last image
1034 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
1036 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1037 *ignore = ( int )( ( position - self->video_expected ) / mlt_producer_get_fps( producer ) * source_fps );
1038 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1040 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
1042 if ( use_new_seek && self->last_position == POSITION_INITIAL )
1044 // find first key frame
1049 while ( ret >= 0 && toscan-- > 0 )
1051 ret = av_read_frame( context, &pkt );
1052 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
1054 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) );
1055 self->first_pts = pkt.pts;
1058 av_free_packet( &pkt );
1061 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1064 // Calculate the timestamp for the requested frame
1068 timestamp = ( req_position - 0.1 / source_fps ) /
1069 ( av_q2d( stream->time_base ) * source_fps );
1070 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pos %"PRId64" pts %"PRId64"\n", req_position, timestamp );
1071 if ( self->first_pts > 0 )
1072 timestamp += self->first_pts;
1073 else if ( context->start_time != AV_NOPTS_VALUE )
1074 timestamp += context->start_time;
1078 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
1079 if ( context->start_time != AV_NOPTS_VALUE )
1080 timestamp += context->start_time;
1083 timestamp -= AV_TIME_BASE;
1084 if ( timestamp < 0 )
1086 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
1087 timestamp, position, self->video_expected, self->last_position );
1089 // Seek to the timestamp
1092 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1093 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1095 else if ( req_position > 0 || self->last_position <= 0 )
1097 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
1101 // Re-open video stream when rewinding to beginning from somewhere else.
1102 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1103 // not reliably seeking to the first frame across formats.
1104 reopen_video( self, producer );
1107 // Remove the cached info relating to the previous position
1108 self->current_position = POSITION_INVALID;
1109 self->last_position = POSITION_INVALID;
1110 av_freep( &self->av_frame );
1114 // flush any pictures still in decode buffer
1115 avcodec_flush_buffers( codec_context );
1122 /** Convert a frame position to a time code.
1125 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1127 return ( double )position / mlt_producer_get_fps( producer );
1130 // Collect information about all audio streams
1132 static void get_audio_streams_info( producer_avformat self )
1134 // Fetch the audio format context
1135 AVFormatContext *context = self->audio_format;
1139 i < context->nb_streams;
1142 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1144 AVCodecContext *codec_context = context->streams[i]->codec;
1145 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1147 // If we don't have a codec and we can't initialise it, we can't do much more...
1148 pthread_mutex_lock( &self->open_mutex );
1149 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1150 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1152 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1155 self->audio_streams++;
1156 self->audio_max_stream = i;
1157 self->total_channels += codec_context->channels;
1158 if ( codec_context->channels > self->max_channel )
1159 self->max_channel = codec_context->channels;
1160 if ( codec_context->sample_rate > self->max_frequency )
1161 self->max_frequency = codec_context->sample_rate;
1162 avcodec_close( codec_context );
1164 pthread_mutex_unlock( &self->open_mutex );
1167 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1168 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1170 // Other audio-specific initializations
1171 self->resample_factor = 1.0;
1174 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1176 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1178 const int *new_coefficients;
1180 int brightness, contrast, saturation;
1182 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1183 &brightness, &contrast, &saturation ) != -1 )
1185 // Don't change these from defaults unless explicitly told to.
1186 if ( use_full_range >= 0 )
1187 full_range = use_full_range;
1188 switch ( colorspace )
1194 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1197 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1200 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1203 new_coefficients = coefficients;
1206 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1207 brightness, contrast, saturation );
1212 static mlt_image_format pick_format( enum PixelFormat pix_fmt )
1220 return mlt_image_rgb24a;
1221 case PIX_FMT_YUV420P:
1222 case PIX_FMT_YUVJ420P:
1223 case PIX_FMT_YUVA420P:
1224 return mlt_image_yuv420p;
1228 case PIX_FMT_MONOWHITE:
1229 case PIX_FMT_MONOBLACK:
1232 return mlt_image_rgb24;
1234 return mlt_image_yuv422;
1238 static void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
1239 mlt_image_format *format, int width, int height, int colorspace )
1242 int full_range = -1;
1243 int flags = SWS_BILINEAR | SWS_ACCURATE_RND;
1246 flags |= SWS_CPU_CAPS_MMX;
1249 flags |= SWS_CPU_CAPS_MMX2;
1252 if ( *format == mlt_image_yuv420p )
1254 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1255 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1257 output.data[0] = buffer;
1258 output.data[1] = buffer + width * height;
1259 output.data[2] = buffer + ( 5 * width * height ) / 4;
1260 output.linesize[0] = width;
1261 output.linesize[1] = width >> 1;
1262 output.linesize[2] = width >> 1;
1263 set_luma_transfer( context, colorspace, full_range );
1264 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1265 output.data, output.linesize);
1266 sws_freeContext( context );
1268 else if ( *format == mlt_image_rgb24 )
1270 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1271 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1273 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1274 set_luma_transfer( context, colorspace, full_range );
1275 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1276 output.data, output.linesize);
1277 sws_freeContext( context );
1279 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1281 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1282 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1284 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1285 set_luma_transfer( context, colorspace, full_range );
1286 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1287 output.data, output.linesize);
1288 sws_freeContext( context );
1292 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1293 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1295 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1296 set_luma_transfer( context, colorspace, full_range );
1297 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1298 output.data, output.linesize);
1299 sws_freeContext( context );
1302 if ( *format == mlt_image_yuv420p )
1305 pict.data[0] = buffer;
1306 pict.data[1] = buffer + width * height;
1307 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1308 pict.linesize[0] = width;
1309 pict.linesize[1] = width >> 1;
1310 pict.linesize[2] = width >> 1;
1311 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1313 else if ( *format == mlt_image_rgb24 )
1316 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1317 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1319 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
1322 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1323 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1328 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1329 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1334 /** Allocate the image buffer and set it on the frame.
1337 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1341 if ( codec_context->width == 0 || codec_context->height == 0 )
1343 *width = codec_context->width;
1344 *height = codec_context->height;
1345 size = mlt_image_format_size( *format, *width, *height, NULL );
1346 *buffer = mlt_pool_alloc( size );
1348 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1355 /** Get an image from a frame.
1358 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1361 producer_avformat self = mlt_frame_pop_service( frame );
1362 mlt_producer producer = self->parent;
1364 // Get the properties from the frame
1365 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1367 // Obtain the frame number of this frame
1368 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1370 // Get the producer properties
1371 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1373 pthread_mutex_lock( &self->video_mutex );
1375 // Fetch the video format context
1376 AVFormatContext *context = self->video_format;
1378 // Get the video stream
1379 AVStream *stream = context->streams[ self->video_index ];
1381 // Get codec context
1382 AVCodecContext *codec_context = stream->codec;
1384 // Get the image cache
1385 if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1386 self->image_cache = mlt_cache_init();
1387 if ( self->image_cache )
1389 mlt_cache_item item = mlt_cache_get( self->image_cache, (void*) position );
1390 uint8_t *original = mlt_cache_item_data( item, (int*) format );
1393 // Set the resolution
1394 *width = codec_context->width;
1395 *height = codec_context->height;
1397 // Workaround 1088 encodings missing cropping info.
1398 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1402 int size = mlt_image_format_size( *format, *width, *height, NULL );
1405 *buffer = mlt_pool_alloc( size );
1406 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1407 memcpy( *buffer, original, size );
1408 mlt_cache_item_close( item );
1413 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1414 mlt_frame_set_image( frame, *buffer, size, NULL );
1416 self->got_picture = 1;
1418 goto exit_get_image;
1427 // Special case ffwd handling
1430 // We may want to use the source fps if available
1431 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1432 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1434 // This is the physical frame position in the source
1435 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1437 // Determines if we have to decode all frames in a sequence
1438 // Temporary hack to improve intra frame only
1439 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1440 strcmp( codec_context->codec->name, "dnxhd" ) &&
1441 strcmp( codec_context->codec->name, "dvvideo" ) &&
1442 strcmp( codec_context->codec->name, "huffyuv" ) &&
1443 strcmp( codec_context->codec->name, "mjpeg" ) &&
1444 strcmp( codec_context->codec->name, "rawvideo" ) );
1446 // Turn on usage of new seek API and PTS for seeking
1447 int use_new_seek = self->seekable &&
1448 codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1449 if ( mlt_properties_get( properties, "new_seek" ) )
1450 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1451 double delay = mlt_properties_get_double( properties, "video_delay" );
1453 // Seek if necessary
1454 int paused = seek_video( self, position, req_position, must_decode, use_new_seek, &ignore );
1456 // Seek might have reopened the file
1457 context = self->video_format;
1458 stream = context->streams[ self->video_index ];
1459 codec_context = stream->codec;
1461 if ( *format == mlt_image_none ||
1462 codec_context->pix_fmt == PIX_FMT_ARGB ||
1463 codec_context->pix_fmt == PIX_FMT_RGBA ||
1464 codec_context->pix_fmt == PIX_FMT_ABGR ||
1465 codec_context->pix_fmt == PIX_FMT_BGRA )
1466 *format = pick_format( codec_context->pix_fmt );
1468 // Duplicate the last image if necessary
1469 if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture
1471 || self->current_position == req_position
1472 || ( !use_new_seek && self->current_position > req_position ) ) )
1475 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1477 // Workaround 1088 encodings missing cropping info.
1478 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1481 if ( self->vdpau && self->vdpau->buffer )
1484 picture.data[0] = self->vdpau->buffer;
1485 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1486 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1487 picture.linesize[0] = codec_context->width;
1488 picture.linesize[1] = codec_context->width / 2;
1489 picture.linesize[2] = codec_context->width / 2;
1490 convert_image( (AVFrame*) &picture, *buffer,
1491 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1495 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1496 format, *width, *height, self->colorspace );
1499 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1504 int64_t int_position = 0;
1505 int decode_errors = 0;
1506 int got_picture = 0;
1508 av_init_packet( &pkt );
1510 // Construct an AVFrame for YUV422 conversion
1511 if ( !self->av_frame )
1512 self->av_frame = avcodec_alloc_frame( );
1514 while( ret >= 0 && !got_picture )
1517 pthread_mutex_lock( &self->packets_mutex );
1518 if ( mlt_deque_count( self->vpackets ) )
1520 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1526 ret = av_read_frame( context, &pkt );
1527 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->audio_index )
1529 if ( !av_dup_packet( &pkt ) )
1531 AVPacket *tmp = malloc( sizeof(AVPacket) );
1533 mlt_deque_push_back( self->apackets, tmp );
1537 pthread_mutex_unlock( &self->packets_mutex );
1539 // We only deal with video from the selected video_index
1540 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1542 // Determine time code of the packet
1545 int64_t pts = pkt.pts;
1546 if ( self->first_pts > 0 )
1547 pts -= self->first_pts;
1548 else if ( context->start_time != AV_NOPTS_VALUE )
1549 pts -= context->start_time;
1550 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.1 );
1551 if ( pkt.pts == AV_NOPTS_VALUE )
1553 self->invalid_pts_counter++;
1554 if ( self->invalid_pts_counter > 20 )
1556 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1557 mlt_properties_set_int( properties, "new_seek", 0 );
1558 int_position = req_position;
1564 self->invalid_pts_counter = 0;
1566 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1567 pkt.pts, req_position, self->current_position, int_position );
1571 if ( pkt.dts != AV_NOPTS_VALUE )
1573 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pkt.dts + delay ) * source_fps + 0.5 );
1574 if ( context->start_time != AV_NOPTS_VALUE )
1575 int_position -= ( int64_t )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1576 if ( int_position == self->last_position )
1577 int_position = self->last_position + 1;
1579 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1580 pkt.dts, req_position, self->current_position, int_position );
1581 // Make a dumb assumption on streams that contain wild timestamps
1582 if ( abs( req_position - int_position ) > 999 )
1584 int_position = req_position;
1585 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1588 self->last_position = int_position;
1591 if ( must_decode || int_position >= req_position )
1596 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1598 vdpau_decoder_init( self );
1600 self->vdpau->is_decoded = 0;
1603 codec_context->reordered_opaque = pkt.pts;
1604 if ( int_position >= req_position )
1605 codec_context->skip_loop_filter = AVDISCARD_NONE;
1606 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1607 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1609 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1611 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1614 if ( ++decode_errors <= 10 )
1627 // Determine time code of the packet
1628 int64_t pts = self->av_frame->reordered_opaque;
1629 if ( self->first_pts > 0 )
1630 pts -= self->first_pts;
1631 else if ( context->start_time != AV_NOPTS_VALUE )
1632 pts -= context->start_time;
1633 int_position = ( int64_t )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1634 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %"PRId64", key %d\n", int_position, self->av_frame->key_frame );
1637 if ( int_position < req_position )
1642 else if ( int_position >= req_position )
1645 codec_context->skip_loop_filter = AVDISCARD_NONE;
1647 else if ( ignore -- )
1652 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1655 // Now handle the picture if we have one
1658 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1660 // Workaround 1088 encodings missing cropping info.
1661 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1666 if ( self->vdpau->is_decoded )
1668 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1670 uint32_t pitches[3];
1671 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1673 if ( !self->vdpau->buffer )
1674 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1675 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1676 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1677 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1678 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1679 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1680 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1682 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1683 if ( status == VDP_STATUS_OK )
1685 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1686 format, *width, *height, self->colorspace );
1690 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1691 image_size = self->vdpau->is_decoded = 0;
1696 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1697 image_size = got_picture = 0;
1702 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1703 format, *width, *height, self->colorspace );
1704 self->top_field_first |= self->av_frame->top_field_first;
1705 self->current_position = int_position;
1706 self->got_picture = 1;
1713 if ( self->seekable || pkt.stream_index != self->audio_index )
1714 av_free_packet( &pkt );
1718 if ( self->got_picture && image_size > 0 && self->image_cache )
1720 // Copy buffer to image cache
1721 uint8_t *image = mlt_pool_alloc( image_size );
1722 memcpy( image, *buffer, image_size );
1723 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1725 // Try to duplicate last image if there was a decoding failure
1726 else if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1729 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1731 // Workaround 1088 encodings missing cropping info.
1732 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1735 if ( self->vdpau && self->vdpau->buffer )
1738 picture.data[0] = self->vdpau->buffer;
1739 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1740 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1741 picture.linesize[0] = codec_context->width;
1742 picture.linesize[1] = codec_context->width / 2;
1743 picture.linesize[2] = codec_context->width / 2;
1744 convert_image( (AVFrame*) &picture, *buffer,
1745 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1749 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1750 format, *width, *height, self->colorspace );
1751 self->got_picture = 1;
1754 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1757 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1758 self->video_expected = position + 1;
1762 pthread_mutex_unlock( &self->video_mutex );
1764 // Set the progressive flag
1765 if ( mlt_properties_get( properties, "force_progressive" ) )
1766 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1767 else if ( self->av_frame )
1768 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1770 // Set the field order property for this frame
1771 if ( mlt_properties_get( properties, "force_tff" ) )
1772 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1774 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1776 // Set immutable properties of the selected track's (or overridden) source attributes.
1777 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1778 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1779 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1780 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1782 return !self->got_picture;
1785 /** Process properties as AVOptions and apply to AV context obj
1788 static void apply_properties( void *obj, mlt_properties properties, int flags )
1791 int count = mlt_properties_count( properties );
1792 for ( i = 0; i < count; i++ )
1794 const char *opt_name = mlt_properties_get_name( properties, i );
1795 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(7<<8)+0)
1796 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1798 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1800 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1803 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1804 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1805 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1806 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1807 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1808 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1810 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1816 /** Initialize the video codec context.
1819 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1821 // Initialise the codec if necessary
1822 if ( !self->video_codec )
1824 // Get the video stream
1825 AVStream *stream = self->video_format->streams[ index ];
1827 // Get codec context
1828 AVCodecContext *codec_context = stream->codec;
1831 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1833 if ( codec_context->codec_id == CODEC_ID_H264 )
1835 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1837 if ( vdpau_init( self ) )
1839 self->video_codec = codec_context;
1840 if ( !vdpau_decoder_init( self ) )
1845 codec = avcodec_find_decoder( codec_context->codec_id );
1849 // Initialise multi-threading
1850 int thread_count = mlt_properties_get_int( properties, "threads" );
1851 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1852 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1853 if ( thread_count > 1 )
1854 codec_context->thread_count = thread_count;
1856 // If we don't have a codec and we can't initialise it, we can't do much more...
1857 pthread_mutex_lock( &self->open_mutex );
1858 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1859 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1861 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1864 // Now store the codec with its destructor
1865 self->video_codec = codec_context;
1869 // Remember that we can't use this later
1870 self->video_index = -1;
1871 pthread_mutex_unlock( &self->open_mutex );
1874 pthread_mutex_unlock( &self->open_mutex );
1876 // Process properties as AVOptions
1877 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1878 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1879 if ( codec->priv_class && codec_context->priv_data )
1880 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1883 // Reset some image properties
1884 mlt_properties_set_int( properties, "width", self->video_codec->width );
1885 mlt_properties_set_int( properties, "height", self->video_codec->height );
1886 // For DV, we'll just use the saved aspect ratio
1887 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1888 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1890 // Determine the fps first from the codec
1891 double source_fps = (double) self->video_codec->time_base.den /
1892 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1894 if ( mlt_properties_get( properties, "force_fps" ) )
1896 source_fps = mlt_properties_get_double( properties, "force_fps" );
1897 stream->time_base = av_d2q( source_fps, 1024 );
1898 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1899 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1903 // If the muxer reports a frame rate different than the codec
1904 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1905 double muxer_fps = av_q2d( stream->avg_frame_rate );
1906 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1907 muxer_fps = av_q2d( stream->r_frame_rate );
1909 double muxer_fps = av_q2d( stream->r_frame_rate );
1911 // Choose the lesser - the wrong tends to be off by some multiple of 10
1912 source_fps = FFMIN( source_fps, muxer_fps );
1913 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1915 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1916 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1918 else if ( muxer_fps > 0 )
1920 AVRational frame_rate = stream->r_frame_rate;
1921 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1922 // avg_frame_rate gives some approximate value that does not well match the media.
1923 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1924 // results in some very choppy output, but some value slightly different works
1926 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1927 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1928 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1930 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1931 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1932 source_fps = av_q2d( frame_rate );
1936 source_fps = mlt_producer_get_fps( self->parent );
1937 AVRational frame_rate = av_d2q( source_fps, 255 );
1938 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1939 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1943 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1944 if ( source_fps > 0 )
1945 mlt_properties_set_double( properties, "source_fps", source_fps );
1947 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
1949 // Set the YUV colorspace from override or detect
1950 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1951 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1952 if ( ! self->colorspace )
1954 switch ( self->video_codec->colorspace )
1956 case AVCOL_SPC_SMPTE240M:
1957 self->colorspace = 240;
1959 case AVCOL_SPC_BT470BG:
1960 case AVCOL_SPC_SMPTE170M:
1961 self->colorspace = 601;
1963 case AVCOL_SPC_BT709:
1964 self->colorspace = 709;
1967 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1968 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1973 // Let apps get chosen colorspace
1974 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1976 return self->video_codec && self->video_index > -1;
1979 /** Set up video handling.
1982 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1985 mlt_producer producer = self->parent;
1987 // Get the properties
1988 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1990 // Fetch the video format context
1991 AVFormatContext *context = self->video_format;
1993 // Get the video_index
1994 int index = mlt_properties_get_int( properties, "video_index" );
1996 // Reopen the file if necessary
1997 if ( !context && index > -1 )
1999 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2000 mlt_properties_get( properties, "resource" ), 1 );
2001 context = self->video_format;
2004 // Exception handling for video_index
2005 if ( context && index >= (int) context->nb_streams )
2007 // Get the last video stream
2008 for ( index = context->nb_streams - 1;
2009 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
2011 mlt_properties_set_int( properties, "video_index", index );
2013 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
2015 // Invalidate the video stream
2017 mlt_properties_set_int( properties, "video_index", index );
2020 // Update the video properties if the index changed
2021 if ( index != self->video_index )
2023 // Reset the video properties if the index changed
2024 self->video_index = index;
2025 pthread_mutex_lock( &self->open_mutex );
2026 if ( self->video_codec )
2027 avcodec_close( self->video_codec );
2028 self->video_codec = NULL;
2029 pthread_mutex_unlock( &self->open_mutex );
2032 // Get the frame properties
2033 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2036 if ( context && index > -1 && video_codec_init( self, index, properties ) )
2038 // Set the frame properties
2039 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
2040 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
2041 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
2043 // Set the width and height
2044 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
2045 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
2046 // real_width and real_height are deprecated in favor of meta.media.width and .height
2047 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
2048 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
2049 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
2050 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
2051 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
2052 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
2054 // Workaround 1088 encodings missing cropping info.
2055 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
2057 mlt_properties_set_int( properties, "meta.media.height", 1080 );
2058 mlt_properties_set_int( frame_properties, "real_height", 1080 );
2061 // Add our image operation
2062 mlt_frame_push_service( frame, self );
2063 mlt_frame_push_get_image( frame, producer_get_image );
2067 // If something failed, use test card image
2068 mlt_properties_set_int( frame_properties, "test_image", 1 );
2072 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
2076 // Seek if necessary
2077 if ( self->seekable && position != self->audio_expected )
2079 if ( position + 1 == self->audio_expected )
2081 // We're paused - silence required
2084 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
2086 // Fast forward - seeking is inefficient for small distances - just ignore following frames
2087 *ignore = position - self->audio_expected;
2089 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
2091 AVFormatContext *context = self->audio_format;
2092 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
2093 if ( context->start_time != AV_NOPTS_VALUE )
2094 timestamp += context->start_time;
2095 if ( timestamp < 0 )
2098 // Set to the real timecode
2099 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
2102 // Clear the usage in the audio buffer
2103 int i = MAX_AUDIO_STREAMS + 1;
2105 self->audio_used[i - 1] = 0;
2111 static int sample_bytes( AVCodecContext *context )
2113 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2114 return av_get_bytes_per_sample( context->sample_fmt );
2115 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2116 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2118 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2122 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2124 // Fetch the audio_format
2125 AVFormatContext *context = self->audio_format;
2127 // Get the current stream index
2128 int index = pkt.stream_index;
2130 // Get codec context
2131 AVCodecContext *codec_context = self->audio_codec[ index ];
2133 // Obtain the resample context if it exists (not always needed)
2134 ReSampleContext *resample = self->audio_resample[ index ];
2136 // Obtain the audio buffers
2137 uint8_t *audio_buffer = self->audio_buffer[ index ];
2138 uint8_t *decode_buffer = self->decode_buffer[ index ];
2140 int audio_used = self->audio_used[ index ];
2141 uint8_t *ptr = pkt.data;
2145 while ( ptr && ret >= 0 && len > 0 )
2147 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2148 int data_size = self->audio_buffer_size[ index ];
2151 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2152 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2153 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2154 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2156 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2160 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2164 pkt.size = len -= ret;
2165 pkt.data = ptr += ret;
2167 // If decoded successfully
2168 if ( data_size > 0 )
2170 // Figure out how many samples will be needed after resampling
2171 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2172 int samples_needed = self->resample_factor * convert_samples;
2174 // Resize audio buffer to prevent overflow
2175 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2177 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2178 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2182 // Copy to audio buffer while resampling
2183 uint8_t *source = decode_buffer;
2184 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2185 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2189 // Straight copy to audio buffer
2190 memcpy( &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ], decode_buffer, data_size );
2191 audio_used += convert_samples;
2195 while ( *ignore && audio_used )
2198 audio_used -= audio_used > samples ? samples : audio_used;
2199 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2200 audio_used * sizeof_sample );
2205 // If we're behind, ignore this packet
2206 // Skip this on non-seekable, audio-only inputs.
2207 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2209 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
2210 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2211 int64_t int_position = ( int64_t )( current_pts * fps + 0.5 );
2212 if ( context->start_time != AV_NOPTS_VALUE )
2213 int_position -= ( int64_t )( fps * context->start_time / AV_TIME_BASE + 0.5 );
2215 if ( int_position > 0 )
2217 if ( int_position < req_position )
2218 // We are behind, so skip some
2219 *ignore = req_position - int_position;
2220 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2221 // We are ahead, so seek backwards some more
2222 seek_audio( self, req_position, timecode - 1.0, ignore );
2226 self->audio_used[ index ] = audio_used;
2231 /** Get the audio from a frame.
2233 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2236 producer_avformat self = mlt_frame_pop_audio( frame );
2238 pthread_mutex_lock( &self->audio_mutex );
2240 // Obtain the frame number of this frame
2241 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
2243 // Calculate the real time code
2244 double real_timecode = producer_time_of_frame( self->parent, position );
2246 // Get the producer fps
2247 double fps = mlt_producer_get_fps( self->parent );
2249 // Number of frames to ignore (for ffwd)
2250 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2252 // Flag for paused (silence)
2253 int paused = seek_audio( self, position, real_timecode, &ignore[0] );
2255 // Initialize ignore for all streams from the seek return value
2256 int i = MAX_AUDIO_STREAMS;
2258 ignore[i] = ignore[0];
2260 // Fetch the audio_format
2261 AVFormatContext *context = self->audio_format;
2263 int sizeof_sample = sizeof( int16_t );
2265 // Determine the tracks to use
2266 int index = self->audio_index;
2267 int index_max = self->audio_index + 1;
2268 if ( self->audio_index == INT_MAX )
2271 index_max = context->nb_streams;
2272 *channels = self->total_channels;
2273 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2274 *frequency = FFMAX( self->max_frequency, *frequency );
2277 // Initialize the resamplers and buffers
2278 for ( ; index < index_max; index++ )
2280 // Get codec context
2281 AVCodecContext *codec_context = self->audio_codec[ index ];
2283 if ( codec_context && !self->audio_buffer[ index ] )
2285 // Check for resample and create if necessary
2286 if ( codec_context->channels <= 2 )
2288 // Determine by how much resampling will increase number of samples
2289 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2290 resample_factor *= (double) *frequency / codec_context->sample_rate;
2291 if ( resample_factor > self->resample_factor )
2292 self->resample_factor = resample_factor;
2294 // Create the resampler
2295 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2296 self->audio_resample[ index ] = av_audio_resample_init(
2297 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2298 codec_context->channels, *frequency, codec_context->sample_rate,
2299 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2301 self->audio_resample[ index ] = audio_resample_init(
2302 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2303 codec_context->channels, *frequency, codec_context->sample_rate );
2308 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2309 sizeof_sample = sample_bytes( codec_context );
2312 // Check for audio buffer and create if necessary
2313 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2314 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2316 // Check for decoder buffer and create if necessary
2317 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2321 // Get the audio if required
2328 av_init_packet( &pkt );
2330 // If not resampling, give consumer more than requested.
2331 // It requested number samples based on requested frame rate.
2332 // Do not clean this up with a samples *= ...!
2333 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2334 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2336 while ( ret >= 0 && !got_audio )
2338 // Check if the buffer already contains the samples required
2339 if ( self->audio_index != INT_MAX &&
2340 self->audio_used[ self->audio_index ] >= *samples &&
2341 ignore[ self->audio_index ] == 0 )
2346 else if ( self->audio_index == INT_MAX )
2348 // Check if there is enough audio for all streams
2350 for ( index = 0; got_audio && index < context->nb_streams; index++ )
2351 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2358 pthread_mutex_lock( &self->packets_mutex );
2359 if ( mlt_deque_count( self->apackets ) )
2361 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2367 ret = av_read_frame( context, &pkt );
2368 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2370 if ( !av_dup_packet( &pkt ) )
2372 AVPacket *tmp = malloc( sizeof(AVPacket) );
2374 mlt_deque_push_back( self->vpackets, tmp );
2378 pthread_mutex_unlock( &self->packets_mutex );
2380 // We only deal with audio from the selected audio index
2381 index = pkt.stream_index;
2382 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2383 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2385 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2386 self->audio_codec[index]->channels : *channels;
2387 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2390 if ( self->seekable || index != self->video_index )
2391 av_free_packet( &pkt );
2395 // Set some additional return values
2396 *format = mlt_audio_s16;
2397 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2399 index = self->audio_index;
2400 *channels = self->audio_codec[ index ]->channels;
2401 *frequency = self->audio_codec[ index ]->sample_rate;
2402 *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2403 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2405 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2407 else if ( self->audio_index == INT_MAX )
2409 // This only works if all audio tracks have the same sample format.
2410 for ( index = 0; index < index_max; index++ )
2411 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2413 *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2414 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2416 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2421 // Allocate and set the frame's audio buffer
2422 int size = mlt_audio_format_size( *format, *samples, *channels );
2423 *buffer = mlt_pool_alloc( size );
2424 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2426 // Interleave tracks if audio_index=all
2427 if ( self->audio_index == INT_MAX )
2429 uint8_t *dest = *buffer;
2431 for ( i = 0; i < *samples; i++ )
2433 for ( index = 0; index < index_max; index++ )
2434 if ( self->audio_codec[ index ] )
2436 int current_channels = self->audio_codec[ index ]->channels;
2437 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2438 memcpy( dest, src, current_channels * sizeof_sample );
2439 dest += current_channels * sizeof_sample;
2442 for ( index = 0; index < index_max; index++ )
2443 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2445 int current_channels = self->audio_codec[ index ]->channels;
2446 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2447 self->audio_used[index] -= *samples;
2448 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2451 // Copy a single track to the output buffer
2454 index = self->audio_index;
2456 // Now handle the audio if we have enough
2457 if ( self->audio_used[ index ] > 0 )
2459 uint8_t *src = self->audio_buffer[ index ];
2460 // copy samples from audio_buffer
2461 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2462 memcpy( *buffer, src, size * *channels * sizeof_sample );
2463 // supply the remaining requested samples as silence
2464 if ( *samples > self->audio_used[ index ] )
2465 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2466 // reposition the samples within audio_buffer
2467 self->audio_used[ index ] -= size;
2468 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2472 // Otherwise fill with silence
2473 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2479 // Get silence and don't touch the context
2480 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2483 // Regardless of speed (other than paused), we expect to get the next frame
2485 self->audio_expected = position + 1;
2487 pthread_mutex_unlock( &self->audio_mutex );
2492 /** Initialize the audio codec context.
2495 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2497 // Initialise the codec if necessary
2498 if ( !self->audio_codec[ index ] )
2500 // Get codec context
2501 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2504 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2506 // If we don't have a codec and we can't initialise it, we can't do much more...
2507 pthread_mutex_lock( &self->open_mutex );
2508 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2509 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2511 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2514 // Now store the codec with its destructor
2515 if ( self->audio_codec[ index ] )
2516 avcodec_close( self->audio_codec[ index ] );
2517 self->audio_codec[ index ] = codec_context;
2521 // Remember that we can't use self later
2522 self->audio_index = -1;
2524 pthread_mutex_unlock( &self->open_mutex );
2526 // Process properties as AVOptions
2527 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2528 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
2529 if ( codec && codec->priv_class && codec_context->priv_data )
2530 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2533 return self->audio_codec[ index ] && self->audio_index > -1;
2536 /** Set up audio handling.
2539 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2542 mlt_producer producer = self->parent;
2544 // Get the properties
2545 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2547 // Fetch the audio format context
2548 AVFormatContext *context = self->audio_format;
2550 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2552 // Get the audio_index
2553 int index = mlt_properties_get_int( properties, "audio_index" );
2555 // Handle all audio tracks
2556 if ( self->audio_index > -1 &&
2557 mlt_properties_get( properties, "audio_index" ) &&
2558 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2561 // Reopen the file if necessary
2562 if ( !context && self->audio_index > -1 && index > -1 )
2564 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2565 mlt_properties_get( properties, "resource" ), 1 );
2566 context = self->audio_format;
2569 // Exception handling for audio_index
2570 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2572 for ( index = context->nb_streams - 1;
2573 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2575 mlt_properties_set_int( properties, "audio_index", index );
2577 if ( context && index > -1 && index < INT_MAX &&
2578 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2580 index = self->audio_index;
2581 mlt_properties_set_int( properties, "audio_index", index );
2584 // Update the audio properties if the index changed
2585 if ( context && index > -1 && index != self->audio_index )
2587 pthread_mutex_lock( &self->open_mutex );
2588 if ( self->audio_codec[ self->audio_index ] )
2589 avcodec_close( self->audio_codec[ self->audio_index ] );
2590 self->audio_codec[ self->audio_index ] = NULL;
2591 pthread_mutex_unlock( &self->open_mutex );
2593 if ( self->audio_index != -1 )
2594 self->audio_index = index;
2599 if ( context && index == INT_MAX )
2601 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2602 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2603 for ( index = 0; index < context->nb_streams; index++ )
2605 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2606 audio_codec_init( self, index, properties );
2609 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2611 // Set the frame properties
2612 if ( index < INT_MAX )
2614 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2615 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2618 if ( context && index > -1 )
2620 // Add our audio operation
2621 mlt_frame_push_audio( frame, self );
2622 mlt_frame_push_audio( frame, producer_get_audio );
2626 /** Our get frame implementation.
2629 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2631 // Access the private data
2632 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2633 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2634 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2639 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2640 producer->child = self;
2641 self->parent = producer;
2642 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2643 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2646 // Create an empty frame
2647 *frame = mlt_frame_init( service);
2651 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2655 mlt_cache_item_close( cache_item );
2659 // Update timecode on the frame we're creating
2660 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2663 producer_set_up_video( self, *frame );
2666 producer_set_up_audio( self, *frame );
2668 // Set the position of this producer
2669 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2670 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", position );
2672 // Calculate the next timecode
2673 mlt_producer_prepare_next( producer );
2678 static void producer_avformat_close( producer_avformat self )
2680 mlt_log_debug( NULL, "producer_avformat_close\n" );
2682 // Cleanup av contexts
2683 av_free( self->av_frame );
2684 pthread_mutex_lock( &self->open_mutex );
2686 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2688 if ( self->audio_resample[i] )
2689 audio_resample_close( self->audio_resample[i] );
2690 mlt_pool_release( self->audio_buffer[i] );
2691 av_free( self->decode_buffer[i] );
2692 if ( self->audio_codec[i] )
2693 avcodec_close( self->audio_codec[i] );
2694 self->audio_codec[i] = NULL;
2696 if ( self->video_codec )
2697 avcodec_close( self->video_codec );
2698 self->video_codec = NULL;
2700 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2701 if ( self->dummy_context )
2702 avformat_close_input( &self->dummy_context );
2703 if ( self->seekable && self->audio_format )
2704 avformat_close_input( &self->audio_format );
2705 if ( self->video_format )
2706 avformat_close_input( &self->video_format );
2708 if ( self->dummy_context )
2709 av_close_input_file( self->dummy_context );
2710 if ( self->seekable && self->audio_format )
2711 av_close_input_file( self->audio_format );
2712 if ( self->video_format )
2713 av_close_input_file( self->video_format );
2715 pthread_mutex_unlock( &self->open_mutex );
2717 vdpau_producer_close( self );
2719 if ( self->image_cache )
2720 mlt_cache_close( self->image_cache );
2722 // Cleanup the mutexes
2723 pthread_mutex_destroy( &self->audio_mutex );
2724 pthread_mutex_destroy( &self->video_mutex );
2725 pthread_mutex_destroy( &self->packets_mutex );
2726 pthread_mutex_destroy( &self->open_mutex );
2728 // Cleanup the packet queues
2730 if ( self->apackets )
2732 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2734 av_free_packet( pkt );
2737 mlt_deque_close( self->apackets );
2738 self->apackets = NULL;
2740 if ( self->vpackets )
2742 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2744 av_free_packet( pkt );
2747 mlt_deque_close( self->vpackets );
2748 self->vpackets = NULL;
2754 static void producer_close( mlt_producer parent )
2756 // Remove this instance from the cache
2757 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2760 parent->close = NULL;
2761 mlt_producer_close( parent );