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 (32)
83 #define MAX_VDPAU_SURFACES (10)
85 struct producer_avformat_s
88 AVFormatContext *dummy_context;
89 AVFormatContext *audio_format;
90 AVFormatContext *video_format;
91 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
92 AVCodecContext *video_codec;
95 ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
96 mlt_position audio_expected;
97 mlt_position video_expected;
101 int64_t last_position;
103 int64_t current_position;
104 mlt_position nonseek_position;
106 uint8_t *audio_buffer[ MAX_AUDIO_STREAMS ];
107 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
108 uint8_t *decode_buffer[ MAX_AUDIO_STREAMS ];
109 int audio_used[ MAX_AUDIO_STREAMS ];
111 int audio_max_stream;
115 unsigned int invalid_pts_counter;
116 unsigned int invalid_dts_counter;
117 double resample_factor;
118 mlt_cache image_cache;
121 pthread_mutex_t video_mutex;
122 pthread_mutex_t audio_mutex;
125 pthread_mutex_t packets_mutex;
126 pthread_mutex_t open_mutex;
131 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
145 typedef struct producer_avformat_s *producer_avformat;
147 // Forward references.
148 static int list_components( char* file );
149 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock );
150 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
151 static void producer_avformat_close( producer_avformat );
152 static void producer_close( mlt_producer parent );
153 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
154 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
155 static void apply_properties( void *obj, mlt_properties properties, int flags );
156 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
157 static void get_audio_streams_info( producer_avformat self );
163 /** Constructor for libavformat.
166 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
168 if ( list_components( file ) )
171 mlt_producer producer = NULL;
173 // Check that we have a non-NULL argument
176 // Construct the producer
177 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
178 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
181 if ( mlt_producer_init( producer, self ) == 0 )
183 self->parent = producer;
185 // Get the properties
186 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
188 // Set the resource property (required for all producers)
189 mlt_properties_set( properties, "resource", file );
191 // Register transport implementation with the producer
192 producer->close = (mlt_destructor) producer_close;
194 // Register our get_frame implementation
195 producer->get_frame = producer_get_frame;
197 if ( strcmp( service, "avformat-novalidate" ) )
200 if ( producer_open( self, profile, file, 1 ) != 0 )
203 mlt_producer_close( producer );
206 else if ( self->seekable )
208 // Close the file to release resources for large playlists - reopen later as needed
209 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
210 if ( self->audio_format )
211 avformat_close_input( &self->audio_format );
212 if ( self->video_format )
213 avformat_close_input( &self->video_format );
215 if ( self->audio_format )
216 av_close_input_file( self->audio_format );
217 if ( self->video_format )
218 av_close_input_file( self->video_format );
220 self->audio_format = NULL;
221 self->video_format = NULL;
226 // Default the user-selectable indices from the auto-detected indices
227 mlt_properties_set_int( properties, "audio_index", self->audio_index );
228 mlt_properties_set_int( properties, "video_index", self->video_index );
230 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
232 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
239 int list_components( char* file )
243 // Report information about available demuxers and codecs as YAML Tiny
244 if ( file && strstr( file, "f-list" ) )
246 fprintf( stderr, "---\nformats:\n" );
247 AVInputFormat *format = NULL;
248 while ( ( format = av_iformat_next( format ) ) )
249 fprintf( stderr, " - %s\n", format->name );
250 fprintf( stderr, "...\n" );
253 if ( file && strstr( file, "acodec-list" ) )
255 fprintf( stderr, "---\naudio_codecs:\n" );
256 AVCodec *codec = NULL;
257 while ( ( codec = av_codec_next( codec ) ) )
258 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
259 fprintf( stderr, " - %s\n", codec->name );
260 fprintf( stderr, "...\n" );
263 if ( file && strstr( file, "vcodec-list" ) )
265 fprintf( stderr, "---\nvideo_codecs:\n" );
266 AVCodec *codec = NULL;
267 while ( ( codec = av_codec_next( codec ) ) )
268 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
269 fprintf( stderr, " - %s\n", codec->name );
270 fprintf( stderr, "...\n" );
277 /** Find the default streams.
280 static mlt_properties find_default_streams( producer_avformat self )
284 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
285 AVDictionaryEntry *tag = NULL;
287 AVMetadataTag *tag = NULL;
289 AVFormatContext *context = self->video_format;
290 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
292 // Default to the first audio and video streams found
293 self->audio_index = -1;
294 self->video_index = -1;
296 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
298 // Allow for multiple audio and video streams in the file and select first of each (if available)
299 for( i = 0; i < context->nb_streams; i++ )
301 // Get the codec context
302 AVStream *stream = context->streams[ i ];
303 if ( ! stream ) continue;
304 AVCodecContext *codec_context = stream->codec;
305 if ( ! codec_context ) continue;
306 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
307 if ( ! codec ) continue;
309 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
311 // Determine the type and obtain the first index of each type
312 switch( codec_context->codec_type )
314 case CODEC_TYPE_VIDEO:
315 // Use first video stream
316 if ( self->video_index < 0 )
317 self->video_index = i;
318 mlt_properties_set( meta_media, key, "video" );
319 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
320 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
321 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
322 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
323 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
324 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
326 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
329 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
330 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
331 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
333 snprintf( key, sizeof(key), "meta.media.%d.codec.width", i );
334 mlt_properties_set_int( meta_media, key, codec_context->width );
335 snprintf( key, sizeof(key), "meta.media.%d.codec.height", i );
336 mlt_properties_set_int( meta_media, key, codec_context->height );
337 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
338 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
339 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
340 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
341 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(3<<8)+0)
342 mlt_properties_set( meta_media, key, av_get_pix_fmt_name( codec_context->pix_fmt ) );
344 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
346 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
347 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
348 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
349 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
350 switch ( codec_context->colorspace )
352 case AVCOL_SPC_SMPTE240M:
353 mlt_properties_set_int( meta_media, key, 240 );
355 case AVCOL_SPC_BT470BG:
356 case AVCOL_SPC_SMPTE170M:
357 mlt_properties_set_int( meta_media, key, 601 );
359 case AVCOL_SPC_BT709:
360 mlt_properties_set_int( meta_media, key, 709 );
363 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
364 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
369 case CODEC_TYPE_AUDIO:
370 if ( !codec_context->channels )
372 // Use first audio stream
373 if ( self->audio_index < 0 )
374 self->audio_index = i;
375 mlt_properties_set( meta_media, key, "audio" );
376 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
377 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
378 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
379 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
380 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
381 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
383 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
384 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
385 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
386 mlt_properties_set_int( meta_media, key, codec_context->channels );
391 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
392 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
393 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
394 mlt_properties_set( meta_media, key, codec->name );
395 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
396 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
397 mlt_properties_set( meta_media, key, codec->long_name );
399 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
400 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
401 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
402 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
403 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
404 // mlt_properties_set_int( meta_media, key, codec_context->profile );
405 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
406 // mlt_properties_set_int( meta_media, key, codec_context->level );
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( stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
413 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
416 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
418 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
419 mlt_properties_set( meta_media, key, tag->value );
424 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
425 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
426 while ( ( tag = av_dict_get( context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
428 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
431 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
433 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
434 mlt_properties_set( meta_media, key, tag->value );
438 if ( context->title && strcmp( context->title, "" ) )
439 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
440 if ( context->author && strcmp( context->author, "" ) )
441 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
442 if ( context->copyright && strcmp( context->copyright, "" ) )
443 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
444 if ( context->comment )
445 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
446 if ( context->album )
447 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
449 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
450 if ( context->track )
451 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
457 static inline int dv_is_pal( AVPacket *pkt )
459 return pkt->data[3] & 0x80;
462 static int dv_is_wide( AVPacket *pkt )
464 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
466 for ( ; i < pkt->size; i += 5 /* packet size */ )
468 if ( pkt->data[ i ] == 0x61 )
470 uint8_t x = pkt->data[ i + 2 ] & 0x7;
471 return ( x == 2 ) || ( x == 7 );
477 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
479 double aspect_ratio = 1.0;
481 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
485 if ( dv_is_pal( pkt ) )
487 if ( dv_is_wide( pkt ) )
489 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
490 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
494 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
495 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
500 if ( dv_is_wide( pkt ) )
502 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
503 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
507 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
508 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
515 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
516 stream->sample_aspect_ratio;
518 codec_context->sample_aspect_ratio;
520 // Override FFmpeg's notion of DV aspect ratios, which are
521 // based upon a width of 704. Since we do not have a normaliser
522 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
523 // we just coerce the values to facilitate a passive behaviour through
524 // the rescale normaliser when using equivalent producers and consumers.
525 // = display_aspect / (width * height)
526 if ( ar.num == 10 && ar.den == 11 )
529 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
530 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
532 else if ( ar.num == 59 && ar.den == 54 )
535 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
536 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
538 else if ( ar.num == 40 && ar.den == 33 )
541 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
542 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
544 else if ( ar.num == 118 && ar.den == 81 )
547 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
548 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
554 AVRational codec_sar = codec_context->sample_aspect_ratio;
555 AVRational stream_sar =
556 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
557 stream->sample_aspect_ratio;
561 if ( codec_sar.num > 0 )
563 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
564 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
566 else if ( stream_sar.num > 0 )
568 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
569 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
573 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
574 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
577 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
578 aspect_ratio = av_q2d( ar );
579 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
584 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
585 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVDictionary **params )
587 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
590 if ( !URL ) return NULL;
593 char *protocol = strdup( URL );
594 char *url = strchr( protocol, ':' );
596 // Only if there is not a protocol specification that avformat can handle
597 #if LIBAVFORMAT_VERSION_MAJOR >= 53
598 if ( url && avio_check( URL, 0 ) < 0 )
600 if ( url && !url_exist( URL ) )
603 // Truncate protocol string
605 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
608 *format = av_find_input_format( protocol );
610 // Eat the format designator
615 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
616 // support for legacy width and height parameters
620 // These are required by video4linux2 (defaults)
621 params->width = profile->width;
622 params->height = profile->height;
623 if ( !strstr( URL, "&frame_rate" ) )
624 params->time_base = (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
625 params->channels = 2;
626 params->sample_rate = 48000;
630 url = strchr( url, '?' );
634 char *name = strdup( ++url );
635 char *value = strchr( name, '=' );
637 // Also accept : as delimiter for backwards compatibility.
638 value = strchr( name, ':' );
643 char *t = strchr( value, '&' );
646 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
647 // translate old parameters to new av_dict names
648 if ( !strcmp( name, "frame_rate" ) )
649 av_dict_set( params, "framerate", value, 0 );
650 else if ( !strcmp( name, "pix_fmt" ) )
651 av_dict_set( params, "pixel_format", value, 0 );
652 else if ( !strcmp( name, "width" ) )
653 width = strdup( value );
654 else if ( !strcmp( name, "height" ) )
655 height = strdup( value );
657 // generic demux/device option support
658 av_dict_set( params, name, value, 0 );
660 if ( !strcmp( name, "frame_rate" ) )
661 params->time_base.den = atoi( value );
662 else if ( !strcmp( name, "frame_rate_base" ) )
663 params->time_base.num = atoi( value );
664 else if ( !strcmp( name, "sample_rate" ) )
665 params->sample_rate = atoi( value );
666 else if ( !strcmp( name, "channel" ) )
667 params->channel = atoi( value );
668 else if ( !strcmp( name, "channels" ) )
669 params->channels = atoi( value );
670 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
671 else if ( !strcmp( name, "pix_fmt" ) )
672 params->pix_fmt = av_get_pix_fmt( value );
674 else if ( !strcmp( name, "width" ) )
675 params->width = atoi( value );
676 else if ( !strcmp( name, "height" ) )
677 params->height = atoi( value );
678 else if ( !strcmp( name, "standard" ) )
679 params->standard = strdup( value );
683 url = strchr( url, '&' );
685 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
686 // continued support for legacy width and height parameters
687 if ( width && height )
689 char *s = malloc( strlen( width ) + strlen( height ) + 2 );
693 av_dict_set( params, "video_size", s, 0 );
696 if ( width ) free( width );
697 if ( height ) free ( height );
700 result = strdup( result );
704 result = strdup( URL );
710 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
714 // Get the properties
715 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
717 AVFormatContext *format = self->video_format;
719 // We will treat everything with the producer fps.
720 // TODO: make this more flexible.
721 double fps = mlt_profile_fps( profile );
724 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
726 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
727 // when producer_open is called after initial call when restoring or reseting the producer.
728 if ( format->duration != AV_NOPTS_VALUE )
730 // This isn't going to be accurate for all formats
731 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
732 mlt_properties_set_position( properties, "out", frames - 1 );
733 mlt_properties_set_position( properties, "length", frames );
734 mlt_properties_set_int( properties, "_length_computed", 1 );
738 // Set live sources to run forever
739 mlt_properties_set_position( properties, "length", INT_MAX );
740 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
741 mlt_properties_set( properties, "eof", "loop" );
742 mlt_properties_set_int( properties, "_length_computed", 1 );
746 // Check if we're seekable
747 // avdevices are typically AVFMT_NOFILE and not seekable
748 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
751 // protocols can indicate if they support seeking
752 #if LIBAVFORMAT_VERSION_MAJOR >= 53
753 self->seekable = format->pb->seekable;
755 URLContext *uc = url_fileno( format->pb );
757 self->seekable = !uc->is_streamed;
760 if ( self->seekable )
762 // Do a more rigourous test of seekable on a disposable context
763 self->seekable = av_seek_frame( format, -1, format->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
764 mlt_properties_set_int( properties, "seekable", self->seekable );
765 self->dummy_context = format;
766 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
767 self->video_format = NULL;
768 avformat_open_input( &self->video_format, filename, NULL, NULL );
769 avformat_find_stream_info( self->video_format, NULL );
771 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
772 av_find_stream_info( self->video_format );
774 format = self->video_format;
777 // Fetch the width, height and aspect ratio
778 if ( self->video_index != -1 )
780 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
781 mlt_properties_set_int( properties, "width", codec_context->width );
782 mlt_properties_set_int( properties, "height", codec_context->height );
784 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
786 // Fetch the first frame of DV so we can read it directly
791 ret = av_read_frame( format, &pkt );
792 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
794 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
795 av_free_packet(&pkt);
799 av_free_packet(&pkt);
804 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
808 // Verify that we can convert this to YUV 4:2:2
809 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
810 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
811 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
813 sws_freeContext( context );
824 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
826 // Return an error code (0 == no error)
828 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
833 pthread_mutex_init( &self->audio_mutex, NULL );
834 pthread_mutex_init( &self->video_mutex, NULL );
835 pthread_mutex_init( &self->packets_mutex, NULL );
836 pthread_mutex_init( &self->open_mutex, NULL );
837 pthread_mutex_lock( &self->audio_mutex );
838 pthread_mutex_lock( &self->video_mutex );
840 mlt_events_block( properties, self->parent );
843 AVInputFormat *format = NULL;
844 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
845 AVDictionary *params = NULL;
847 AVFormatParameters params;
848 memset( ¶ms, 0, sizeof(params) );
850 char *filename = parse_url( profile, URL, &format, ¶ms );
852 // Now attempt to open the file or device with filename
853 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
854 error = avformat_open_input( &self->video_format, filename, format, ¶ms ) < 0;
856 // If the URL is a network stream URL, then we probably need to open with full URL
857 error = avformat_open_input( &self->video_format, URL, format, ¶ms ) < 0;
859 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
861 // If the URL is a network stream URL, then we probably need to open with full URL
862 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
865 // Set MLT properties onto video AVFormatContext
866 if ( !error && self->video_format )
868 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
869 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
870 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
871 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
875 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
876 av_dict_free( ¶ms );
878 // Cleanup AVFormatParameters
879 if ( params.standard )
880 free( (void*) params.standard );
883 // If successful, then try to get additional info
884 if ( !error && self->video_format )
886 // Get the stream info
887 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
888 error = avformat_find_stream_info( self->video_format, NULL ) < 0;
890 error = av_find_stream_info( self->video_format ) < 0;
893 // Continue if no error
894 if ( !error && self->video_format )
896 // Find default audio and video streams
897 find_default_streams( self );
898 error = get_basic_info( self, profile, filename );
900 // Initialize position info
901 self->first_pts = AV_NOPTS_VALUE;
902 self->last_position = POSITION_INITIAL;
904 if ( !self->audio_format )
906 // We're going to cheat here - for seekable A/V files, we will have separate contexts
907 // to support independent seeking of audio from video.
908 // TODO: Is this really necessary?
909 if ( self->audio_index != -1 && self->video_index != -1 )
911 if ( self->seekable )
913 // And open again for our audio context
914 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
915 avformat_open_input( &self->audio_format, filename, NULL, NULL );
916 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
917 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
918 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
919 avformat_find_stream_info( self->audio_format, NULL );
921 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
922 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
923 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
924 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
925 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
927 av_find_stream_info( self->audio_format );
932 self->audio_format = self->video_format;
935 else if ( self->audio_index != -1 )
937 // We only have an audio context
938 self->audio_format = self->video_format;
939 self->video_format = NULL;
941 else if ( self->video_index == -1 )
943 // Something has gone wrong
946 if ( self->audio_format && !self->audio_streams )
947 get_audio_streams_info( self );
955 self->apackets = mlt_deque_init();
956 self->vpackets = mlt_deque_init();
959 if ( self->dummy_context )
961 pthread_mutex_lock( &self->open_mutex );
962 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
963 avformat_close_input( &self->dummy_context );
965 av_close_input_file( self->dummy_context );
967 self->dummy_context = NULL;
968 pthread_mutex_unlock( &self->open_mutex );
971 // Unlock the service
974 pthread_mutex_unlock( &self->audio_mutex );
975 pthread_mutex_unlock( &self->video_mutex );
977 mlt_events_unblock( properties, self->parent );
982 static void reopen_video( producer_avformat self, mlt_producer producer )
984 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
985 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
986 pthread_mutex_lock( &self->audio_mutex );
987 pthread_mutex_lock( &self->open_mutex );
989 if ( self->video_codec )
990 avcodec_close( self->video_codec );
991 self->video_codec = NULL;
992 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
993 if ( self->dummy_context )
994 avformat_close_input( &self->dummy_context );
995 if ( self->video_format )
996 avformat_close_input( &self->video_format );
998 if ( self->dummy_context )
999 av_close_input_file( self->dummy_context );
1000 if ( self->video_format )
1001 av_close_input_file( self->video_format );
1003 self->dummy_context = NULL;
1004 self->video_format = NULL;
1005 pthread_mutex_unlock( &self->open_mutex );
1007 int audio_index = self->audio_index;
1008 int video_index = self->video_index;
1010 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1011 mlt_properties_get( properties, "resource" ), 0 );
1013 self->audio_index = audio_index;
1014 if ( self->video_format && video_index > -1 )
1016 self->video_index = video_index;
1017 video_codec_init( self, video_index, properties );
1020 pthread_mutex_unlock( &self->audio_mutex );
1021 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1024 static int64_t best_pts( producer_avformat self, int64_t pts, int64_t dts )
1026 self->invalid_pts_counter += pts == AV_NOPTS_VALUE;
1027 self->invalid_dts_counter += dts == AV_NOPTS_VALUE;
1028 if ( ( self->invalid_pts_counter <= self->invalid_dts_counter
1029 || dts == AV_NOPTS_VALUE ) && pts != AV_NOPTS_VALUE )
1035 static int seek_video( producer_avformat self, mlt_position position,
1036 int64_t req_position, int preseek )
1038 mlt_producer producer = self->parent;
1041 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
1043 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1045 // Fetch the video format context
1046 AVFormatContext *context = self->video_format;
1048 // Get the video stream
1049 AVStream *stream = context->streams[ self->video_index ];
1051 // Get codec context
1052 AVCodecContext *codec_context = stream->codec;
1054 // We may want to use the source fps if available
1055 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1056 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1059 if ( self->last_position == POSITION_INITIAL )
1065 while ( ret >= 0 && toscan-- > 0 )
1067 ret = av_read_frame( context, &pkt );
1068 if ( ret >= 0 && pkt.stream_index == self->video_index && ( pkt.flags & PKT_FLAG_KEY ) )
1070 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1071 "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n",
1072 pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
1073 self->first_pts = best_pts( self, pkt.pts, pkt.dts );
1074 if ( self->first_pts != AV_NOPTS_VALUE )
1077 av_free_packet( &pkt );
1079 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1082 if ( self->av_frame && position + 1 == self->video_expected )
1084 // We're paused - use last image
1087 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
1089 // Calculate the timestamp for the requested frame
1090 int64_t timestamp = req_position / ( av_q2d( stream->time_base ) * source_fps );
1091 if ( req_position <= 0 )
1093 else if ( self->first_pts != AV_NOPTS_VALUE )
1094 timestamp += self->first_pts;
1095 else if ( context->start_time != AV_NOPTS_VALUE )
1096 timestamp += context->start_time;
1097 if ( preseek && av_q2d( stream->time_base ) != 0 )
1098 timestamp -= 2 / av_q2d( stream->time_base );
1099 if ( timestamp < 0 )
1101 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
1102 timestamp, position, self->video_expected, self->last_position );
1104 // Seek to the timestamp
1105 // NOTE: reopen_video is disabled at this time because it is causing trouble with A/V sync.
1106 if ( 1 || req_position > 0 || self->last_position <= 0 )
1108 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1109 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1111 // flush any pictures still in decode buffer
1112 avcodec_flush_buffers( codec_context );
1116 // Re-open video stream when rewinding to beginning from somewhere else.
1117 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1118 // not reliably seeking to the first frame across formats.
1119 reopen_video( self, producer );
1122 // Remove the cached info relating to the previous position
1123 self->current_position = POSITION_INVALID;
1124 self->last_position = POSITION_INVALID;
1125 av_freep( &self->av_frame );
1131 /** Convert a frame position to a time code.
1134 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1136 return ( double )position / mlt_producer_get_fps( producer );
1139 // Collect information about all audio streams
1141 static void get_audio_streams_info( producer_avformat self )
1143 // Fetch the audio format context
1144 AVFormatContext *context = self->audio_format;
1148 i < context->nb_streams;
1151 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1153 AVCodecContext *codec_context = context->streams[i]->codec;
1154 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1156 // If we don't have a codec and we can't initialise it, we can't do much more...
1157 pthread_mutex_lock( &self->open_mutex );
1158 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1159 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1161 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1164 self->audio_streams++;
1165 self->audio_max_stream = i;
1166 self->total_channels += codec_context->channels;
1167 if ( codec_context->channels > self->max_channel )
1168 self->max_channel = codec_context->channels;
1169 if ( codec_context->sample_rate > self->max_frequency )
1170 self->max_frequency = codec_context->sample_rate;
1171 avcodec_close( codec_context );
1173 pthread_mutex_unlock( &self->open_mutex );
1176 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1177 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1179 // Other audio-specific initializations
1180 self->resample_factor = 1.0;
1183 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1185 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1187 const int *new_coefficients;
1189 int brightness, contrast, saturation;
1191 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1192 &brightness, &contrast, &saturation ) != -1 )
1194 // Don't change these from defaults unless explicitly told to.
1195 if ( use_full_range >= 0 )
1196 full_range = use_full_range;
1197 switch ( colorspace )
1203 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1206 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1209 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1212 new_coefficients = coefficients;
1215 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1216 brightness, contrast, saturation );
1221 static mlt_image_format pick_pix_format( enum PixelFormat pix_fmt )
1229 return mlt_image_rgb24a;
1230 case PIX_FMT_YUV420P:
1231 case PIX_FMT_YUVJ420P:
1232 case PIX_FMT_YUVA420P:
1233 return mlt_image_yuv420p;
1237 case PIX_FMT_MONOWHITE:
1238 case PIX_FMT_MONOBLACK:
1241 return mlt_image_rgb24;
1243 return mlt_image_yuv422;
1247 static mlt_audio_format pick_audio_format( int sample_fmt )
1249 switch ( sample_fmt )
1252 case AV_SAMPLE_FMT_S16:
1253 return mlt_audio_s16;
1254 case AV_SAMPLE_FMT_S32:
1255 return mlt_audio_s32le;
1256 case AV_SAMPLE_FMT_FLT:
1257 return mlt_audio_f32le;
1258 // planar - this producer converts planar to interleaved
1259 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1260 case AV_SAMPLE_FMT_S16P:
1261 return mlt_audio_s16;
1262 case AV_SAMPLE_FMT_S32P:
1263 return mlt_audio_s32le;
1264 case AV_SAMPLE_FMT_FLTP:
1265 return mlt_audio_f32le;
1268 return mlt_audio_none;
1272 static void convert_image( producer_avformat self, AVFrame *frame, uint8_t *buffer, int pix_fmt,
1273 mlt_image_format *format, int width, int height, uint8_t **alpha )
1276 int flags = SWS_BICUBIC | SWS_ACCURATE_RND;
1279 flags |= SWS_CPU_CAPS_MMX;
1282 flags |= SWS_CPU_CAPS_MMX2;
1285 // extract alpha from planar formats
1286 if ( ( pix_fmt == PIX_FMT_YUVA420P
1287 #if defined(FFUDIV) && LIBAVUTIL_VERSION_INT >= ((51<<16)+(35<<8)+101)
1288 || pix_fmt == PIX_FMT_YUVA444P
1291 *format != mlt_image_rgb24a && *format != mlt_image_opengl &&
1292 frame->data[3] && frame->linesize[3] )
1297 dst = *alpha = mlt_pool_alloc( width * height );
1298 src = frame->data[3];
1300 for ( i = 0; i < height; dst += width, src += frame->linesize[3], i++ )
1301 memcpy( dst, src, FFMIN( width, frame->linesize[3] ) );
1304 if ( *format == mlt_image_yuv420p )
1306 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1307 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1309 output.data[0] = buffer;
1310 output.data[1] = buffer + width * height;
1311 output.data[2] = buffer + ( 5 * width * height ) / 4;
1312 output.linesize[0] = width;
1313 output.linesize[1] = width >> 1;
1314 output.linesize[2] = width >> 1;
1315 set_luma_transfer( context, self->colorspace, -1 );
1316 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1317 output.data, output.linesize);
1318 sws_freeContext( context );
1320 else if ( *format == mlt_image_rgb24 )
1322 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1323 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1325 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1326 set_luma_transfer( context, self->colorspace, self->full_luma );
1327 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1328 output.data, output.linesize);
1329 sws_freeContext( context );
1331 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1333 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1334 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1336 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1337 set_luma_transfer( context, self->colorspace, self->full_luma );
1338 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1339 output.data, output.linesize);
1340 sws_freeContext( context );
1344 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1345 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1347 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1348 set_luma_transfer( context, self->colorspace, -1 );
1349 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1350 output.data, output.linesize);
1351 sws_freeContext( context );
1354 if ( *format == mlt_image_yuv420p )
1357 pict.data[0] = buffer;
1358 pict.data[1] = buffer + width * height;
1359 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1360 pict.linesize[0] = width;
1361 pict.linesize[1] = width >> 1;
1362 pict.linesize[2] = width >> 1;
1363 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1365 else if ( *format == mlt_image_rgb24 )
1368 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1369 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1371 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1374 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1375 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1380 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1381 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1386 /** Allocate the image buffer and set it on the frame.
1389 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1393 if ( codec_context->width == 0 || codec_context->height == 0 )
1395 *width = codec_context->width;
1396 *height = codec_context->height;
1397 size = mlt_image_format_size( *format, *width, *height, NULL );
1398 *buffer = mlt_pool_alloc( size );
1400 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1407 /** Get an image from a frame.
1410 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1413 producer_avformat self = mlt_frame_pop_service( frame );
1414 mlt_producer producer = self->parent;
1416 // Get the properties from the frame
1417 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1419 // Obtain the frame number of this frame
1420 mlt_position position = mlt_frame_original_position( frame );
1422 // Get the producer properties
1423 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1425 pthread_mutex_lock( &self->video_mutex );
1427 // Fetch the video format context
1428 AVFormatContext *context = self->video_format;
1430 // Get the video stream
1431 AVStream *stream = context->streams[ self->video_index ];
1433 // Get codec context
1434 AVCodecContext *codec_context = stream->codec;
1436 uint8_t *alpha = NULL;
1437 int got_picture = 0;
1440 // Get the image cache
1441 if ( ! self->image_cache )
1443 // if cache size supplied by environment variable
1444 int cache_supplied = getenv( "MLT_AVFORMAT_CACHE" ) != NULL;
1445 int cache_size = cache_supplied? atoi( getenv( "MLT_AVFORMAT_CACHE" ) ) : 0;
1447 // cache size supplied via property
1448 if ( mlt_properties_get( properties, "cache" ) )
1451 cache_size = mlt_properties_get_int( properties, "cache" );
1453 if ( mlt_properties_get_int( properties, "noimagecache" ) )
1455 // create cache if not disabled
1456 if ( !cache_supplied || cache_size > 0 )
1457 self->image_cache = mlt_cache_init();
1458 // set cache size if supplied
1459 if ( self->image_cache && cache_supplied )
1460 mlt_cache_set_size( self->image_cache, cache_size );
1462 if ( self->image_cache )
1464 mlt_frame original = mlt_cache_get_frame( self->image_cache, position );
1467 mlt_properties orig_props = MLT_FRAME_PROPERTIES( original );
1470 *buffer = mlt_properties_get_data( orig_props, "alpha", &size );
1472 mlt_frame_set_alpha( frame, *buffer, size, NULL );
1473 *buffer = mlt_properties_get_data( orig_props, "image", &size );
1474 mlt_frame_set_image( frame, *buffer, size, NULL );
1475 mlt_properties_set_data( frame_properties, "avformat.image_cache", original, 0, (mlt_destructor) mlt_frame_close, NULL );
1476 *format = mlt_properties_get_int( orig_props, "format" );
1478 // Set the resolution
1479 *width = codec_context->width;
1480 *height = codec_context->height;
1482 // Workaround 1088 encodings missing cropping info.
1483 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1487 goto exit_get_image;
1492 // We may want to use the source fps if available
1493 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1494 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1496 // This is the physical frame position in the source
1497 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1499 // Determines if we have to decode all frames in a sequence
1500 // Temporary hack to improve intra frame only
1501 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1502 strcmp( codec_context->codec->name, "dnxhd" ) &&
1503 strcmp( codec_context->codec->name, "dvvideo" ) &&
1504 strcmp( codec_context->codec->name, "huffyuv" ) &&
1505 strcmp( codec_context->codec->name, "mjpeg" ) &&
1506 strcmp( codec_context->codec->name, "rawvideo" ) );
1508 double delay = mlt_properties_get_double( properties, "video_delay" );
1510 // Seek if necessary
1511 const char *interp = mlt_properties_get( frame_properties, "rescale.interp" );
1512 int preseek = must_decode
1513 #if defined(FFUDIV) && LIBAVFORMAT_VERSION_INT >= ((53<<16)+(24<<8)+2)
1514 && ( interp && strcmp( interp, "nearest" ) )
1516 && codec_context->has_b_frames;
1517 int paused = seek_video( self, position, req_position, preseek );
1519 // Seek might have reopened the file
1520 context = self->video_format;
1521 stream = context->streams[ self->video_index ];
1522 codec_context = stream->codec;
1523 if ( *format == mlt_image_none ||
1524 codec_context->pix_fmt == PIX_FMT_ARGB ||
1525 codec_context->pix_fmt == PIX_FMT_RGBA ||
1526 codec_context->pix_fmt == PIX_FMT_ABGR ||
1527 codec_context->pix_fmt == PIX_FMT_BGRA )
1528 *format = pick_pix_format( codec_context->pix_fmt );
1530 // Duplicate the last image if necessary
1531 if ( self->av_frame && self->av_frame->linesize[0]
1532 && ( paused || self->current_position >= req_position ) )
1535 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1537 // Workaround 1088 encodings missing cropping info.
1538 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1541 if ( self->vdpau && self->vdpau->buffer )
1544 picture.data[0] = self->vdpau->buffer;
1545 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1546 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1547 picture.linesize[0] = codec_context->width;
1548 picture.linesize[1] = codec_context->width / 2;
1549 picture.linesize[2] = codec_context->width / 2;
1550 convert_image( self, (AVFrame*) &picture, *buffer,
1551 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1555 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1556 format, *width, *height, &alpha );
1563 int64_t int_position = 0;
1564 int decode_errors = 0;
1566 // Construct an AVFrame for YUV422 conversion
1567 if ( !self->av_frame )
1568 self->av_frame = avcodec_alloc_frame( );
1570 while( ret >= 0 && !got_picture )
1573 if ( self->pkt.stream_index == self->video_index )
1574 av_free_packet( &self->pkt );
1575 av_init_packet( &self->pkt );
1576 pthread_mutex_lock( &self->packets_mutex );
1577 if ( mlt_deque_count( self->vpackets ) )
1579 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1585 ret = av_read_frame( context, &self->pkt );
1586 if ( ret >= 0 && !self->seekable && self->pkt.stream_index == self->audio_index )
1588 if ( !av_dup_packet( &self->pkt ) )
1590 AVPacket *tmp = malloc( sizeof(AVPacket) );
1592 mlt_deque_push_back( self->apackets, tmp );
1596 pthread_mutex_unlock( &self->packets_mutex );
1598 // We only deal with video from the selected video_index
1599 if ( ret >= 0 && self->pkt.stream_index == self->video_index && self->pkt.size > 0 )
1601 int64_t pts = best_pts( self, self->pkt.pts, self->pkt.dts );
1602 if ( pts != AV_NOPTS_VALUE )
1604 if ( !self->seekable && self->first_pts == AV_NOPTS_VALUE )
1605 self->first_pts = pts;
1606 if ( self->first_pts != AV_NOPTS_VALUE )
1607 pts -= self->first_pts;
1608 else if ( context->start_time != AV_NOPTS_VALUE )
1609 pts -= context->start_time;
1610 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.5 );
1611 if ( int_position == self->last_position )
1612 int_position = self->last_position + 1;
1614 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1615 "V pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1616 self->pkt.pts, self->pkt.dts, req_position, self->current_position, int_position );
1618 // Make a dumb assumption on streams that contain wild timestamps
1619 if ( abs( req_position - int_position ) > 999 )
1621 int_position = req_position;
1622 mlt_log_warning( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!\n" );
1624 self->last_position = int_position;
1627 if ( must_decode || int_position >= req_position )
1632 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1634 vdpau_decoder_init( self );
1636 self->vdpau->is_decoded = 0;
1639 codec_context->reordered_opaque = int_position;
1640 if ( int_position >= req_position )
1641 codec_context->skip_loop_filter = AVDISCARD_NONE;
1642 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1643 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &self->pkt );
1645 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, self->pkt.data, self->pkt.size );
1647 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1650 if ( ++decode_errors <= 10 )
1661 // Get position of reordered frame
1662 int_position = self->av_frame->reordered_opaque;
1663 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(106<<8)+0))
1664 pts = best_pts( self, self->av_frame->pkt_pts, self->av_frame->pkt_dts );
1665 if ( pts != AV_NOPTS_VALUE )
1667 if ( self->first_pts != AV_NOPTS_VALUE )
1668 pts -= self->first_pts;
1669 else if ( context->start_time != AV_NOPTS_VALUE )
1670 pts -= context->start_time;
1671 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.5 );
1675 if ( int_position < req_position )
1677 else if ( int_position >= req_position )
1678 codec_context->skip_loop_filter = AVDISCARD_NONE;
1680 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, self->pkt.flags & PKT_FLAG_KEY );
1683 // Now handle the picture if we have one
1686 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1688 // Workaround 1088 encodings missing cropping info.
1689 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1694 if ( self->vdpau->is_decoded )
1696 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1698 uint32_t pitches[3];
1699 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1701 if ( !self->vdpau->buffer )
1702 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1703 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1704 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1705 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1706 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1707 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1708 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1710 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1711 if ( status == VDP_STATUS_OK )
1713 convert_image( self, self->av_frame, *buffer, PIX_FMT_YUV420P,
1714 format, *width, *height, &alpha );
1718 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1719 image_size = self->vdpau->is_decoded = 0;
1724 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1725 image_size = got_picture = 0;
1730 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1731 format, *width, *height, &alpha );
1732 self->top_field_first |= self->av_frame->top_field_first;
1733 self->current_position = int_position;
1741 // Free packet data if not video and not live audio packet
1742 if ( self->pkt.stream_index != self->video_index &&
1743 !( !self->seekable && self->pkt.stream_index == self->audio_index ) )
1744 av_free_packet( &self->pkt );
1750 mlt_frame_set_alpha( frame, alpha, (*width) * (*height), mlt_pool_release );
1752 if ( image_size > 0 && self->image_cache )
1754 mlt_properties_set_int( frame_properties, "format", *format );
1755 mlt_cache_put_frame( self->image_cache, frame );
1758 // Try to duplicate last image if there was a decoding failure
1759 // TODO: with multithread decoding a partial frame decoding resulting
1760 // in failure also resets av_frame making test below fail.
1761 if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1764 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1766 // Workaround 1088 encodings missing cropping info.
1767 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1770 if ( self->vdpau && self->vdpau->buffer )
1773 picture.data[0] = self->vdpau->buffer;
1774 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1775 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1776 picture.linesize[0] = codec_context->width;
1777 picture.linesize[1] = codec_context->width / 2;
1778 picture.linesize[2] = codec_context->width / 2;
1779 convert_image( self, (AVFrame*) &picture, *buffer,
1780 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1784 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1785 format, *width, *height, &alpha );
1790 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1791 self->video_expected = position + 1;
1795 pthread_mutex_unlock( &self->video_mutex );
1797 // Set the progressive flag
1798 if ( mlt_properties_get( properties, "force_progressive" ) )
1799 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1800 else if ( self->av_frame )
1801 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1803 // Set the field order property for this frame
1804 if ( mlt_properties_get( properties, "force_tff" ) )
1805 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1807 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1809 // Set immutable properties of the selected track's (or overridden) source attributes.
1810 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1811 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1812 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1813 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1815 // If we already have RGB, then the full range processing either happened already
1816 // or does not apply (RGB source).
1817 if ( *format == mlt_image_rgb24 || *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1818 mlt_properties_set( frame_properties, "force_full_luma", NULL );
1820 return !got_picture;
1823 /** Process properties as AVOptions and apply to AV context obj
1826 static void apply_properties( void *obj, mlt_properties properties, int flags )
1829 int count = mlt_properties_count( properties );
1830 for ( i = 0; i < count; i++ )
1832 const char *opt_name = mlt_properties_get_name( properties, i );
1833 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
1834 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1836 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1838 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1841 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1842 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1843 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1844 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1845 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1846 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1848 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1854 /** Initialize the video codec context.
1857 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1859 // Initialise the codec if necessary
1860 if ( !self->video_codec )
1862 // Get the video stream
1863 AVStream *stream = self->video_format->streams[ index ];
1865 // Get codec context
1866 AVCodecContext *codec_context = stream->codec;
1869 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1871 if ( codec_context->codec_id == CODEC_ID_H264 )
1873 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1875 if ( vdpau_init( self ) )
1877 self->video_codec = codec_context;
1878 if ( !vdpau_decoder_init( self ) )
1883 codec = avcodec_find_decoder( codec_context->codec_id );
1887 // Initialise multi-threading
1888 int thread_count = mlt_properties_get_int( properties, "threads" );
1889 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1890 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1891 if ( thread_count > 1 )
1892 codec_context->thread_count = thread_count;
1894 // If we don't have a codec and we can't initialise it, we can't do much more...
1895 pthread_mutex_lock( &self->open_mutex );
1896 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1897 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1899 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1902 // Now store the codec with its destructor
1903 self->video_codec = codec_context;
1907 // Remember that we can't use this later
1908 self->video_index = -1;
1909 pthread_mutex_unlock( &self->open_mutex );
1912 pthread_mutex_unlock( &self->open_mutex );
1914 // Process properties as AVOptions
1915 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1916 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1917 if ( codec->priv_class && codec_context->priv_data )
1918 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1921 // Reset some image properties
1922 if ( self->video_codec )
1924 mlt_properties_set_int( properties, "width", self->video_codec->width );
1925 mlt_properties_set_int( properties, "height", self->video_codec->height );
1927 // For DV, we'll just use the saved aspect ratio
1928 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1929 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1931 // Determine the fps first from the codec
1932 double source_fps = (double) self->video_codec->time_base.den /
1933 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1936 // If the muxer reports a frame rate different than the codec
1937 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1938 double muxer_fps = av_q2d( stream->avg_frame_rate );
1939 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1940 muxer_fps = av_q2d( stream->r_frame_rate );
1942 double muxer_fps = av_q2d( stream->r_frame_rate );
1944 // Choose the lesser - the wrong tends to be off by some multiple of 10
1945 source_fps = FFMIN( source_fps, muxer_fps );
1946 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1948 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1949 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1951 else if ( muxer_fps > 0 )
1953 AVRational frame_rate = stream->r_frame_rate;
1954 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1955 // avg_frame_rate gives some approximate value that does not well match the media.
1956 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1957 // results in some very choppy output, but some value slightly different works
1959 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1960 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1961 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1963 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1964 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1968 source_fps = mlt_producer_get_fps( self->parent );
1969 AVRational frame_rate = av_d2q( source_fps, 255 );
1970 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1971 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1974 if ( mlt_properties_get( properties, "force_fps" ) )
1976 double source_fps = mlt_properties_get_double( properties, "force_fps" );
1977 AVRational fps = av_d2q( source_fps, 1024 );
1978 stream->time_base.num *= mlt_properties_get_int( properties, "meta.media.frame_rate_num" ) * fps.den;
1979 stream->time_base.den *= mlt_properties_get_int( properties, "meta.media.frame_rate_den" ) * fps.num;
1980 mlt_properties_set_int( properties, "meta.media.frame_rate_num", fps.num );
1981 mlt_properties_set_int( properties, "meta.media.frame_rate_den", fps.den );
1984 // Set the YUV colorspace from override or detect
1985 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1986 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1987 if ( ! self->colorspace )
1989 switch ( self->video_codec->colorspace )
1991 case AVCOL_SPC_SMPTE240M:
1992 self->colorspace = 240;
1994 case AVCOL_SPC_BT470BG:
1995 case AVCOL_SPC_SMPTE170M:
1996 self->colorspace = 601;
1998 case AVCOL_SPC_BT709:
1999 self->colorspace = 709;
2002 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
2003 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
2008 // Let apps get chosen colorspace
2009 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
2011 self->full_luma = -1;
2012 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(72<<8)+2)
2013 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent), "color_range %d\n", codec_context->color_range );
2014 if ( codec_context->color_range == AVCOL_RANGE_JPEG )
2015 self->full_luma = 1;
2017 if ( mlt_properties_get( properties, "set.force_full_luma" ) )
2018 self->full_luma = mlt_properties_get_int( properties, "set.force_full_luma" );
2020 return self->video_codec && self->video_index > -1;
2023 /** Set up video handling.
2026 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
2029 mlt_producer producer = self->parent;
2031 // Get the properties
2032 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2034 // Fetch the video format context
2035 AVFormatContext *context = self->video_format;
2037 // Get the video_index
2038 int index = mlt_properties_get_int( properties, "video_index" );
2040 // Reopen the file if necessary
2041 if ( !context && index > -1 )
2043 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2044 mlt_properties_get( properties, "resource" ), 1 );
2045 context = self->video_format;
2048 // Exception handling for video_index
2049 if ( context && index >= (int) context->nb_streams )
2051 // Get the last video stream
2052 for ( index = context->nb_streams - 1;
2053 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
2055 mlt_properties_set_int( properties, "video_index", index );
2057 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
2059 // Invalidate the video stream
2061 mlt_properties_set_int( properties, "video_index", index );
2064 // Update the video properties if the index changed
2065 if ( index != self->video_index )
2067 // Reset the video properties if the index changed
2068 self->video_index = index;
2069 pthread_mutex_lock( &self->open_mutex );
2070 if ( self->video_codec )
2071 avcodec_close( self->video_codec );
2072 self->video_codec = NULL;
2073 pthread_mutex_unlock( &self->open_mutex );
2076 // Get the frame properties
2077 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2080 if ( context && index > -1 && video_codec_init( self, index, properties ) )
2082 // Set the frame properties
2083 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
2084 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
2085 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
2087 // Set the width and height
2088 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
2089 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
2090 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
2091 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
2092 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
2093 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
2095 // Workaround 1088 encodings missing cropping info.
2096 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
2098 mlt_properties_set_int( properties, "meta.media.height", 1080 );
2101 // Add our image operation
2102 mlt_frame_push_service( frame, self );
2103 mlt_frame_push_get_image( frame, producer_get_image );
2107 // If something failed, use test card image
2108 mlt_properties_set_int( frame_properties, "test_image", 1 );
2112 static int seek_audio( producer_avformat self, mlt_position position, double timecode )
2116 // Seek if necessary
2117 if ( self->seekable && position != self->audio_expected )
2119 if ( position + 1 == self->audio_expected )
2121 // We're paused - silence required
2124 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
2126 AVFormatContext *context = self->audio_format;
2127 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
2128 if ( context->start_time != AV_NOPTS_VALUE )
2129 timestamp += context->start_time;
2130 if ( timestamp < 0 )
2133 // Set to the real timecode
2134 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
2137 // Clear the usage in the audio buffer
2138 int i = MAX_AUDIO_STREAMS + 1;
2140 self->audio_used[i - 1] = 0;
2146 static int sample_bytes( AVCodecContext *context )
2148 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2149 return av_get_bytes_per_sample( context->sample_fmt );
2150 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2151 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2153 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2157 static void planar_to_interleaved( uint8_t *dest, uint8_t *src, int samples, int channels, int bytes_per_sample )
2160 for ( s = 0; s < samples; s++ )
2162 for ( c = 0; c < channels; c++ )
2164 memcpy( dest, src + ( c * samples + s ) * bytes_per_sample, bytes_per_sample );
2165 dest += bytes_per_sample;
2170 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2172 // Fetch the audio_format
2173 AVFormatContext *context = self->audio_format;
2175 // Get the current stream index
2176 int index = pkt.stream_index;
2178 // Get codec context
2179 AVCodecContext *codec_context = self->audio_codec[ index ];
2181 // Obtain the resample context if it exists (not always needed)
2182 ReSampleContext *resample = self->audio_resample[ index ];
2184 // Obtain the audio buffers
2185 uint8_t *audio_buffer = self->audio_buffer[ index ];
2186 uint8_t *decode_buffer = self->decode_buffer[ index ];
2188 int audio_used = self->audio_used[ index ];
2189 uint8_t *ptr = pkt.data;
2193 while ( ptr && ret >= 0 && len > 0 )
2195 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2196 int data_size = self->audio_buffer_size[ index ];
2199 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2200 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2201 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2202 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2204 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2208 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2212 pkt.size = len -= ret;
2213 pkt.data = ptr += ret;
2215 // If decoded successfully
2216 if ( data_size > 0 )
2218 // Figure out how many samples will be needed after resampling
2219 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2220 int samples_needed = self->resample_factor * convert_samples;
2222 // Resize audio buffer to prevent overflow
2223 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2225 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2226 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2230 // Copy to audio buffer while resampling
2231 uint8_t *source = decode_buffer;
2232 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2233 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2237 uint8_t *source = decode_buffer;
2238 uint8_t *dest = &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ];
2239 switch ( codec_context->sample_fmt )
2241 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2242 case AV_SAMPLE_FMT_S16P:
2243 case AV_SAMPLE_FMT_S32P:
2244 case AV_SAMPLE_FMT_FLTP:
2245 planar_to_interleaved( dest, source, convert_samples, codec_context->channels, sizeof_sample );
2249 // Straight copy to audio buffer
2250 memcpy( dest, decode_buffer, data_size );
2252 audio_used += convert_samples;
2256 while ( *ignore && audio_used )
2259 audio_used -= audio_used > samples ? samples : audio_used;
2260 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2261 audio_used * sizeof_sample );
2266 // If we're behind, ignore this packet
2267 // Skip this on non-seekable, audio-only inputs.
2268 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2270 int64_t pts = pkt.pts;
2271 if ( self->first_pts != 0 )
2272 pts -= self->first_pts;
2273 else if ( context->start_time != AV_NOPTS_VALUE )
2274 pts -= context->start_time;
2275 double timebase = av_q2d( context->streams[ index ]->time_base );
2276 int64_t int_position = ( int64_t )( timebase * pts * fps + 0.5 );
2277 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2279 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
2280 "A pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
2281 pkt.pts, pkt.dts, req_position, self->current_position, int_position );
2283 if ( int_position > 0 )
2285 if ( int_position < req_position )
2286 // We are behind, so skip some
2287 *ignore = req_position - int_position;
2288 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2289 // We are ahead, so seek backwards some more
2290 seek_audio( self, req_position, timecode - 1.0 );
2294 self->audio_used[ index ] = audio_used;
2299 /** Get the audio from a frame.
2301 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2304 producer_avformat self = mlt_frame_pop_audio( frame );
2306 pthread_mutex_lock( &self->audio_mutex );
2308 // Obtain the frame number of this frame
2309 mlt_position position = mlt_frame_original_position( frame );
2311 // Calculate the real time code
2312 double real_timecode = producer_time_of_frame( self->parent, position );
2314 // Get the producer fps
2315 double fps = mlt_producer_get_fps( self->parent );
2317 // Number of frames to ignore (for ffwd)
2318 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2320 // Flag for paused (silence)
2321 int paused = seek_audio( self, position, real_timecode );
2323 // Initialize ignore for all streams from the seek return value
2324 int i = MAX_AUDIO_STREAMS;
2326 ignore[i] = ignore[0];
2328 // Fetch the audio_format
2329 AVFormatContext *context = self->audio_format;
2331 int sizeof_sample = sizeof( int16_t );
2333 // Determine the tracks to use
2334 int index = self->audio_index;
2335 int index_max = self->audio_index + 1;
2336 if ( self->audio_index == INT_MAX )
2339 index_max = FFMIN( MAX_AUDIO_STREAMS, context->nb_streams );
2340 *channels = self->total_channels;
2341 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2342 *frequency = FFMAX( self->max_frequency, *frequency );
2345 // Initialize the resamplers and buffers
2346 for ( ; index < index_max && index < MAX_AUDIO_STREAMS; index++ )
2348 // Get codec context
2349 AVCodecContext *codec_context = self->audio_codec[ index ];
2351 if ( codec_context && !self->audio_buffer[ index ] )
2353 #if LIBAVCODEC_VERSION_INT < ((54<<16)+(26<<8)+0)
2354 // Check for resample and create if necessary
2355 if ( codec_context->channels <= 2 )
2357 // Determine by how much resampling will increase number of samples
2358 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2359 resample_factor *= (double) *frequency / codec_context->sample_rate;
2360 if ( resample_factor > self->resample_factor )
2361 self->resample_factor = resample_factor;
2363 // Create the resampler
2364 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2365 self->audio_resample[ index ] = av_audio_resample_init(
2366 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2367 codec_context->channels, *frequency, codec_context->sample_rate,
2368 AV_SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2370 self->audio_resample[ index ] = audio_resample_init(
2371 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2372 codec_context->channels, *frequency, codec_context->sample_rate );
2378 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2379 sizeof_sample = sample_bytes( codec_context );
2382 // Check for audio buffer and create if necessary
2383 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2384 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2386 // Check for decoder buffer and create if necessary
2387 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2391 // Get the audio if required
2392 if ( !paused && *frequency > 0 )
2398 av_init_packet( &pkt );
2400 // If not resampling, give consumer more than requested.
2401 // It requested number samples based on requested frame rate.
2402 // Do not clean this up with a samples *= ...!
2403 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2404 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2406 while ( ret >= 0 && !got_audio )
2408 // Check if the buffer already contains the samples required
2409 if ( self->audio_index != INT_MAX &&
2410 self->audio_used[ self->audio_index ] >= *samples &&
2411 ignore[ self->audio_index ] == 0 )
2416 else if ( self->audio_index == INT_MAX )
2418 // Check if there is enough audio for all streams
2420 for ( index = 0; got_audio && index < index_max; index++ )
2421 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2428 pthread_mutex_lock( &self->packets_mutex );
2429 if ( mlt_deque_count( self->apackets ) )
2431 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2437 ret = av_read_frame( context, &pkt );
2438 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2440 if ( !av_dup_packet( &pkt ) )
2442 AVPacket *tmp = malloc( sizeof(AVPacket) );
2444 mlt_deque_push_back( self->vpackets, tmp );
2448 pthread_mutex_unlock( &self->packets_mutex );
2450 // We only deal with audio from the selected audio index
2451 index = pkt.stream_index;
2452 if ( index < MAX_AUDIO_STREAMS && ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2453 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2455 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2456 self->audio_codec[index]->channels : *channels;
2457 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2460 if ( self->seekable || index != self->video_index )
2461 av_free_packet( &pkt );
2465 // Set some additional return values
2466 *format = mlt_audio_s16;
2467 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2469 index = self->audio_index;
2470 *channels = self->audio_codec[ index ]->channels;
2471 *frequency = self->audio_codec[ index ]->sample_rate;
2472 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2473 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2475 else if ( self->audio_index == INT_MAX )
2477 for ( index = 0; index < index_max; index++ )
2478 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2480 // XXX: This only works if all audio tracks have the same sample format.
2481 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2482 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2487 // Allocate and set the frame's audio buffer
2488 int size = mlt_audio_format_size( *format, *samples, *channels );
2489 *buffer = mlt_pool_alloc( size );
2490 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2492 // Interleave tracks if audio_index=all
2493 if ( self->audio_index == INT_MAX )
2495 uint8_t *dest = *buffer;
2497 for ( i = 0; i < *samples; i++ )
2499 for ( index = 0; index < index_max; index++ )
2500 if ( self->audio_codec[ index ] )
2502 int current_channels = self->audio_codec[ index ]->channels;
2503 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2504 memcpy( dest, src, current_channels * sizeof_sample );
2505 dest += current_channels * sizeof_sample;
2508 for ( index = 0; index < index_max; index++ )
2509 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2511 int current_channels = self->audio_codec[ index ]->channels;
2512 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2513 self->audio_used[index] -= *samples;
2514 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2517 // Copy a single track to the output buffer
2520 index = self->audio_index;
2522 // Now handle the audio if we have enough
2523 if ( self->audio_used[ index ] > 0 )
2525 uint8_t *src = self->audio_buffer[ index ];
2526 // copy samples from audio_buffer
2527 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2528 memcpy( *buffer, src, size * *channels * sizeof_sample );
2529 // supply the remaining requested samples as silence
2530 if ( *samples > self->audio_used[ index ] )
2531 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2532 // reposition the samples within audio_buffer
2533 self->audio_used[ index ] -= size;
2534 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2538 // Otherwise fill with silence
2539 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2545 // Get silence and don't touch the context
2546 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2549 // Regardless of speed (other than paused), we expect to get the next frame
2551 self->audio_expected = position + 1;
2553 pthread_mutex_unlock( &self->audio_mutex );
2558 /** Initialize the audio codec context.
2561 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2563 // Initialise the codec if necessary
2564 if ( !self->audio_codec[ index ] )
2566 // Get codec context
2567 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2570 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2572 // If we don't have a codec and we can't initialise it, we can't do much more...
2573 pthread_mutex_lock( &self->open_mutex );
2574 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2575 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2577 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2580 // Now store the codec with its destructor
2581 if ( self->audio_codec[ index ] )
2582 avcodec_close( self->audio_codec[ index ] );
2583 self->audio_codec[ index ] = codec_context;
2587 // Remember that we can't use self later
2588 self->audio_index = -1;
2590 pthread_mutex_unlock( &self->open_mutex );
2592 // Process properties as AVOptions
2593 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2594 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
2595 if ( codec && codec->priv_class && codec_context->priv_data )
2596 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2599 return self->audio_codec[ index ] && self->audio_index > -1;
2602 /** Set up audio handling.
2605 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2608 mlt_producer producer = self->parent;
2610 // Get the properties
2611 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2613 // Fetch the audio format context
2614 AVFormatContext *context = self->audio_format;
2616 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2618 // Get the audio_index
2619 int index = mlt_properties_get_int( properties, "audio_index" );
2621 // Handle all audio tracks
2622 if ( self->audio_index > -1 &&
2623 mlt_properties_get( properties, "audio_index" ) &&
2624 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2627 // Reopen the file if necessary
2628 if ( !context && self->audio_index > -1 && index > -1 )
2630 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2631 mlt_properties_get( properties, "resource" ), 1 );
2632 context = self->audio_format;
2635 // Exception handling for audio_index
2636 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2638 for ( index = context->nb_streams - 1;
2639 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2641 mlt_properties_set_int( properties, "audio_index", index );
2643 if ( context && index > -1 && index < INT_MAX &&
2644 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2646 index = self->audio_index;
2647 mlt_properties_set_int( properties, "audio_index", index );
2650 // Update the audio properties if the index changed
2651 if ( context && index > -1 && index != self->audio_index )
2653 pthread_mutex_lock( &self->open_mutex );
2654 if ( self->audio_codec[ self->audio_index ] )
2655 avcodec_close( self->audio_codec[ self->audio_index ] );
2656 self->audio_codec[ self->audio_index ] = NULL;
2657 pthread_mutex_unlock( &self->open_mutex );
2659 if ( self->audio_index != -1 )
2660 self->audio_index = index;
2665 if ( context && index == INT_MAX )
2667 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2668 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2669 for ( index = 0; index < context->nb_streams; index++ )
2671 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2672 audio_codec_init( self, index, properties );
2675 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2677 // Set the frame properties
2678 if ( index < MAX_AUDIO_STREAMS )
2680 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2681 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2684 if ( context && index > -1 )
2686 // Add our audio operation
2687 mlt_frame_push_audio( frame, self );
2688 mlt_frame_push_audio( frame, producer_get_audio );
2692 /** Our get frame implementation.
2695 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2697 // Access the private data
2698 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2699 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2700 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2705 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2706 producer->child = self;
2707 self->parent = producer;
2708 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2709 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2712 // Create an empty frame
2713 *frame = mlt_frame_init( service);
2717 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2721 mlt_cache_item_close( cache_item );
2725 // Update timecode on the frame we're creating
2726 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2729 producer_set_up_video( self, *frame );
2732 producer_set_up_audio( self, *frame );
2734 // Set the position of this producer
2735 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2736 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "original_position", position );
2738 // Calculate the next timecode
2739 mlt_producer_prepare_next( producer );
2744 static void producer_avformat_close( producer_avformat self )
2746 mlt_log_debug( NULL, "producer_avformat_close\n" );
2748 // Cleanup av contexts
2749 av_free_packet( &self->pkt );
2750 av_free( self->av_frame );
2751 pthread_mutex_lock( &self->open_mutex );
2753 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2755 if ( self->audio_resample[i] )
2756 audio_resample_close( self->audio_resample[i] );
2757 mlt_pool_release( self->audio_buffer[i] );
2758 av_free( self->decode_buffer[i] );
2759 if ( self->audio_codec[i] )
2760 avcodec_close( self->audio_codec[i] );
2761 self->audio_codec[i] = NULL;
2763 if ( self->video_codec )
2764 avcodec_close( self->video_codec );
2765 self->video_codec = NULL;
2767 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2768 if ( self->dummy_context )
2769 avformat_close_input( &self->dummy_context );
2770 if ( self->seekable && self->audio_format )
2771 avformat_close_input( &self->audio_format );
2772 if ( self->video_format )
2773 avformat_close_input( &self->video_format );
2775 if ( self->dummy_context )
2776 av_close_input_file( self->dummy_context );
2777 if ( self->seekable && self->audio_format )
2778 av_close_input_file( self->audio_format );
2779 if ( self->video_format )
2780 av_close_input_file( self->video_format );
2782 pthread_mutex_unlock( &self->open_mutex );
2784 vdpau_producer_close( self );
2786 if ( self->image_cache )
2787 mlt_cache_close( self->image_cache );
2789 // Cleanup the mutexes
2790 pthread_mutex_destroy( &self->audio_mutex );
2791 pthread_mutex_destroy( &self->video_mutex );
2792 pthread_mutex_destroy( &self->packets_mutex );
2793 pthread_mutex_destroy( &self->open_mutex );
2795 // Cleanup the packet queues
2797 if ( self->apackets )
2799 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2801 av_free_packet( pkt );
2804 mlt_deque_close( self->apackets );
2805 self->apackets = NULL;
2807 if ( self->vpackets )
2809 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2811 av_free_packet( pkt );
2814 mlt_deque_close( self->vpackets );
2815 self->vpackets = NULL;
2821 static void producer_close( mlt_producer parent )
2823 // Remove this instance from the cache
2824 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2827 parent->close = NULL;
2828 mlt_producer_close( parent );