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;
119 pthread_mutex_t video_mutex;
120 pthread_mutex_t audio_mutex;
123 pthread_mutex_t packets_mutex;
124 pthread_mutex_t open_mutex;
129 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
143 typedef struct producer_avformat_s *producer_avformat;
145 // Forward references.
146 static int list_components( char* file );
147 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock );
148 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
149 static void producer_avformat_close( producer_avformat );
150 static void producer_close( mlt_producer parent );
151 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
152 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
153 static void apply_properties( void *obj, mlt_properties properties, int flags );
154 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
155 static void get_audio_streams_info( producer_avformat self );
161 /** Constructor for libavformat.
164 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
166 if ( list_components( file ) )
169 mlt_producer producer = NULL;
171 // Check that we have a non-NULL argument
174 // Construct the producer
175 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
176 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
179 if ( mlt_producer_init( producer, self ) == 0 )
181 self->parent = producer;
183 // Get the properties
184 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
186 // Set the resource property (required for all producers)
187 mlt_properties_set( properties, "resource", file );
189 // Register transport implementation with the producer
190 producer->close = (mlt_destructor) producer_close;
192 // Register our get_frame implementation
193 producer->get_frame = producer_get_frame;
195 if ( strcmp( service, "avformat-novalidate" ) )
198 if ( producer_open( self, profile, file, 1 ) != 0 )
201 mlt_producer_close( producer );
204 else if ( self->seekable )
206 // Close the file to release resources for large playlists - reopen later as needed
207 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
208 if ( self->audio_format )
209 avformat_close_input( &self->audio_format );
210 if ( self->video_format )
211 avformat_close_input( &self->video_format );
213 if ( self->audio_format )
214 av_close_input_file( self->audio_format );
215 if ( self->video_format )
216 av_close_input_file( self->video_format );
218 self->audio_format = NULL;
219 self->video_format = NULL;
224 // Default the user-selectable indices from the auto-detected indices
225 mlt_properties_set_int( properties, "audio_index", self->audio_index );
226 mlt_properties_set_int( properties, "video_index", self->video_index );
228 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
230 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
237 int list_components( char* file )
241 // Report information about available demuxers and codecs as YAML Tiny
242 if ( file && strstr( file, "f-list" ) )
244 fprintf( stderr, "---\nformats:\n" );
245 AVInputFormat *format = NULL;
246 while ( ( format = av_iformat_next( format ) ) )
247 fprintf( stderr, " - %s\n", format->name );
248 fprintf( stderr, "...\n" );
251 if ( file && strstr( file, "acodec-list" ) )
253 fprintf( stderr, "---\naudio_codecs:\n" );
254 AVCodec *codec = NULL;
255 while ( ( codec = av_codec_next( codec ) ) )
256 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
257 fprintf( stderr, " - %s\n", codec->name );
258 fprintf( stderr, "...\n" );
261 if ( file && strstr( file, "vcodec-list" ) )
263 fprintf( stderr, "---\nvideo_codecs:\n" );
264 AVCodec *codec = NULL;
265 while ( ( codec = av_codec_next( codec ) ) )
266 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
267 fprintf( stderr, " - %s\n", codec->name );
268 fprintf( stderr, "...\n" );
275 /** Find the default streams.
278 static mlt_properties find_default_streams( producer_avformat self )
282 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
283 AVDictionaryEntry *tag = NULL;
285 AVMetadataTag *tag = NULL;
287 AVFormatContext *context = self->video_format;
288 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
290 // Default to the first audio and video streams found
291 self->audio_index = -1;
292 self->video_index = -1;
294 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
296 // Allow for multiple audio and video streams in the file and select first of each (if available)
297 for( i = 0; i < context->nb_streams; i++ )
299 // Get the codec context
300 AVStream *stream = context->streams[ i ];
301 if ( ! stream ) continue;
302 AVCodecContext *codec_context = stream->codec;
303 if ( ! codec_context ) continue;
304 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
305 if ( ! codec ) continue;
307 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
309 // Determine the type and obtain the first index of each type
310 switch( codec_context->codec_type )
312 case CODEC_TYPE_VIDEO:
313 // Use first video stream
314 if ( self->video_index < 0 )
315 self->video_index = i;
316 mlt_properties_set( meta_media, key, "video" );
317 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
318 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
319 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
320 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
321 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
322 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
324 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
327 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
328 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
329 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
331 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
332 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
333 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
334 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
335 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(3<<8)+0)
336 mlt_properties_set( meta_media, key, av_get_pix_fmt_name( codec_context->pix_fmt ) );
338 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
340 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
341 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
342 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
343 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
344 switch ( codec_context->colorspace )
346 case AVCOL_SPC_SMPTE240M:
347 mlt_properties_set_int( meta_media, key, 240 );
349 case AVCOL_SPC_BT470BG:
350 case AVCOL_SPC_SMPTE170M:
351 mlt_properties_set_int( meta_media, key, 601 );
353 case AVCOL_SPC_BT709:
354 mlt_properties_set_int( meta_media, key, 709 );
357 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
358 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
363 case CODEC_TYPE_AUDIO:
364 // Use first audio stream
365 if ( self->audio_index < 0 )
366 self->audio_index = i;
367 mlt_properties_set( meta_media, key, "audio" );
368 #if LIBAVCODEC_VERSION_MAJOR >= 53
369 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
370 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
371 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
372 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
373 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
375 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
376 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
377 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
378 mlt_properties_set_int( meta_media, key, codec_context->channels );
383 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
384 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
385 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
386 mlt_properties_set( meta_media, key, codec->name );
387 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
388 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
389 mlt_properties_set( meta_media, key, codec->long_name );
391 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
392 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
393 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
394 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
395 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
396 // mlt_properties_set_int( meta_media, key, codec_context->profile );
397 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
398 // mlt_properties_set_int( meta_media, key, codec_context->level );
401 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
402 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
403 while ( ( tag = av_dict_get( stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
405 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
408 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
410 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
411 mlt_properties_set( meta_media, key, tag->value );
416 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
417 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
418 while ( ( tag = av_dict_get( context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
420 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
423 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
425 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
426 mlt_properties_set( meta_media, key, tag->value );
430 if ( context->title && strcmp( context->title, "" ) )
431 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
432 if ( context->author && strcmp( context->author, "" ) )
433 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
434 if ( context->copyright && strcmp( context->copyright, "" ) )
435 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
436 if ( context->comment )
437 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
438 if ( context->album )
439 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
441 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
442 if ( context->track )
443 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
449 static inline int dv_is_pal( AVPacket *pkt )
451 return pkt->data[3] & 0x80;
454 static int dv_is_wide( AVPacket *pkt )
456 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
458 for ( ; i < pkt->size; i += 5 /* packet size */ )
460 if ( pkt->data[ i ] == 0x61 )
462 uint8_t x = pkt->data[ i + 2 ] & 0x7;
463 return ( x == 2 ) || ( x == 7 );
469 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
471 double aspect_ratio = 1.0;
473 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
477 if ( dv_is_pal( pkt ) )
479 if ( dv_is_wide( pkt ) )
481 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
482 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
486 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
487 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
492 if ( dv_is_wide( pkt ) )
494 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
495 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
499 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
500 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
507 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
508 stream->sample_aspect_ratio;
510 codec_context->sample_aspect_ratio;
512 // Override FFmpeg's notion of DV aspect ratios, which are
513 // based upon a width of 704. Since we do not have a normaliser
514 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
515 // we just coerce the values to facilitate a passive behaviour through
516 // the rescale normaliser when using equivalent producers and consumers.
517 // = display_aspect / (width * height)
518 if ( ar.num == 10 && ar.den == 11 )
521 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
522 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
524 else if ( ar.num == 59 && ar.den == 54 )
527 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
528 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
530 else if ( ar.num == 40 && ar.den == 33 )
533 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
534 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
536 else if ( ar.num == 118 && ar.den == 81 )
539 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
540 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
546 AVRational codec_sar = codec_context->sample_aspect_ratio;
547 AVRational stream_sar =
548 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
549 stream->sample_aspect_ratio;
553 if ( codec_sar.num > 0 )
555 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
556 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
558 else if ( stream_sar.num > 0 )
560 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
561 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
565 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
566 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
569 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
570 aspect_ratio = av_q2d( ar );
571 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
576 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
577 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVDictionary **params )
579 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
582 if ( !URL ) return NULL;
585 char *protocol = strdup( URL );
586 char *url = strchr( protocol, ':' );
588 // Only if there is not a protocol specification that avformat can handle
589 #if LIBAVFORMAT_VERSION_MAJOR >= 53
590 if ( url && avio_check( URL, 0 ) < 0 )
592 if ( url && !url_exist( URL ) )
595 // Truncate protocol string
597 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
600 *format = av_find_input_format( protocol );
602 // Eat the format designator
607 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
608 // support for legacy width and height parameters
612 // These are required by video4linux2 (defaults)
613 params->width = profile->width;
614 params->height = profile->height;
615 if ( !strstr( URL, "&frame_rate" ) )
616 params->time_base = (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
617 params->channels = 2;
618 params->sample_rate = 48000;
622 url = strchr( url, '?' );
626 char *name = strdup( ++url );
627 char *value = strchr( name, '=' );
629 // Also accept : as delimiter for backwards compatibility.
630 value = strchr( name, ':' );
635 char *t = strchr( value, '&' );
638 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
639 // translate old parameters to new av_dict names
640 if ( !strcmp( name, "frame_rate" ) )
641 av_dict_set( params, "framerate", value, 0 );
642 else if ( !strcmp( name, "pix_fmt" ) )
643 av_dict_set( params, "pixel_format", value, 0 );
644 else if ( !strcmp( name, "width" ) )
645 width = strdup( value );
646 else if ( !strcmp( name, "height" ) )
647 height = strdup( value );
649 // generic demux/device option support
650 av_dict_set( params, name, value, 0 );
652 if ( !strcmp( name, "frame_rate" ) )
653 params->time_base.den = atoi( value );
654 else if ( !strcmp( name, "frame_rate_base" ) )
655 params->time_base.num = atoi( value );
656 else if ( !strcmp( name, "sample_rate" ) )
657 params->sample_rate = atoi( value );
658 else if ( !strcmp( name, "channel" ) )
659 params->channel = atoi( value );
660 else if ( !strcmp( name, "channels" ) )
661 params->channels = atoi( value );
662 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
663 else if ( !strcmp( name, "pix_fmt" ) )
664 params->pix_fmt = av_get_pix_fmt( value );
666 else if ( !strcmp( name, "width" ) )
667 params->width = atoi( value );
668 else if ( !strcmp( name, "height" ) )
669 params->height = atoi( value );
670 else if ( !strcmp( name, "standard" ) )
671 params->standard = strdup( value );
675 url = strchr( url, '&' );
677 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
678 // continued support for legacy width and height parameters
679 if ( width && height )
681 char *s = malloc( strlen( width ) + strlen( height ) + 2 );
685 av_dict_set( params, "video_size", s, 0 );
688 if ( width ) free( width );
689 if ( height ) free ( height );
692 result = strdup( result );
696 result = strdup( URL );
702 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
706 // Get the properties
707 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
709 AVFormatContext *format = self->video_format;
711 // We will treat everything with the producer fps.
712 // TODO: make this more flexible.
713 double fps = mlt_profile_fps( profile );
716 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
718 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
719 // when producer_open is called after initial call when restoring or reseting the producer.
720 if ( format->duration != AV_NOPTS_VALUE )
722 // This isn't going to be accurate for all formats
723 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
724 mlt_properties_set_position( properties, "out", frames - 1 );
725 mlt_properties_set_position( properties, "length", frames );
726 mlt_properties_set_int( properties, "_length_computed", 1 );
730 // Set live sources to run forever
731 mlt_properties_set_position( properties, "length", INT_MAX );
732 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
733 mlt_properties_set( properties, "eof", "loop" );
734 mlt_properties_set_int( properties, "_length_computed", 1 );
738 // Check if we're seekable
739 // avdevices are typically AVFMT_NOFILE and not seekable
740 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
743 // protocols can indicate if they support seeking
744 #if LIBAVFORMAT_VERSION_MAJOR >= 53
745 self->seekable = format->pb->seekable;
747 URLContext *uc = url_fileno( format->pb );
749 self->seekable = !uc->is_streamed;
752 if ( self->seekable )
754 // Do a more rigourous test of seekable on a disposable context
755 self->seekable = av_seek_frame( format, -1, format->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
756 mlt_properties_set_int( properties, "seekable", self->seekable );
757 self->dummy_context = format;
758 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
759 self->video_format = NULL;
760 avformat_open_input( &self->video_format, filename, NULL, NULL );
761 avformat_find_stream_info( self->video_format, NULL );
763 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
764 av_find_stream_info( self->video_format );
766 format = self->video_format;
769 // Fetch the width, height and aspect ratio
770 if ( self->video_index != -1 )
772 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
773 mlt_properties_set_int( properties, "width", codec_context->width );
774 mlt_properties_set_int( properties, "height", codec_context->height );
776 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
778 // Fetch the first frame of DV so we can read it directly
783 ret = av_read_frame( format, &pkt );
784 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
786 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
793 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
797 // Verify that we can convert this to YUV 4:2:2
798 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
799 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
800 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
802 sws_freeContext( context );
813 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
815 // Return an error code (0 == no error)
817 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
822 pthread_mutex_init( &self->audio_mutex, NULL );
823 pthread_mutex_init( &self->video_mutex, NULL );
824 pthread_mutex_init( &self->packets_mutex, NULL );
825 pthread_mutex_init( &self->open_mutex, NULL );
826 pthread_mutex_lock( &self->audio_mutex );
827 pthread_mutex_lock( &self->video_mutex );
829 mlt_events_block( properties, self->parent );
832 AVInputFormat *format = NULL;
833 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
834 AVDictionary *params = NULL;
836 AVFormatParameters params;
837 memset( ¶ms, 0, sizeof(params) );
839 char *filename = parse_url( profile, URL, &format, ¶ms );
841 // Now attempt to open the file or device with filename
842 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
843 error = avformat_open_input( &self->video_format, filename, format, ¶ms ) < 0;
845 // If the URL is a network stream URL, then we probably need to open with full URL
846 error = avformat_open_input( &self->video_format, URL, format, ¶ms ) < 0;
848 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
850 // If the URL is a network stream URL, then we probably need to open with full URL
851 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
854 // Set MLT properties onto video AVFormatContext
855 if ( !error && self->video_format )
857 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
858 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
859 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
860 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
864 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
865 av_dict_free( ¶ms );
867 // Cleanup AVFormatParameters
868 if ( params.standard )
869 free( (void*) params.standard );
872 // If successful, then try to get additional info
873 if ( !error && self->video_format )
875 // Get the stream info
876 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
877 error = avformat_find_stream_info( self->video_format, NULL ) < 0;
879 error = av_find_stream_info( self->video_format ) < 0;
882 // Continue if no error
883 if ( !error && self->video_format )
885 // Find default audio and video streams
886 find_default_streams( self );
887 error = get_basic_info( self, profile, filename );
889 // Initialize position info
890 self->first_pts = -1;
891 self->last_position = POSITION_INITIAL;
893 if ( !self->audio_format )
895 // We're going to cheat here - for seekable A/V files, we will have separate contexts
896 // to support independent seeking of audio from video.
897 // TODO: Is this really necessary?
898 if ( self->audio_index != -1 && self->video_index != -1 )
900 if ( self->seekable )
902 // And open again for our audio context
903 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
904 avformat_open_input( &self->audio_format, filename, NULL, NULL );
905 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
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 );
908 avformat_find_stream_info( self->audio_format, NULL );
910 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
911 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
912 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
913 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
914 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
916 av_find_stream_info( self->audio_format );
921 self->audio_format = self->video_format;
924 else if ( self->audio_index != -1 )
926 // We only have an audio context
927 self->audio_format = self->video_format;
928 self->video_format = NULL;
930 else if ( self->video_index == -1 )
932 // Something has gone wrong
935 if ( self->audio_format && !self->audio_streams )
936 get_audio_streams_info( self );
944 self->apackets = mlt_deque_init();
945 self->vpackets = mlt_deque_init();
948 if ( self->dummy_context )
950 pthread_mutex_lock( &self->open_mutex );
951 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
952 avformat_close_input( &self->dummy_context );
954 av_close_input_file( self->dummy_context );
956 self->dummy_context = NULL;
957 pthread_mutex_unlock( &self->open_mutex );
960 // Unlock the service
963 pthread_mutex_unlock( &self->audio_mutex );
964 pthread_mutex_unlock( &self->video_mutex );
966 mlt_events_unblock( properties, self->parent );
971 static void reopen_video( producer_avformat self, mlt_producer producer )
973 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
974 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
975 pthread_mutex_lock( &self->audio_mutex );
976 pthread_mutex_lock( &self->open_mutex );
978 if ( self->video_codec )
979 avcodec_close( self->video_codec );
980 self->video_codec = NULL;
981 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
982 if ( self->dummy_context )
983 avformat_close_input( &self->dummy_context );
984 if ( self->video_format )
985 avformat_close_input( &self->video_format );
987 if ( self->dummy_context )
988 av_close_input_file( self->dummy_context );
989 if ( self->video_format )
990 av_close_input_file( self->video_format );
992 self->dummy_context = NULL;
993 self->video_format = NULL;
994 pthread_mutex_unlock( &self->open_mutex );
996 int audio_index = self->audio_index;
997 int video_index = self->video_index;
999 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1000 mlt_properties_get( properties, "resource" ), 0 );
1002 self->audio_index = audio_index;
1003 if ( self->video_format && video_index > -1 )
1005 self->video_index = video_index;
1006 video_codec_init( self, video_index, properties );
1009 pthread_mutex_unlock( &self->audio_mutex );
1010 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1013 static int seek_video( producer_avformat self, mlt_position position,
1014 int64_t req_position, int must_decode, int use_new_seek, int *ignore )
1016 mlt_producer producer = self->parent;
1019 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
1021 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1023 // Fetch the video format context
1024 AVFormatContext *context = self->video_format;
1026 // Get the video stream
1027 AVStream *stream = context->streams[ self->video_index ];
1029 // Get codec context
1030 AVCodecContext *codec_context = stream->codec;
1032 // We may want to use the source fps if available
1033 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1034 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1036 if ( self->av_frame && position + 1 == self->video_expected )
1038 // We're paused - use last image
1041 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
1043 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1044 *ignore = ( int )( ( position - self->video_expected ) / mlt_producer_get_fps( producer ) * source_fps );
1045 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1047 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
1049 if ( use_new_seek && self->last_position == POSITION_INITIAL )
1051 // find first key frame
1056 while ( ret >= 0 && toscan-- > 0 )
1058 ret = av_read_frame( context, &pkt );
1059 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
1061 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) );
1062 self->first_pts = pkt.pts;
1065 av_free_packet( &pkt );
1068 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1071 // Calculate the timestamp for the requested frame
1075 timestamp = ( req_position - 0.1 / source_fps ) /
1076 ( av_q2d( stream->time_base ) * source_fps );
1077 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pos %"PRId64" pts %"PRId64"\n", req_position, timestamp );
1078 if ( self->first_pts > 0 )
1079 timestamp += self->first_pts;
1080 else if ( context->start_time != AV_NOPTS_VALUE )
1081 timestamp += context->start_time;
1085 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
1086 if ( context->start_time != AV_NOPTS_VALUE )
1087 timestamp += context->start_time;
1090 timestamp -= AV_TIME_BASE;
1091 if ( timestamp < 0 )
1093 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
1094 timestamp, position, self->video_expected, self->last_position );
1096 // Seek to the timestamp
1099 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1100 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1102 else if ( req_position > 0 || self->last_position <= 0 )
1104 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
1108 // Re-open video stream when rewinding to beginning from somewhere else.
1109 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1110 // not reliably seeking to the first frame across formats.
1111 reopen_video( self, producer );
1114 // Remove the cached info relating to the previous position
1115 self->current_position = POSITION_INVALID;
1116 self->last_position = POSITION_INVALID;
1117 av_freep( &self->av_frame );
1121 // flush any pictures still in decode buffer
1122 avcodec_flush_buffers( codec_context );
1129 /** Convert a frame position to a time code.
1132 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1134 return ( double )position / mlt_producer_get_fps( producer );
1137 // Collect information about all audio streams
1139 static void get_audio_streams_info( producer_avformat self )
1141 // Fetch the audio format context
1142 AVFormatContext *context = self->audio_format;
1146 i < context->nb_streams;
1149 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1151 AVCodecContext *codec_context = context->streams[i]->codec;
1152 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1154 // If we don't have a codec and we can't initialise it, we can't do much more...
1155 pthread_mutex_lock( &self->open_mutex );
1156 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1157 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1159 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1162 self->audio_streams++;
1163 self->audio_max_stream = i;
1164 self->total_channels += codec_context->channels;
1165 if ( codec_context->channels > self->max_channel )
1166 self->max_channel = codec_context->channels;
1167 if ( codec_context->sample_rate > self->max_frequency )
1168 self->max_frequency = codec_context->sample_rate;
1169 avcodec_close( codec_context );
1171 pthread_mutex_unlock( &self->open_mutex );
1174 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1175 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1177 // Other audio-specific initializations
1178 self->resample_factor = 1.0;
1181 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1183 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1185 const int *new_coefficients;
1187 int brightness, contrast, saturation;
1189 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1190 &brightness, &contrast, &saturation ) != -1 )
1192 // Don't change these from defaults unless explicitly told to.
1193 if ( use_full_range >= 0 )
1194 full_range = use_full_range;
1195 switch ( colorspace )
1201 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1204 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1207 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1210 new_coefficients = coefficients;
1213 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1214 brightness, contrast, saturation );
1219 static mlt_image_format pick_format( enum PixelFormat pix_fmt )
1227 return mlt_image_rgb24a;
1228 case PIX_FMT_YUV420P:
1229 case PIX_FMT_YUVJ420P:
1230 case PIX_FMT_YUVA420P:
1231 return mlt_image_yuv420p;
1235 case PIX_FMT_MONOWHITE:
1236 case PIX_FMT_MONOBLACK:
1239 return mlt_image_rgb24;
1241 return mlt_image_yuv422;
1245 static void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
1246 mlt_image_format *format, int width, int height, int colorspace )
1249 int full_range = -1;
1250 int flags = SWS_BILINEAR | SWS_ACCURATE_RND;
1253 flags |= SWS_CPU_CAPS_MMX;
1256 flags |= SWS_CPU_CAPS_MMX2;
1259 if ( *format == mlt_image_yuv420p )
1261 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1262 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1264 output.data[0] = buffer;
1265 output.data[1] = buffer + width * height;
1266 output.data[2] = buffer + ( 5 * width * height ) / 4;
1267 output.linesize[0] = width;
1268 output.linesize[1] = width >> 1;
1269 output.linesize[2] = width >> 1;
1270 set_luma_transfer( context, colorspace, full_range );
1271 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1272 output.data, output.linesize);
1273 sws_freeContext( context );
1275 else if ( *format == mlt_image_rgb24 )
1277 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1278 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1280 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1281 set_luma_transfer( context, colorspace, full_range );
1282 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1283 output.data, output.linesize);
1284 sws_freeContext( context );
1286 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1288 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1289 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1291 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1292 set_luma_transfer( context, colorspace, full_range );
1293 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1294 output.data, output.linesize);
1295 sws_freeContext( context );
1299 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1300 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1302 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1303 set_luma_transfer( context, colorspace, full_range );
1304 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1305 output.data, output.linesize);
1306 sws_freeContext( context );
1309 if ( *format == mlt_image_yuv420p )
1312 pict.data[0] = buffer;
1313 pict.data[1] = buffer + width * height;
1314 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1315 pict.linesize[0] = width;
1316 pict.linesize[1] = width >> 1;
1317 pict.linesize[2] = width >> 1;
1318 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1320 else if ( *format == mlt_image_rgb24 )
1323 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1324 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1326 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
1329 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1330 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1335 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1336 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1341 /** Allocate the image buffer and set it on the frame.
1344 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1348 if ( codec_context->width == 0 || codec_context->height == 0 )
1350 *width = codec_context->width;
1351 *height = codec_context->height;
1352 size = mlt_image_format_size( *format, *width, *height, NULL );
1353 *buffer = mlt_pool_alloc( size );
1355 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1362 /** Get an image from a frame.
1365 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1368 producer_avformat self = mlt_frame_pop_service( frame );
1369 mlt_producer producer = self->parent;
1371 // Get the properties from the frame
1372 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1374 // Obtain the frame number of this frame
1375 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1377 // Get the producer properties
1378 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1380 pthread_mutex_lock( &self->video_mutex );
1382 // Fetch the video format context
1383 AVFormatContext *context = self->video_format;
1385 // Get the video stream
1386 AVStream *stream = context->streams[ self->video_index ];
1388 // Get codec context
1389 AVCodecContext *codec_context = stream->codec;
1391 // Get the image cache
1392 if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1393 self->image_cache = mlt_cache_init();
1394 if ( self->image_cache )
1396 mlt_cache_item item = mlt_cache_get( self->image_cache, (void*) position );
1397 uint8_t *original = mlt_cache_item_data( item, (int*) format );
1400 // Set the resolution
1401 *width = codec_context->width;
1402 *height = codec_context->height;
1404 // Workaround 1088 encodings missing cropping info.
1405 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1409 int size = mlt_image_format_size( *format, *width, *height, NULL );
1412 *buffer = mlt_pool_alloc( size );
1413 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1414 memcpy( *buffer, original, size );
1415 mlt_cache_item_close( item );
1420 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1421 mlt_frame_set_image( frame, *buffer, size, NULL );
1423 self->got_picture = 1;
1425 goto exit_get_image;
1434 // Special case ffwd handling
1437 // We may want to use the source fps if available
1438 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1439 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1441 // This is the physical frame position in the source
1442 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1444 // Determines if we have to decode all frames in a sequence
1445 // Temporary hack to improve intra frame only
1446 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1447 strcmp( codec_context->codec->name, "dnxhd" ) &&
1448 strcmp( codec_context->codec->name, "dvvideo" ) &&
1449 strcmp( codec_context->codec->name, "huffyuv" ) &&
1450 strcmp( codec_context->codec->name, "mjpeg" ) &&
1451 strcmp( codec_context->codec->name, "rawvideo" ) );
1453 // Turn on usage of new seek API and PTS for seeking
1454 int use_new_seek = self->seekable &&
1455 codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1456 if ( mlt_properties_get( properties, "new_seek" ) )
1457 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1458 double delay = mlt_properties_get_double( properties, "video_delay" );
1460 // Seek if necessary
1461 int paused = seek_video( self, position, req_position, must_decode, use_new_seek, &ignore );
1463 // Seek might have reopened the file
1464 context = self->video_format;
1465 stream = context->streams[ self->video_index ];
1466 codec_context = stream->codec;
1468 if ( *format == mlt_image_none ||
1469 codec_context->pix_fmt == PIX_FMT_ARGB ||
1470 codec_context->pix_fmt == PIX_FMT_RGBA ||
1471 codec_context->pix_fmt == PIX_FMT_ABGR ||
1472 codec_context->pix_fmt == PIX_FMT_BGRA )
1473 *format = pick_format( codec_context->pix_fmt );
1475 // Duplicate the last image if necessary
1476 if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture
1478 || self->current_position == req_position
1479 || ( !use_new_seek && self->current_position > req_position ) ) )
1482 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1484 // Workaround 1088 encodings missing cropping info.
1485 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1488 if ( self->vdpau && self->vdpau->buffer )
1491 picture.data[0] = self->vdpau->buffer;
1492 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1493 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1494 picture.linesize[0] = codec_context->width;
1495 picture.linesize[1] = codec_context->width / 2;
1496 picture.linesize[2] = codec_context->width / 2;
1497 convert_image( (AVFrame*) &picture, *buffer,
1498 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1502 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1503 format, *width, *height, self->colorspace );
1506 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1511 int64_t int_position = 0;
1512 int decode_errors = 0;
1513 int got_picture = 0;
1515 av_init_packet( &pkt );
1517 // Construct an AVFrame for YUV422 conversion
1518 if ( !self->av_frame )
1519 self->av_frame = avcodec_alloc_frame( );
1521 while( ret >= 0 && !got_picture )
1524 pthread_mutex_lock( &self->packets_mutex );
1525 if ( mlt_deque_count( self->vpackets ) )
1527 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1533 ret = av_read_frame( context, &pkt );
1534 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->audio_index )
1536 if ( !av_dup_packet( &pkt ) )
1538 AVPacket *tmp = malloc( sizeof(AVPacket) );
1540 mlt_deque_push_back( self->apackets, tmp );
1544 pthread_mutex_unlock( &self->packets_mutex );
1546 // We only deal with video from the selected video_index
1547 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1549 // Determine time code of the packet
1552 int64_t pts = pkt.pts;
1553 if ( self->first_pts > 0 )
1554 pts -= self->first_pts;
1555 else if ( context->start_time != AV_NOPTS_VALUE )
1556 pts -= context->start_time;
1557 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.1 );
1558 if ( pkt.pts == AV_NOPTS_VALUE )
1560 self->invalid_pts_counter++;
1561 if ( self->invalid_pts_counter > 20 )
1563 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1564 mlt_properties_set_int( properties, "new_seek", 0 );
1565 int_position = req_position;
1571 self->invalid_pts_counter = 0;
1573 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1574 pkt.pts, req_position, self->current_position, int_position );
1578 if ( pkt.dts != AV_NOPTS_VALUE )
1580 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pkt.dts + delay ) * source_fps + 0.5 );
1581 if ( context->start_time != AV_NOPTS_VALUE )
1582 int_position -= ( int64_t )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1583 if ( int_position == self->last_position )
1584 int_position = self->last_position + 1;
1586 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1587 pkt.dts, req_position, self->current_position, int_position );
1588 // Make a dumb assumption on streams that contain wild timestamps
1589 if ( abs( req_position - int_position ) > 999 )
1591 int_position = req_position;
1592 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1595 self->last_position = int_position;
1598 if ( must_decode || int_position >= req_position )
1603 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1605 vdpau_decoder_init( self );
1607 self->vdpau->is_decoded = 0;
1610 codec_context->reordered_opaque = pkt.pts;
1611 if ( int_position >= req_position )
1612 codec_context->skip_loop_filter = AVDISCARD_NONE;
1613 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1614 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1616 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1618 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1621 if ( ++decode_errors <= 10 )
1634 // Determine time code of the packet
1635 int64_t pts = self->av_frame->reordered_opaque;
1636 if ( self->first_pts > 0 )
1637 pts -= self->first_pts;
1638 else if ( context->start_time != AV_NOPTS_VALUE )
1639 pts -= context->start_time;
1640 int_position = ( int64_t )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1641 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %"PRId64", key %d\n", int_position, self->av_frame->key_frame );
1644 if ( int_position < req_position )
1649 else if ( int_position >= req_position )
1652 codec_context->skip_loop_filter = AVDISCARD_NONE;
1654 else if ( ignore -- )
1659 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1662 // Now handle the picture if we have one
1665 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1667 // Workaround 1088 encodings missing cropping info.
1668 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1673 if ( self->vdpau->is_decoded )
1675 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1677 uint32_t pitches[3];
1678 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1680 if ( !self->vdpau->buffer )
1681 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1682 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1683 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1684 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1685 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1686 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1687 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1689 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1690 if ( status == VDP_STATUS_OK )
1692 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1693 format, *width, *height, self->colorspace );
1697 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1698 image_size = self->vdpau->is_decoded = 0;
1703 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1704 image_size = got_picture = 0;
1709 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1710 format, *width, *height, self->colorspace );
1711 self->top_field_first |= self->av_frame->top_field_first;
1712 self->current_position = int_position;
1713 self->got_picture = 1;
1720 if ( self->seekable || pkt.stream_index != self->audio_index )
1721 av_free_packet( &pkt );
1725 if ( self->got_picture && image_size > 0 && self->image_cache )
1727 // Copy buffer to image cache
1728 uint8_t *image = mlt_pool_alloc( image_size );
1729 memcpy( image, *buffer, image_size );
1730 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1732 // Try to duplicate last image if there was a decoding failure
1733 else if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1736 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1738 // Workaround 1088 encodings missing cropping info.
1739 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1742 if ( self->vdpau && self->vdpau->buffer )
1745 picture.data[0] = self->vdpau->buffer;
1746 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1747 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1748 picture.linesize[0] = codec_context->width;
1749 picture.linesize[1] = codec_context->width / 2;
1750 picture.linesize[2] = codec_context->width / 2;
1751 convert_image( (AVFrame*) &picture, *buffer,
1752 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1756 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1757 format, *width, *height, self->colorspace );
1758 self->got_picture = 1;
1761 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1764 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1765 self->video_expected = position + 1;
1769 pthread_mutex_unlock( &self->video_mutex );
1771 // Set the progressive flag
1772 if ( mlt_properties_get( properties, "force_progressive" ) )
1773 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1774 else if ( self->av_frame )
1775 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1777 // Set the field order property for this frame
1778 if ( mlt_properties_get( properties, "force_tff" ) )
1779 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1781 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1783 // Set immutable properties of the selected track's (or overridden) source attributes.
1784 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1785 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1786 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1787 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1789 return !self->got_picture;
1792 /** Process properties as AVOptions and apply to AV context obj
1795 static void apply_properties( void *obj, mlt_properties properties, int flags )
1798 int count = mlt_properties_count( properties );
1799 for ( i = 0; i < count; i++ )
1801 const char *opt_name = mlt_properties_get_name( properties, i );
1802 #if LIBAVUTIL_VERSION_INT > ((51<<16)+(7<<8)+0)
1803 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1805 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1807 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1810 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1811 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1812 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1813 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1814 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1815 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1817 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1823 /** Initialize the video codec context.
1826 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1828 // Initialise the codec if necessary
1829 if ( !self->video_codec )
1831 // Get the video stream
1832 AVStream *stream = self->video_format->streams[ index ];
1834 // Get codec context
1835 AVCodecContext *codec_context = stream->codec;
1838 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1840 if ( codec_context->codec_id == CODEC_ID_H264 )
1842 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1844 if ( vdpau_init( self ) )
1846 self->video_codec = codec_context;
1847 if ( !vdpau_decoder_init( self ) )
1852 codec = avcodec_find_decoder( codec_context->codec_id );
1856 // Initialise multi-threading
1857 int thread_count = mlt_properties_get_int( properties, "threads" );
1858 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1859 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1860 if ( thread_count > 1 )
1861 codec_context->thread_count = thread_count;
1863 // If we don't have a codec and we can't initialise it, we can't do much more...
1864 pthread_mutex_lock( &self->open_mutex );
1865 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1866 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1868 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1871 // Now store the codec with its destructor
1872 self->video_codec = codec_context;
1876 // Remember that we can't use this later
1877 self->video_index = -1;
1878 pthread_mutex_unlock( &self->open_mutex );
1881 pthread_mutex_unlock( &self->open_mutex );
1883 // Process properties as AVOptions
1884 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1885 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1886 if ( codec->priv_class && codec_context->priv_data )
1887 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1890 // Reset some image properties
1891 mlt_properties_set_int( properties, "width", self->video_codec->width );
1892 mlt_properties_set_int( properties, "height", self->video_codec->height );
1893 // For DV, we'll just use the saved aspect ratio
1894 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1895 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1897 // Determine the fps first from the codec
1898 double source_fps = (double) self->video_codec->time_base.den /
1899 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1901 if ( mlt_properties_get( properties, "force_fps" ) )
1903 source_fps = mlt_properties_get_double( properties, "force_fps" );
1904 stream->time_base = av_d2q( source_fps, 1024 );
1905 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1906 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1910 // If the muxer reports a frame rate different than the codec
1911 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1912 double muxer_fps = av_q2d( stream->avg_frame_rate );
1913 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1914 muxer_fps = av_q2d( stream->r_frame_rate );
1916 double muxer_fps = av_q2d( stream->r_frame_rate );
1918 // Choose the lesser - the wrong tends to be off by some multiple of 10
1919 source_fps = FFMIN( source_fps, muxer_fps );
1920 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1922 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1923 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1925 else if ( muxer_fps > 0 )
1927 AVRational frame_rate = stream->r_frame_rate;
1928 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1929 // avg_frame_rate gives some approximate value that does not well match the media.
1930 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1931 // results in some very choppy output, but some value slightly different works
1933 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1934 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1935 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1937 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1938 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1939 source_fps = av_q2d( frame_rate );
1943 source_fps = mlt_producer_get_fps( self->parent );
1944 AVRational frame_rate = av_d2q( source_fps, 255 );
1945 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1946 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1950 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1951 if ( source_fps > 0 )
1952 mlt_properties_set_double( properties, "source_fps", source_fps );
1954 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
1956 // Set the YUV colorspace from override or detect
1957 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1958 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1959 if ( ! self->colorspace )
1961 switch ( self->video_codec->colorspace )
1963 case AVCOL_SPC_SMPTE240M:
1964 self->colorspace = 240;
1966 case AVCOL_SPC_BT470BG:
1967 case AVCOL_SPC_SMPTE170M:
1968 self->colorspace = 601;
1970 case AVCOL_SPC_BT709:
1971 self->colorspace = 709;
1974 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1975 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1980 // Let apps get chosen colorspace
1981 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1983 return self->video_codec && self->video_index > -1;
1986 /** Set up video handling.
1989 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1992 mlt_producer producer = self->parent;
1994 // Get the properties
1995 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1997 // Fetch the video format context
1998 AVFormatContext *context = self->video_format;
2000 // Get the video_index
2001 int index = mlt_properties_get_int( properties, "video_index" );
2003 // Reopen the file if necessary
2004 if ( !context && index > -1 )
2006 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2007 mlt_properties_get( properties, "resource" ), 1 );
2008 context = self->video_format;
2011 // Exception handling for video_index
2012 if ( context && index >= (int) context->nb_streams )
2014 // Get the last video stream
2015 for ( index = context->nb_streams - 1;
2016 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
2018 mlt_properties_set_int( properties, "video_index", index );
2020 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
2022 // Invalidate the video stream
2024 mlt_properties_set_int( properties, "video_index", index );
2027 // Update the video properties if the index changed
2028 if ( index != self->video_index )
2030 // Reset the video properties if the index changed
2031 self->video_index = index;
2032 pthread_mutex_lock( &self->open_mutex );
2033 if ( self->video_codec )
2034 avcodec_close( self->video_codec );
2035 self->video_codec = NULL;
2036 pthread_mutex_unlock( &self->open_mutex );
2039 // Get the frame properties
2040 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2043 if ( context && index > -1 && video_codec_init( self, index, properties ) )
2045 // Set the frame properties
2046 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
2047 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
2048 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
2050 // Set the width and height
2051 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
2052 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
2053 // real_width and real_height are deprecated in favor of meta.media.width and .height
2054 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
2055 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
2056 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
2057 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
2058 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
2059 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
2061 // Workaround 1088 encodings missing cropping info.
2062 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
2064 mlt_properties_set_int( properties, "meta.media.height", 1080 );
2065 mlt_properties_set_int( frame_properties, "real_height", 1080 );
2068 // Add our image operation
2069 mlt_frame_push_service( frame, self );
2070 mlt_frame_push_get_image( frame, producer_get_image );
2074 // If something failed, use test card image
2075 mlt_properties_set_int( frame_properties, "test_image", 1 );
2079 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
2083 // Seek if necessary
2084 if ( self->seekable && position != self->audio_expected )
2086 if ( position + 1 == self->audio_expected )
2088 // We're paused - silence required
2091 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
2093 // Fast forward - seeking is inefficient for small distances - just ignore following frames
2094 *ignore = position - self->audio_expected;
2096 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
2098 AVFormatContext *context = self->audio_format;
2099 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
2100 if ( context->start_time != AV_NOPTS_VALUE )
2101 timestamp += context->start_time;
2102 if ( timestamp < 0 )
2105 // Set to the real timecode
2106 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
2109 // Clear the usage in the audio buffer
2110 int i = MAX_AUDIO_STREAMS + 1;
2112 self->audio_used[i - 1] = 0;
2118 static int sample_bytes( AVCodecContext *context )
2120 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2121 return av_get_bytes_per_sample( context->sample_fmt );
2122 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2123 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2125 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2129 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2131 // Fetch the audio_format
2132 AVFormatContext *context = self->audio_format;
2134 // Get the current stream index
2135 int index = pkt.stream_index;
2137 // Get codec context
2138 AVCodecContext *codec_context = self->audio_codec[ index ];
2140 // Obtain the resample context if it exists (not always needed)
2141 ReSampleContext *resample = self->audio_resample[ index ];
2143 // Obtain the audio buffers
2144 uint8_t *audio_buffer = self->audio_buffer[ index ];
2145 uint8_t *decode_buffer = self->decode_buffer[ index ];
2147 int audio_used = self->audio_used[ index ];
2148 uint8_t *ptr = pkt.data;
2152 while ( ptr && ret >= 0 && len > 0 )
2154 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2155 int data_size = self->audio_buffer_size[ index ];
2158 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2159 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2160 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2161 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2163 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2167 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2171 pkt.size = len -= ret;
2172 pkt.data = ptr += ret;
2174 // If decoded successfully
2175 if ( data_size > 0 )
2177 // Figure out how many samples will be needed after resampling
2178 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2179 int samples_needed = self->resample_factor * convert_samples;
2181 // Resize audio buffer to prevent overflow
2182 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2184 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2185 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2189 // Copy to audio buffer while resampling
2190 uint8_t *source = decode_buffer;
2191 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2192 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2196 // Straight copy to audio buffer
2197 memcpy( &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ], decode_buffer, data_size );
2198 audio_used += convert_samples;
2202 while ( *ignore && audio_used )
2205 audio_used -= audio_used > samples ? samples : audio_used;
2206 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2207 audio_used * sizeof_sample );
2212 // If we're behind, ignore this packet
2213 // Skip this on non-seekable, audio-only inputs.
2214 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2216 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
2217 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2218 int64_t int_position = ( int64_t )( current_pts * fps + 0.5 );
2219 if ( context->start_time != AV_NOPTS_VALUE )
2220 int_position -= ( int64_t )( fps * context->start_time / AV_TIME_BASE + 0.5 );
2222 if ( int_position > 0 )
2224 if ( int_position < req_position )
2225 // We are behind, so skip some
2226 *ignore = req_position - int_position;
2227 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2228 // We are ahead, so seek backwards some more
2229 seek_audio( self, req_position, timecode - 1.0, ignore );
2233 self->audio_used[ index ] = audio_used;
2238 /** Get the audio from a frame.
2240 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2243 producer_avformat self = mlt_frame_pop_audio( frame );
2245 pthread_mutex_lock( &self->audio_mutex );
2247 // Obtain the frame number of this frame
2248 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
2250 // Calculate the real time code
2251 double real_timecode = producer_time_of_frame( self->parent, position );
2253 // Get the producer fps
2254 double fps = mlt_producer_get_fps( self->parent );
2256 // Number of frames to ignore (for ffwd)
2257 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2259 // Flag for paused (silence)
2260 int paused = seek_audio( self, position, real_timecode, &ignore[0] );
2262 // Initialize ignore for all streams from the seek return value
2263 int i = MAX_AUDIO_STREAMS;
2265 ignore[i] = ignore[0];
2267 // Fetch the audio_format
2268 AVFormatContext *context = self->audio_format;
2270 int sizeof_sample = sizeof( int16_t );
2272 // Determine the tracks to use
2273 int index = self->audio_index;
2274 int index_max = self->audio_index + 1;
2275 if ( self->audio_index == INT_MAX )
2278 index_max = context->nb_streams;
2279 *channels = self->total_channels;
2280 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2281 *frequency = FFMAX( self->max_frequency, *frequency );
2284 // Initialize the resamplers and buffers
2285 for ( ; index < index_max; index++ )
2287 // Get codec context
2288 AVCodecContext *codec_context = self->audio_codec[ index ];
2290 if ( codec_context && !self->audio_buffer[ index ] )
2292 // Check for resample and create if necessary
2293 if ( codec_context->channels <= 2 )
2295 // Determine by how much resampling will increase number of samples
2296 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2297 resample_factor *= (double) *frequency / codec_context->sample_rate;
2298 if ( resample_factor > self->resample_factor )
2299 self->resample_factor = resample_factor;
2301 // Create the resampler
2302 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2303 self->audio_resample[ index ] = av_audio_resample_init(
2304 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2305 codec_context->channels, *frequency, codec_context->sample_rate,
2306 AV_SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2308 self->audio_resample[ index ] = audio_resample_init(
2309 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2310 codec_context->channels, *frequency, codec_context->sample_rate );
2315 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2316 sizeof_sample = sample_bytes( codec_context );
2319 // Check for audio buffer and create if necessary
2320 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2321 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2323 // Check for decoder buffer and create if necessary
2324 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2328 // Get the audio if required
2335 av_init_packet( &pkt );
2337 // If not resampling, give consumer more than requested.
2338 // It requested number samples based on requested frame rate.
2339 // Do not clean this up with a samples *= ...!
2340 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2341 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2343 while ( ret >= 0 && !got_audio )
2345 // Check if the buffer already contains the samples required
2346 if ( self->audio_index != INT_MAX &&
2347 self->audio_used[ self->audio_index ] >= *samples &&
2348 ignore[ self->audio_index ] == 0 )
2353 else if ( self->audio_index == INT_MAX )
2355 // Check if there is enough audio for all streams
2357 for ( index = 0; got_audio && index < context->nb_streams; index++ )
2358 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2365 pthread_mutex_lock( &self->packets_mutex );
2366 if ( mlt_deque_count( self->apackets ) )
2368 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2374 ret = av_read_frame( context, &pkt );
2375 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2377 if ( !av_dup_packet( &pkt ) )
2379 AVPacket *tmp = malloc( sizeof(AVPacket) );
2381 mlt_deque_push_back( self->vpackets, tmp );
2385 pthread_mutex_unlock( &self->packets_mutex );
2387 // We only deal with audio from the selected audio index
2388 index = pkt.stream_index;
2389 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2390 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2392 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2393 self->audio_codec[index]->channels : *channels;
2394 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2397 if ( self->seekable || index != self->video_index )
2398 av_free_packet( &pkt );
2402 // Set some additional return values
2403 *format = mlt_audio_s16;
2404 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2406 index = self->audio_index;
2407 *channels = self->audio_codec[ index ]->channels;
2408 *frequency = self->audio_codec[ index ]->sample_rate;
2409 *format = self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_S32 ? mlt_audio_s32le
2410 : self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_FLT ? mlt_audio_f32le
2412 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2414 else if ( self->audio_index == INT_MAX )
2416 // This only works if all audio tracks have the same sample format.
2417 for ( index = 0; index < index_max; index++ )
2418 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2420 *format = self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_S32 ? mlt_audio_s32le
2421 : self->audio_codec[ index ]->sample_fmt == AV_SAMPLE_FMT_FLT ? mlt_audio_f32le
2423 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2428 // Allocate and set the frame's audio buffer
2429 int size = mlt_audio_format_size( *format, *samples, *channels );
2430 *buffer = mlt_pool_alloc( size );
2431 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2433 // Interleave tracks if audio_index=all
2434 if ( self->audio_index == INT_MAX )
2436 uint8_t *dest = *buffer;
2438 for ( i = 0; i < *samples; i++ )
2440 for ( index = 0; index < index_max; index++ )
2441 if ( self->audio_codec[ index ] )
2443 int current_channels = self->audio_codec[ index ]->channels;
2444 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2445 memcpy( dest, src, current_channels * sizeof_sample );
2446 dest += current_channels * sizeof_sample;
2449 for ( index = 0; index < index_max; index++ )
2450 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2452 int current_channels = self->audio_codec[ index ]->channels;
2453 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2454 self->audio_used[index] -= *samples;
2455 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2458 // Copy a single track to the output buffer
2461 index = self->audio_index;
2463 // Now handle the audio if we have enough
2464 if ( self->audio_used[ index ] > 0 )
2466 uint8_t *src = self->audio_buffer[ index ];
2467 // copy samples from audio_buffer
2468 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2469 memcpy( *buffer, src, size * *channels * sizeof_sample );
2470 // supply the remaining requested samples as silence
2471 if ( *samples > self->audio_used[ index ] )
2472 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2473 // reposition the samples within audio_buffer
2474 self->audio_used[ index ] -= size;
2475 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2479 // Otherwise fill with silence
2480 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2486 // Get silence and don't touch the context
2487 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2490 // Regardless of speed (other than paused), we expect to get the next frame
2492 self->audio_expected = position + 1;
2494 pthread_mutex_unlock( &self->audio_mutex );
2499 /** Initialize the audio codec context.
2502 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2504 // Initialise the codec if necessary
2505 if ( !self->audio_codec[ index ] )
2507 // Get codec context
2508 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2511 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2513 // If we don't have a codec and we can't initialise it, we can't do much more...
2514 pthread_mutex_lock( &self->open_mutex );
2515 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2516 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2518 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2521 // Now store the codec with its destructor
2522 if ( self->audio_codec[ index ] )
2523 avcodec_close( self->audio_codec[ index ] );
2524 self->audio_codec[ index ] = codec_context;
2528 // Remember that we can't use self later
2529 self->audio_index = -1;
2531 pthread_mutex_unlock( &self->open_mutex );
2533 // Process properties as AVOptions
2534 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2535 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
2536 if ( codec && codec->priv_class && codec_context->priv_data )
2537 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2540 return self->audio_codec[ index ] && self->audio_index > -1;
2543 /** Set up audio handling.
2546 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2549 mlt_producer producer = self->parent;
2551 // Get the properties
2552 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2554 // Fetch the audio format context
2555 AVFormatContext *context = self->audio_format;
2557 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2559 // Get the audio_index
2560 int index = mlt_properties_get_int( properties, "audio_index" );
2562 // Handle all audio tracks
2563 if ( self->audio_index > -1 &&
2564 mlt_properties_get( properties, "audio_index" ) &&
2565 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2568 // Reopen the file if necessary
2569 if ( !context && self->audio_index > -1 && index > -1 )
2571 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2572 mlt_properties_get( properties, "resource" ), 1 );
2573 context = self->audio_format;
2576 // Exception handling for audio_index
2577 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2579 for ( index = context->nb_streams - 1;
2580 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2582 mlt_properties_set_int( properties, "audio_index", index );
2584 if ( context && index > -1 && index < INT_MAX &&
2585 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2587 index = self->audio_index;
2588 mlt_properties_set_int( properties, "audio_index", index );
2591 // Update the audio properties if the index changed
2592 if ( context && index > -1 && index != self->audio_index )
2594 pthread_mutex_lock( &self->open_mutex );
2595 if ( self->audio_codec[ self->audio_index ] )
2596 avcodec_close( self->audio_codec[ self->audio_index ] );
2597 self->audio_codec[ self->audio_index ] = NULL;
2598 pthread_mutex_unlock( &self->open_mutex );
2600 if ( self->audio_index != -1 )
2601 self->audio_index = index;
2606 if ( context && index == INT_MAX )
2608 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2609 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2610 for ( index = 0; index < context->nb_streams; index++ )
2612 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2613 audio_codec_init( self, index, properties );
2616 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2618 // Set the frame properties
2619 if ( index < INT_MAX )
2621 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2622 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2625 if ( context && index > -1 )
2627 // Add our audio operation
2628 mlt_frame_push_audio( frame, self );
2629 mlt_frame_push_audio( frame, producer_get_audio );
2633 /** Our get frame implementation.
2636 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2638 // Access the private data
2639 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2640 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2641 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2646 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2647 producer->child = self;
2648 self->parent = producer;
2649 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2650 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2653 // Create an empty frame
2654 *frame = mlt_frame_init( service);
2658 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2662 mlt_cache_item_close( cache_item );
2666 // Update timecode on the frame we're creating
2667 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2670 producer_set_up_video( self, *frame );
2673 producer_set_up_audio( self, *frame );
2675 // Set the position of this producer
2676 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2677 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", position );
2679 // Calculate the next timecode
2680 mlt_producer_prepare_next( producer );
2685 static void producer_avformat_close( producer_avformat self )
2687 mlt_log_debug( NULL, "producer_avformat_close\n" );
2689 // Cleanup av contexts
2690 av_free( self->av_frame );
2691 pthread_mutex_lock( &self->open_mutex );
2693 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2695 if ( self->audio_resample[i] )
2696 audio_resample_close( self->audio_resample[i] );
2697 mlt_pool_release( self->audio_buffer[i] );
2698 av_free( self->decode_buffer[i] );
2699 if ( self->audio_codec[i] )
2700 avcodec_close( self->audio_codec[i] );
2701 self->audio_codec[i] = NULL;
2703 if ( self->video_codec )
2704 avcodec_close( self->video_codec );
2705 self->video_codec = NULL;
2707 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2708 if ( self->dummy_context )
2709 avformat_close_input( &self->dummy_context );
2710 if ( self->seekable && self->audio_format )
2711 avformat_close_input( &self->audio_format );
2712 if ( self->video_format )
2713 avformat_close_input( &self->video_format );
2715 if ( self->dummy_context )
2716 av_close_input_file( self->dummy_context );
2717 if ( self->seekable && self->audio_format )
2718 av_close_input_file( self->audio_format );
2719 if ( self->video_format )
2720 av_close_input_file( self->video_format );
2722 pthread_mutex_unlock( &self->open_mutex );
2724 vdpau_producer_close( self );
2726 if ( self->image_cache )
2727 mlt_cache_close( self->image_cache );
2729 // Cleanup the mutexes
2730 pthread_mutex_destroy( &self->audio_mutex );
2731 pthread_mutex_destroy( &self->video_mutex );
2732 pthread_mutex_destroy( &self->packets_mutex );
2733 pthread_mutex_destroy( &self->open_mutex );
2735 // Cleanup the packet queues
2737 if ( self->apackets )
2739 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2741 av_free_packet( pkt );
2744 mlt_deque_close( self->apackets );
2745 self->apackets = NULL;
2747 if ( self->vpackets )
2749 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2751 av_free_packet( pkt );
2754 mlt_deque_close( self->vpackets );
2755 self->vpackets = NULL;
2761 static void producer_close( mlt_producer parent )
2763 // Remove this instance from the cache
2764 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2767 parent->close = NULL;
2768 mlt_producer_close( parent );