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;
132 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
146 typedef struct producer_avformat_s *producer_avformat;
148 // Forward references.
149 static int list_components( char* file );
150 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock );
151 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
152 static void producer_avformat_close( producer_avformat );
153 static void producer_close( mlt_producer parent );
154 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
155 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
156 static void apply_properties( void *obj, mlt_properties properties, int flags );
157 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
158 static void get_audio_streams_info( producer_avformat self );
164 /** Constructor for libavformat.
167 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
169 if ( list_components( file ) )
172 mlt_producer producer = NULL;
174 // Check that we have a non-NULL argument
177 // Construct the producer
178 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
179 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
182 if ( mlt_producer_init( producer, self ) == 0 )
184 self->parent = producer;
186 // Get the properties
187 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
189 // Set the resource property (required for all producers)
190 mlt_properties_set( properties, "resource", file );
192 // Register transport implementation with the producer
193 producer->close = (mlt_destructor) producer_close;
195 // Register our get_frame implementation
196 producer->get_frame = producer_get_frame;
198 if ( strcmp( service, "avformat-novalidate" ) )
201 if ( producer_open( self, profile, file, 1 ) != 0 )
204 mlt_producer_close( producer );
206 producer_avformat_close( self );
208 else if ( self->seekable )
210 // Close the file to release resources for large playlists - reopen later as needed
211 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
212 if ( self->audio_format )
213 avformat_close_input( &self->audio_format );
214 if ( self->video_format )
215 avformat_close_input( &self->video_format );
217 if ( self->audio_format )
218 av_close_input_file( self->audio_format );
219 if ( self->video_format )
220 av_close_input_file( self->video_format );
222 self->audio_format = NULL;
223 self->video_format = NULL;
228 // Default the user-selectable indices from the auto-detected indices
229 mlt_properties_set_int( properties, "audio_index", self->audio_index );
230 mlt_properties_set_int( properties, "video_index", self->video_index );
232 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
234 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
241 int list_components( char* file )
245 // Report information about available demuxers and codecs as YAML Tiny
246 if ( file && strstr( file, "f-list" ) )
248 fprintf( stderr, "---\nformats:\n" );
249 AVInputFormat *format = NULL;
250 while ( ( format = av_iformat_next( format ) ) )
251 fprintf( stderr, " - %s\n", format->name );
252 fprintf( stderr, "...\n" );
255 if ( file && strstr( file, "acodec-list" ) )
257 fprintf( stderr, "---\naudio_codecs:\n" );
258 AVCodec *codec = NULL;
259 while ( ( codec = av_codec_next( codec ) ) )
260 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
261 fprintf( stderr, " - %s\n", codec->name );
262 fprintf( stderr, "...\n" );
265 if ( file && strstr( file, "vcodec-list" ) )
267 fprintf( stderr, "---\nvideo_codecs:\n" );
268 AVCodec *codec = NULL;
269 while ( ( codec = av_codec_next( codec ) ) )
270 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
271 fprintf( stderr, " - %s\n", codec->name );
272 fprintf( stderr, "...\n" );
279 /** Find the default streams.
282 static mlt_properties find_default_streams( producer_avformat self )
286 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
287 AVDictionaryEntry *tag = NULL;
289 AVMetadataTag *tag = NULL;
291 AVFormatContext *context = self->video_format;
292 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
294 // Default to the first audio and video streams found
295 self->audio_index = -1;
296 self->video_index = -1;
298 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
300 // Allow for multiple audio and video streams in the file and select first of each (if available)
301 for( i = 0; i < context->nb_streams; i++ )
303 // Get the codec context
304 AVStream *stream = context->streams[ i ];
305 if ( ! stream ) continue;
306 AVCodecContext *codec_context = stream->codec;
307 if ( ! codec_context ) continue;
308 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
309 if ( ! codec ) continue;
311 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
313 // Determine the type and obtain the first index of each type
314 switch( codec_context->codec_type )
316 case CODEC_TYPE_VIDEO:
317 // Use first video stream
318 if ( self->video_index < 0 )
319 self->video_index = i;
320 mlt_properties_set( meta_media, key, "video" );
321 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
322 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
323 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
324 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
325 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
326 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
328 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
331 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
332 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
333 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
335 snprintf( key, sizeof(key), "meta.media.%d.codec.width", i );
336 mlt_properties_set_int( meta_media, key, codec_context->width );
337 snprintf( key, sizeof(key), "meta.media.%d.codec.height", i );
338 mlt_properties_set_int( meta_media, key, codec_context->height );
339 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
340 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
341 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
342 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
343 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(3<<8)+0)
344 mlt_properties_set( meta_media, key, av_get_pix_fmt_name( codec_context->pix_fmt ) );
346 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
348 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
349 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
350 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
351 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
352 switch ( codec_context->colorspace )
354 case AVCOL_SPC_SMPTE240M:
355 mlt_properties_set_int( meta_media, key, 240 );
357 case AVCOL_SPC_BT470BG:
358 case AVCOL_SPC_SMPTE170M:
359 mlt_properties_set_int( meta_media, key, 601 );
361 case AVCOL_SPC_BT709:
362 mlt_properties_set_int( meta_media, key, 709 );
365 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
366 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
371 case CODEC_TYPE_AUDIO:
372 if ( !codec_context->channels )
374 // Use first audio stream
375 if ( self->audio_index < 0 )
376 self->audio_index = i;
377 mlt_properties_set( meta_media, key, "audio" );
378 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
379 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
380 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
381 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
382 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
383 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
385 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
386 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
387 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
388 mlt_properties_set_int( meta_media, key, codec_context->channels );
393 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
394 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
395 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
396 mlt_properties_set( meta_media, key, codec->name );
397 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
398 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
399 mlt_properties_set( meta_media, key, codec->long_name );
401 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
402 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
403 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
404 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
405 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
406 // mlt_properties_set_int( meta_media, key, codec_context->profile );
407 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
408 // mlt_properties_set_int( meta_media, key, codec_context->level );
411 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
412 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
413 while ( ( tag = av_dict_get( stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
415 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
418 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
420 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
421 mlt_properties_set( meta_media, key, tag->value );
426 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
427 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
428 while ( ( tag = av_dict_get( context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
430 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
433 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
435 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
436 mlt_properties_set( meta_media, key, tag->value );
440 if ( context->title && strcmp( context->title, "" ) )
441 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
442 if ( context->author && strcmp( context->author, "" ) )
443 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
444 if ( context->copyright && strcmp( context->copyright, "" ) )
445 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
446 if ( context->comment )
447 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
448 if ( context->album )
449 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
451 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
452 if ( context->track )
453 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
459 static inline int dv_is_pal( AVPacket *pkt )
461 return pkt->data[3] & 0x80;
464 static int dv_is_wide( AVPacket *pkt )
466 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
468 for ( ; i < pkt->size; i += 5 /* packet size */ )
470 if ( pkt->data[ i ] == 0x61 )
472 uint8_t x = pkt->data[ i + 2 ] & 0x7;
473 return ( x == 2 ) || ( x == 7 );
479 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
481 double aspect_ratio = 1.0;
483 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
487 if ( dv_is_pal( pkt ) )
489 if ( dv_is_wide( pkt ) )
491 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
492 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
496 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
497 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
502 if ( dv_is_wide( pkt ) )
504 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
505 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
509 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
510 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
517 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
518 stream->sample_aspect_ratio;
520 codec_context->sample_aspect_ratio;
522 // Override FFmpeg's notion of DV aspect ratios, which are
523 // based upon a width of 704. Since we do not have a normaliser
524 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
525 // we just coerce the values to facilitate a passive behaviour through
526 // the rescale normaliser when using equivalent producers and consumers.
527 // = display_aspect / (width * height)
528 if ( ar.num == 10 && ar.den == 11 )
531 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
532 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
534 else if ( ar.num == 59 && ar.den == 54 )
537 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
538 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
540 else if ( ar.num == 40 && ar.den == 33 )
543 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
544 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
546 else if ( ar.num == 118 && ar.den == 81 )
549 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
550 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
556 AVRational codec_sar = codec_context->sample_aspect_ratio;
557 AVRational stream_sar =
558 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
559 stream->sample_aspect_ratio;
563 if ( codec_sar.num > 0 )
565 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
566 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
568 else if ( stream_sar.num > 0 )
570 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
571 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
575 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
576 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
579 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
580 aspect_ratio = av_q2d( ar );
581 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
586 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
587 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVDictionary **params )
589 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
592 if ( !URL ) return NULL;
595 char *protocol = strdup( URL );
596 char *url = strchr( protocol, ':' );
598 // Only if there is not a protocol specification that avformat can handle
599 #if LIBAVFORMAT_VERSION_MAJOR >= 53
600 if ( url && avio_check( URL, 0 ) < 0 )
602 if ( url && !url_exist( URL ) )
605 // Truncate protocol string
607 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
610 *format = av_find_input_format( protocol );
612 // Eat the format designator
617 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
618 // support for legacy width and height parameters
622 // These are required by video4linux2 (defaults)
623 params->width = profile->width;
624 params->height = profile->height;
625 if ( !strstr( URL, "&frame_rate" ) )
626 params->time_base = (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
627 params->channels = 2;
628 params->sample_rate = 48000;
632 url = strchr( url, '?' );
636 char *name = strdup( ++url );
637 char *value = strchr( name, '=' );
639 // Also accept : as delimiter for backwards compatibility.
640 value = strchr( name, ':' );
645 char *t = strchr( value, '&' );
648 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
649 // translate old parameters to new av_dict names
650 if ( !strcmp( name, "frame_rate" ) )
651 av_dict_set( params, "framerate", value, 0 );
652 else if ( !strcmp( name, "pix_fmt" ) )
653 av_dict_set( params, "pixel_format", value, 0 );
654 else if ( !strcmp( name, "width" ) )
655 width = strdup( value );
656 else if ( !strcmp( name, "height" ) )
657 height = strdup( value );
659 // generic demux/device option support
660 av_dict_set( params, name, value, 0 );
662 if ( !strcmp( name, "frame_rate" ) )
663 params->time_base.den = atoi( value );
664 else if ( !strcmp( name, "frame_rate_base" ) )
665 params->time_base.num = atoi( value );
666 else if ( !strcmp( name, "sample_rate" ) )
667 params->sample_rate = atoi( value );
668 else if ( !strcmp( name, "channel" ) )
669 params->channel = atoi( value );
670 else if ( !strcmp( name, "channels" ) )
671 params->channels = atoi( value );
672 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
673 else if ( !strcmp( name, "pix_fmt" ) )
674 params->pix_fmt = av_get_pix_fmt( value );
676 else if ( !strcmp( name, "width" ) )
677 params->width = atoi( value );
678 else if ( !strcmp( name, "height" ) )
679 params->height = atoi( value );
680 else if ( !strcmp( name, "standard" ) )
681 params->standard = strdup( value );
685 url = strchr( url, '&' );
687 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
688 // continued support for legacy width and height parameters
689 if ( width && height )
691 char *s = malloc( strlen( width ) + strlen( height ) + 2 );
695 av_dict_set( params, "video_size", s, 0 );
698 if ( width ) free( width );
699 if ( height ) free ( height );
702 result = strdup( result );
706 result = strdup( URL );
712 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
716 // Get the properties
717 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
719 AVFormatContext *format = self->video_format;
721 // We will treat everything with the producer fps.
722 // TODO: make this more flexible.
723 double fps = mlt_profile_fps( profile );
726 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
728 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
729 // when producer_open is called after initial call when restoring or reseting the producer.
730 if ( format->duration != AV_NOPTS_VALUE )
732 // This isn't going to be accurate for all formats
733 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
734 mlt_properties_set_position( properties, "out", frames - 1 );
735 mlt_properties_set_position( properties, "length", frames );
736 mlt_properties_set_int( properties, "_length_computed", 1 );
740 // Set live sources to run forever
741 mlt_properties_set_position( properties, "length", INT_MAX );
742 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
743 mlt_properties_set( properties, "eof", "loop" );
744 mlt_properties_set_int( properties, "_length_computed", 1 );
748 // Check if we're seekable
749 // avdevices are typically AVFMT_NOFILE and not seekable
750 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
753 // protocols can indicate if they support seeking
754 #if LIBAVFORMAT_VERSION_MAJOR >= 53
755 self->seekable = format->pb->seekable;
757 URLContext *uc = url_fileno( format->pb );
759 self->seekable = !uc->is_streamed;
762 if ( self->seekable )
764 // Do a more rigourous test of seekable on a disposable context
765 self->seekable = av_seek_frame( format, -1, format->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
766 mlt_properties_set_int( properties, "seekable", self->seekable );
767 self->dummy_context = format;
768 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
769 self->video_format = NULL;
770 avformat_open_input( &self->video_format, filename, NULL, NULL );
771 avformat_find_stream_info( self->video_format, NULL );
773 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
774 av_find_stream_info( self->video_format );
776 format = self->video_format;
779 // Fetch the width, height and aspect ratio
780 if ( self->video_index != -1 )
782 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
783 mlt_properties_set_int( properties, "width", codec_context->width );
784 mlt_properties_set_int( properties, "height", codec_context->height );
786 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
788 // Fetch the first frame of DV so we can read it directly
793 ret = av_read_frame( format, &pkt );
794 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
796 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
797 av_free_packet(&pkt);
801 av_free_packet(&pkt);
806 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
810 // Verify that we can convert this to YUV 4:2:2
811 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
812 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
813 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
815 sws_freeContext( context );
826 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
828 // Return an error code (0 == no error)
830 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
835 if ( !self->is_mutex_init )
837 pthread_mutex_init( &self->audio_mutex, NULL );
838 pthread_mutex_init( &self->video_mutex, NULL );
839 pthread_mutex_init( &self->packets_mutex, NULL );
840 pthread_mutex_init( &self->open_mutex, NULL );
841 self->is_mutex_init = 1;
843 pthread_mutex_lock( &self->audio_mutex );
844 pthread_mutex_lock( &self->video_mutex );
846 mlt_events_block( properties, self->parent );
849 AVInputFormat *format = NULL;
850 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
851 AVDictionary *params = NULL;
853 AVFormatParameters params;
854 memset( ¶ms, 0, sizeof(params) );
856 char *filename = parse_url( profile, URL, &format, ¶ms );
858 // Now attempt to open the file or device with filename
859 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
860 error = avformat_open_input( &self->video_format, filename, format, ¶ms ) < 0;
862 // If the URL is a network stream URL, then we probably need to open with full URL
863 error = avformat_open_input( &self->video_format, URL, format, ¶ms ) < 0;
865 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
867 // If the URL is a network stream URL, then we probably need to open with full URL
868 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
871 // Set MLT properties onto video AVFormatContext
872 if ( !error && self->video_format )
874 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
875 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
876 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
877 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
881 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
882 av_dict_free( ¶ms );
884 // Cleanup AVFormatParameters
885 if ( params.standard )
886 free( (void*) params.standard );
889 // If successful, then try to get additional info
890 if ( !error && self->video_format )
892 // Get the stream info
893 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
894 error = avformat_find_stream_info( self->video_format, NULL ) < 0;
896 error = av_find_stream_info( self->video_format ) < 0;
899 // Continue if no error
900 if ( !error && self->video_format )
902 // Find default audio and video streams
903 find_default_streams( self );
904 error = get_basic_info( self, profile, filename );
906 // Initialize position info
907 self->first_pts = AV_NOPTS_VALUE;
908 self->last_position = POSITION_INITIAL;
910 if ( !self->audio_format )
912 // We're going to cheat here - for seekable A/V files, we will have separate contexts
913 // to support independent seeking of audio from video.
914 // TODO: Is this really necessary?
915 if ( self->audio_index != -1 && self->video_index != -1 )
917 if ( self->seekable )
919 // And open again for our audio context
920 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
921 avformat_open_input( &self->audio_format, filename, NULL, NULL );
922 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
923 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
924 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
925 avformat_find_stream_info( self->audio_format, NULL );
927 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
928 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
929 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
930 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
931 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
933 av_find_stream_info( self->audio_format );
938 self->audio_format = self->video_format;
941 else if ( self->audio_index != -1 )
943 // We only have an audio context
944 self->audio_format = self->video_format;
945 self->video_format = NULL;
947 else if ( self->video_index == -1 )
949 // Something has gone wrong
952 if ( self->audio_format && !self->audio_streams )
953 get_audio_streams_info( self );
961 self->apackets = mlt_deque_init();
962 self->vpackets = mlt_deque_init();
965 if ( self->dummy_context )
967 pthread_mutex_lock( &self->open_mutex );
968 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
969 avformat_close_input( &self->dummy_context );
971 av_close_input_file( self->dummy_context );
973 self->dummy_context = NULL;
974 pthread_mutex_unlock( &self->open_mutex );
977 // Unlock the service
980 pthread_mutex_unlock( &self->audio_mutex );
981 pthread_mutex_unlock( &self->video_mutex );
983 mlt_events_unblock( properties, self->parent );
988 static void reopen_video( producer_avformat self, mlt_producer producer )
990 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
991 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
992 pthread_mutex_lock( &self->audio_mutex );
993 pthread_mutex_lock( &self->open_mutex );
995 if ( self->video_codec )
996 avcodec_close( self->video_codec );
997 self->video_codec = NULL;
998 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
999 if ( self->dummy_context )
1000 avformat_close_input( &self->dummy_context );
1001 if ( self->video_format )
1002 avformat_close_input( &self->video_format );
1004 if ( self->dummy_context )
1005 av_close_input_file( self->dummy_context );
1006 if ( self->video_format )
1007 av_close_input_file( self->video_format );
1009 self->dummy_context = NULL;
1010 self->video_format = NULL;
1011 pthread_mutex_unlock( &self->open_mutex );
1013 int audio_index = self->audio_index;
1014 int video_index = self->video_index;
1016 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1017 mlt_properties_get( properties, "resource" ), 0 );
1019 self->audio_index = audio_index;
1020 if ( self->video_format && video_index > -1 )
1022 self->video_index = video_index;
1023 video_codec_init( self, video_index, properties );
1026 pthread_mutex_unlock( &self->audio_mutex );
1027 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1030 static int64_t best_pts( producer_avformat self, int64_t pts, int64_t dts )
1032 self->invalid_pts_counter += pts == AV_NOPTS_VALUE;
1033 self->invalid_dts_counter += dts == AV_NOPTS_VALUE;
1034 if ( ( self->invalid_pts_counter <= self->invalid_dts_counter
1035 || dts == AV_NOPTS_VALUE ) && pts != AV_NOPTS_VALUE )
1041 static int seek_video( producer_avformat self, mlt_position position,
1042 int64_t req_position, int preseek )
1044 mlt_producer producer = self->parent;
1047 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
1049 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1051 // Fetch the video format context
1052 AVFormatContext *context = self->video_format;
1054 // Get the video stream
1055 AVStream *stream = context->streams[ self->video_index ];
1057 // Get codec context
1058 AVCodecContext *codec_context = stream->codec;
1060 // We may want to use the source fps if available
1061 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1062 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1065 if ( self->last_position == POSITION_INITIAL )
1071 while ( ret >= 0 && toscan-- > 0 )
1073 ret = av_read_frame( context, &pkt );
1074 if ( ret >= 0 && pkt.stream_index == self->video_index && ( pkt.flags & PKT_FLAG_KEY ) )
1076 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1077 "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n",
1078 pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
1079 self->first_pts = best_pts( self, pkt.pts, pkt.dts );
1080 if ( self->first_pts != AV_NOPTS_VALUE )
1083 av_free_packet( &pkt );
1085 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1088 if ( self->av_frame && position + 1 == self->video_expected )
1090 // We're paused - use last image
1093 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
1095 // Calculate the timestamp for the requested frame
1096 int64_t timestamp = req_position / ( av_q2d( stream->time_base ) * source_fps );
1097 if ( req_position <= 0 )
1099 else if ( self->first_pts != AV_NOPTS_VALUE )
1100 timestamp += self->first_pts;
1101 else if ( context->start_time != AV_NOPTS_VALUE )
1102 timestamp += context->start_time;
1103 if ( preseek && av_q2d( stream->time_base ) != 0 )
1104 timestamp -= 2 / av_q2d( stream->time_base );
1105 if ( timestamp < 0 )
1107 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
1108 timestamp, position, self->video_expected, self->last_position );
1110 // Seek to the timestamp
1111 // NOTE: reopen_video is disabled at this time because it is causing trouble with A/V sync.
1112 if ( 1 || req_position > 0 || self->last_position <= 0 )
1114 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1115 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1117 // flush any pictures still in decode buffer
1118 avcodec_flush_buffers( codec_context );
1122 // Re-open video stream when rewinding to beginning from somewhere else.
1123 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1124 // not reliably seeking to the first frame across formats.
1125 reopen_video( self, producer );
1128 // Remove the cached info relating to the previous position
1129 self->current_position = POSITION_INVALID;
1130 self->last_position = POSITION_INVALID;
1131 av_freep( &self->av_frame );
1137 /** Convert a frame position to a time code.
1140 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1142 return ( double )position / mlt_producer_get_fps( producer );
1145 // Collect information about all audio streams
1147 static void get_audio_streams_info( producer_avformat self )
1149 // Fetch the audio format context
1150 AVFormatContext *context = self->audio_format;
1154 i < context->nb_streams;
1157 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1159 AVCodecContext *codec_context = context->streams[i]->codec;
1160 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1162 // If we don't have a codec and we can't initialise it, we can't do much more...
1163 pthread_mutex_lock( &self->open_mutex );
1164 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1165 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1167 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1170 self->audio_streams++;
1171 self->audio_max_stream = i;
1172 self->total_channels += codec_context->channels;
1173 if ( codec_context->channels > self->max_channel )
1174 self->max_channel = codec_context->channels;
1175 if ( codec_context->sample_rate > self->max_frequency )
1176 self->max_frequency = codec_context->sample_rate;
1177 avcodec_close( codec_context );
1179 pthread_mutex_unlock( &self->open_mutex );
1182 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1183 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1185 // Other audio-specific initializations
1186 self->resample_factor = 1.0;
1189 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1191 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1193 const int *new_coefficients;
1195 int brightness, contrast, saturation;
1197 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1198 &brightness, &contrast, &saturation ) != -1 )
1200 // Don't change these from defaults unless explicitly told to.
1201 if ( use_full_range >= 0 )
1202 full_range = use_full_range;
1203 switch ( colorspace )
1209 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1212 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1215 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1218 new_coefficients = coefficients;
1221 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1222 brightness, contrast, saturation );
1227 static mlt_image_format pick_pix_format( enum PixelFormat pix_fmt )
1235 return mlt_image_rgb24a;
1236 case PIX_FMT_YUV420P:
1237 case PIX_FMT_YUVJ420P:
1238 case PIX_FMT_YUVA420P:
1239 return mlt_image_yuv420p;
1243 case PIX_FMT_MONOWHITE:
1244 case PIX_FMT_MONOBLACK:
1247 return mlt_image_rgb24;
1249 return mlt_image_yuv422;
1253 static mlt_audio_format pick_audio_format( int sample_fmt )
1255 switch ( sample_fmt )
1258 case AV_SAMPLE_FMT_S16:
1259 return mlt_audio_s16;
1260 case AV_SAMPLE_FMT_S32:
1261 return mlt_audio_s32le;
1262 case AV_SAMPLE_FMT_FLT:
1263 return mlt_audio_f32le;
1264 // planar - this producer converts planar to interleaved
1265 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1266 case AV_SAMPLE_FMT_S16P:
1267 return mlt_audio_s16;
1268 case AV_SAMPLE_FMT_S32P:
1269 return mlt_audio_s32le;
1270 case AV_SAMPLE_FMT_FLTP:
1271 return mlt_audio_f32le;
1274 return mlt_audio_none;
1278 static void convert_image( producer_avformat self, AVFrame *frame, uint8_t *buffer, int pix_fmt,
1279 mlt_image_format *format, int width, int height, uint8_t **alpha )
1282 int flags = SWS_BICUBIC | SWS_ACCURATE_RND;
1285 flags |= SWS_CPU_CAPS_MMX;
1288 flags |= SWS_CPU_CAPS_MMX2;
1291 // extract alpha from planar formats
1292 if ( ( pix_fmt == PIX_FMT_YUVA420P
1293 #if defined(FFUDIV) && LIBAVUTIL_VERSION_INT >= ((51<<16)+(35<<8)+101)
1294 || pix_fmt == PIX_FMT_YUVA444P
1297 *format != mlt_image_rgb24a && *format != mlt_image_opengl &&
1298 frame->data[3] && frame->linesize[3] )
1303 dst = *alpha = mlt_pool_alloc( width * height );
1304 src = frame->data[3];
1306 for ( i = 0; i < height; dst += width, src += frame->linesize[3], i++ )
1307 memcpy( dst, src, FFMIN( width, frame->linesize[3] ) );
1310 if ( *format == mlt_image_yuv420p )
1312 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1313 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1315 output.data[0] = buffer;
1316 output.data[1] = buffer + width * height;
1317 output.data[2] = buffer + ( 5 * width * height ) / 4;
1318 output.linesize[0] = width;
1319 output.linesize[1] = width >> 1;
1320 output.linesize[2] = width >> 1;
1321 set_luma_transfer( context, self->colorspace, -1 );
1322 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1323 output.data, output.linesize);
1324 sws_freeContext( context );
1326 else if ( *format == mlt_image_rgb24 )
1328 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1329 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1331 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1332 set_luma_transfer( context, self->colorspace, self->full_luma );
1333 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1334 output.data, output.linesize);
1335 sws_freeContext( context );
1337 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1339 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1340 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1342 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1343 set_luma_transfer( context, self->colorspace, self->full_luma );
1344 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1345 output.data, output.linesize);
1346 sws_freeContext( context );
1350 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1351 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1353 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1354 set_luma_transfer( context, self->colorspace, -1 );
1355 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1356 output.data, output.linesize);
1357 sws_freeContext( context );
1360 if ( *format == mlt_image_yuv420p )
1363 pict.data[0] = buffer;
1364 pict.data[1] = buffer + width * height;
1365 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1366 pict.linesize[0] = width;
1367 pict.linesize[1] = width >> 1;
1368 pict.linesize[2] = width >> 1;
1369 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1371 else if ( *format == mlt_image_rgb24 )
1374 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1375 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1377 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1380 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1381 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1386 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1387 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1392 /** Allocate the image buffer and set it on the frame.
1395 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1399 if ( codec_context->width == 0 || codec_context->height == 0 )
1401 *width = codec_context->width;
1402 *height = codec_context->height;
1403 size = mlt_image_format_size( *format, *width, *height, NULL );
1404 *buffer = mlt_pool_alloc( size );
1406 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1413 /** Get an image from a frame.
1416 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1419 producer_avformat self = mlt_frame_pop_service( frame );
1420 mlt_producer producer = self->parent;
1422 // Get the properties from the frame
1423 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1425 // Obtain the frame number of this frame
1426 mlt_position position = mlt_frame_original_position( frame );
1428 // Get the producer properties
1429 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1431 pthread_mutex_lock( &self->video_mutex );
1433 // Fetch the video format context
1434 AVFormatContext *context = self->video_format;
1436 // Get the video stream
1437 AVStream *stream = context->streams[ self->video_index ];
1439 // Get codec context
1440 AVCodecContext *codec_context = stream->codec;
1442 uint8_t *alpha = NULL;
1443 int got_picture = 0;
1446 // Get the image cache
1447 if ( ! self->image_cache )
1449 // if cache size supplied by environment variable
1450 int cache_supplied = getenv( "MLT_AVFORMAT_CACHE" ) != NULL;
1451 int cache_size = cache_supplied? atoi( getenv( "MLT_AVFORMAT_CACHE" ) ) : 0;
1453 // cache size supplied via property
1454 if ( mlt_properties_get( properties, "cache" ) )
1457 cache_size = mlt_properties_get_int( properties, "cache" );
1459 if ( mlt_properties_get_int( properties, "noimagecache" ) )
1461 // create cache if not disabled
1462 if ( !cache_supplied || cache_size > 0 )
1463 self->image_cache = mlt_cache_init();
1464 // set cache size if supplied
1465 if ( self->image_cache && cache_supplied )
1466 mlt_cache_set_size( self->image_cache, cache_size );
1468 if ( self->image_cache )
1470 mlt_frame original = mlt_cache_get_frame( self->image_cache, position );
1473 mlt_properties orig_props = MLT_FRAME_PROPERTIES( original );
1476 *buffer = mlt_properties_get_data( orig_props, "alpha", &size );
1478 mlt_frame_set_alpha( frame, *buffer, size, NULL );
1479 *buffer = mlt_properties_get_data( orig_props, "image", &size );
1480 mlt_frame_set_image( frame, *buffer, size, NULL );
1481 mlt_properties_set_data( frame_properties, "avformat.image_cache", original, 0, (mlt_destructor) mlt_frame_close, NULL );
1482 *format = mlt_properties_get_int( orig_props, "format" );
1484 // Set the resolution
1485 *width = codec_context->width;
1486 *height = codec_context->height;
1488 // Workaround 1088 encodings missing cropping info.
1489 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1493 goto exit_get_image;
1498 // We may want to use the source fps if available
1499 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1500 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1502 // This is the physical frame position in the source
1503 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1505 // Determines if we have to decode all frames in a sequence
1506 // Temporary hack to improve intra frame only
1507 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1508 strcmp( codec_context->codec->name, "dnxhd" ) &&
1509 strcmp( codec_context->codec->name, "dvvideo" ) &&
1510 strcmp( codec_context->codec->name, "huffyuv" ) &&
1511 strcmp( codec_context->codec->name, "mjpeg" ) &&
1512 strcmp( codec_context->codec->name, "rawvideo" ) );
1514 double delay = mlt_properties_get_double( properties, "video_delay" );
1516 // Seek if necessary
1517 const char *interp = mlt_properties_get( frame_properties, "rescale.interp" );
1518 int preseek = must_decode
1519 #if defined(FFUDIV) && LIBAVFORMAT_VERSION_INT >= ((53<<16)+(24<<8)+2)
1520 && ( interp && strcmp( interp, "nearest" ) )
1522 && codec_context->has_b_frames;
1523 int paused = seek_video( self, position, req_position, preseek );
1525 // Seek might have reopened the file
1526 context = self->video_format;
1527 stream = context->streams[ self->video_index ];
1528 codec_context = stream->codec;
1529 if ( *format == mlt_image_none ||
1530 codec_context->pix_fmt == PIX_FMT_ARGB ||
1531 codec_context->pix_fmt == PIX_FMT_RGBA ||
1532 codec_context->pix_fmt == PIX_FMT_ABGR ||
1533 codec_context->pix_fmt == PIX_FMT_BGRA )
1534 *format = pick_pix_format( codec_context->pix_fmt );
1536 // Duplicate the last image if necessary
1537 if ( self->av_frame && self->av_frame->linesize[0]
1538 && ( paused || self->current_position >= req_position ) )
1541 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1543 // Workaround 1088 encodings missing cropping info.
1544 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1547 if ( self->vdpau && self->vdpau->buffer )
1550 picture.data[0] = self->vdpau->buffer;
1551 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1552 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1553 picture.linesize[0] = codec_context->width;
1554 picture.linesize[1] = codec_context->width / 2;
1555 picture.linesize[2] = codec_context->width / 2;
1556 convert_image( self, (AVFrame*) &picture, *buffer,
1557 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1561 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1562 format, *width, *height, &alpha );
1569 int64_t int_position = 0;
1570 int decode_errors = 0;
1572 // Construct an AVFrame for YUV422 conversion
1573 if ( !self->av_frame )
1574 self->av_frame = avcodec_alloc_frame( );
1576 while( ret >= 0 && !got_picture )
1579 if ( self->pkt.stream_index == self->video_index )
1580 av_free_packet( &self->pkt );
1581 av_init_packet( &self->pkt );
1582 pthread_mutex_lock( &self->packets_mutex );
1583 if ( mlt_deque_count( self->vpackets ) )
1585 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1591 ret = av_read_frame( context, &self->pkt );
1592 if ( ret >= 0 && !self->seekable && self->pkt.stream_index == self->audio_index )
1594 if ( !av_dup_packet( &self->pkt ) )
1596 AVPacket *tmp = malloc( sizeof(AVPacket) );
1598 mlt_deque_push_back( self->apackets, tmp );
1602 pthread_mutex_unlock( &self->packets_mutex );
1604 // We only deal with video from the selected video_index
1605 if ( ret >= 0 && self->pkt.stream_index == self->video_index && self->pkt.size > 0 )
1607 int64_t pts = best_pts( self, self->pkt.pts, self->pkt.dts );
1608 if ( pts != AV_NOPTS_VALUE )
1610 if ( !self->seekable && self->first_pts == AV_NOPTS_VALUE )
1611 self->first_pts = pts;
1612 if ( self->first_pts != AV_NOPTS_VALUE )
1613 pts -= self->first_pts;
1614 else if ( context->start_time != AV_NOPTS_VALUE )
1615 pts -= context->start_time;
1616 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.5 );
1617 if ( int_position == self->last_position )
1618 int_position = self->last_position + 1;
1620 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1621 "V pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1622 self->pkt.pts, self->pkt.dts, req_position, self->current_position, int_position );
1624 // Make a dumb assumption on streams that contain wild timestamps
1625 if ( abs( req_position - int_position ) > 999 )
1627 int_position = req_position;
1628 mlt_log_warning( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!\n" );
1630 self->last_position = int_position;
1633 if ( must_decode || int_position >= req_position )
1638 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1640 vdpau_decoder_init( self );
1642 self->vdpau->is_decoded = 0;
1645 codec_context->reordered_opaque = int_position;
1646 if ( int_position >= req_position )
1647 codec_context->skip_loop_filter = AVDISCARD_NONE;
1648 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1649 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &self->pkt );
1651 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, self->pkt.data, self->pkt.size );
1653 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1656 if ( ++decode_errors <= 10 )
1667 // Get position of reordered frame
1668 int_position = self->av_frame->reordered_opaque;
1669 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(106<<8)+0))
1670 pts = best_pts( self, self->av_frame->pkt_pts, self->av_frame->pkt_dts );
1671 if ( pts != AV_NOPTS_VALUE )
1673 if ( self->first_pts != AV_NOPTS_VALUE )
1674 pts -= self->first_pts;
1675 else if ( context->start_time != AV_NOPTS_VALUE )
1676 pts -= context->start_time;
1677 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.5 );
1681 if ( int_position < req_position )
1683 else if ( int_position >= req_position )
1684 codec_context->skip_loop_filter = AVDISCARD_NONE;
1686 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, self->pkt.flags & PKT_FLAG_KEY );
1689 // Now handle the picture if we have one
1692 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1694 // Workaround 1088 encodings missing cropping info.
1695 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1700 if ( self->vdpau->is_decoded )
1702 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1704 uint32_t pitches[3];
1705 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1707 if ( !self->vdpau->buffer )
1708 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1709 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1710 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1711 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1712 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1713 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1714 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1716 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1717 if ( status == VDP_STATUS_OK )
1719 convert_image( self, self->av_frame, *buffer, PIX_FMT_YUV420P,
1720 format, *width, *height, &alpha );
1724 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1725 image_size = self->vdpau->is_decoded = 0;
1730 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1731 image_size = got_picture = 0;
1736 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1737 format, *width, *height, &alpha );
1738 self->top_field_first |= self->av_frame->top_field_first;
1739 self->current_position = int_position;
1747 // Free packet data if not video and not live audio packet
1748 if ( self->pkt.stream_index != self->video_index &&
1749 !( !self->seekable && self->pkt.stream_index == self->audio_index ) )
1750 av_free_packet( &self->pkt );
1756 mlt_frame_set_alpha( frame, alpha, (*width) * (*height), mlt_pool_release );
1758 if ( image_size > 0 && self->image_cache )
1760 mlt_properties_set_int( frame_properties, "format", *format );
1761 mlt_cache_put_frame( self->image_cache, frame );
1764 // Try to duplicate last image if there was a decoding failure
1765 // TODO: with multithread decoding a partial frame decoding resulting
1766 // in failure also resets av_frame making test below fail.
1767 if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1770 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1772 // Workaround 1088 encodings missing cropping info.
1773 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1776 if ( self->vdpau && self->vdpau->buffer )
1779 picture.data[0] = self->vdpau->buffer;
1780 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1781 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1782 picture.linesize[0] = codec_context->width;
1783 picture.linesize[1] = codec_context->width / 2;
1784 picture.linesize[2] = codec_context->width / 2;
1785 convert_image( self, (AVFrame*) &picture, *buffer,
1786 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1790 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1791 format, *width, *height, &alpha );
1796 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1797 self->video_expected = position + 1;
1801 pthread_mutex_unlock( &self->video_mutex );
1803 // Set the progressive flag
1804 if ( mlt_properties_get( properties, "force_progressive" ) )
1805 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1806 else if ( self->av_frame )
1807 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1809 // Set the field order property for this frame
1810 if ( mlt_properties_get( properties, "force_tff" ) )
1811 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1813 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1815 // Set immutable properties of the selected track's (or overridden) source attributes.
1816 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1817 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1818 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1819 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1821 // If we already have RGB, then the full range processing either happened already
1822 // or does not apply (RGB source).
1823 if ( *format == mlt_image_rgb24 || *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1824 mlt_properties_set( frame_properties, "force_full_luma", NULL );
1826 return !got_picture;
1829 /** Process properties as AVOptions and apply to AV context obj
1832 static void apply_properties( void *obj, mlt_properties properties, int flags )
1835 int count = mlt_properties_count( properties );
1836 for ( i = 0; i < count; i++ )
1838 const char *opt_name = mlt_properties_get_name( properties, i );
1839 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
1840 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1842 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1844 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1847 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1848 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1849 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1850 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1851 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1852 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1854 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1860 /** Initialize the video codec context.
1863 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1865 // Initialise the codec if necessary
1866 if ( !self->video_codec )
1868 // Get the video stream
1869 AVStream *stream = self->video_format->streams[ index ];
1871 // Get codec context
1872 AVCodecContext *codec_context = stream->codec;
1875 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1877 if ( codec_context->codec_id == CODEC_ID_H264 )
1879 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1881 if ( vdpau_init( self ) )
1883 self->video_codec = codec_context;
1884 if ( !vdpau_decoder_init( self ) )
1889 codec = avcodec_find_decoder( codec_context->codec_id );
1893 // Initialise multi-threading
1894 int thread_count = mlt_properties_get_int( properties, "threads" );
1895 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1896 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1897 if ( thread_count > 1 )
1898 codec_context->thread_count = thread_count;
1900 // If we don't have a codec and we can't initialise it, we can't do much more...
1901 pthread_mutex_lock( &self->open_mutex );
1902 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1903 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1905 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1908 // Now store the codec with its destructor
1909 self->video_codec = codec_context;
1913 // Remember that we can't use this later
1914 self->video_index = -1;
1915 pthread_mutex_unlock( &self->open_mutex );
1918 pthread_mutex_unlock( &self->open_mutex );
1920 // Process properties as AVOptions
1921 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1922 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1923 if ( codec->priv_class && codec_context->priv_data )
1924 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1927 // Reset some image properties
1928 if ( self->video_codec )
1930 mlt_properties_set_int( properties, "width", self->video_codec->width );
1931 mlt_properties_set_int( properties, "height", self->video_codec->height );
1933 // For DV, we'll just use the saved aspect ratio
1934 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1935 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1937 // Determine the fps first from the codec
1938 double source_fps = (double) self->video_codec->time_base.den /
1939 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1942 // If the muxer reports a frame rate different than the codec
1943 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1944 double muxer_fps = av_q2d( stream->avg_frame_rate );
1945 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1946 muxer_fps = av_q2d( stream->r_frame_rate );
1948 double muxer_fps = av_q2d( stream->r_frame_rate );
1950 // Choose the lesser - the wrong tends to be off by some multiple of 10
1951 source_fps = FFMIN( source_fps, muxer_fps );
1952 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1954 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1955 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1957 else if ( muxer_fps > 0 )
1959 AVRational frame_rate = stream->r_frame_rate;
1960 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1961 // avg_frame_rate gives some approximate value that does not well match the media.
1962 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1963 // results in some very choppy output, but some value slightly different works
1965 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1966 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1967 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1969 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1970 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1974 source_fps = mlt_producer_get_fps( self->parent );
1975 AVRational frame_rate = av_d2q( source_fps, 255 );
1976 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1977 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1980 if ( mlt_properties_get( properties, "force_fps" ) )
1982 double source_fps = mlt_properties_get_double( properties, "force_fps" );
1983 AVRational fps = av_d2q( source_fps, 1024 );
1984 stream->time_base.num *= mlt_properties_get_int( properties, "meta.media.frame_rate_num" ) * fps.den;
1985 stream->time_base.den *= mlt_properties_get_int( properties, "meta.media.frame_rate_den" ) * fps.num;
1986 mlt_properties_set_int( properties, "meta.media.frame_rate_num", fps.num );
1987 mlt_properties_set_int( properties, "meta.media.frame_rate_den", fps.den );
1990 // Set the YUV colorspace from override or detect
1991 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1992 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1993 if ( ! self->colorspace )
1995 switch ( self->video_codec->colorspace )
1997 case AVCOL_SPC_SMPTE240M:
1998 self->colorspace = 240;
2000 case AVCOL_SPC_BT470BG:
2001 case AVCOL_SPC_SMPTE170M:
2002 self->colorspace = 601;
2004 case AVCOL_SPC_BT709:
2005 self->colorspace = 709;
2008 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
2009 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
2014 // Let apps get chosen colorspace
2015 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
2017 self->full_luma = -1;
2018 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(72<<8)+2)
2019 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent), "color_range %d\n", codec_context->color_range );
2020 if ( codec_context->color_range == AVCOL_RANGE_JPEG )
2021 self->full_luma = 1;
2023 if ( mlt_properties_get( properties, "set.force_full_luma" ) )
2024 self->full_luma = mlt_properties_get_int( properties, "set.force_full_luma" );
2026 return self->video_codec && self->video_index > -1;
2029 /** Set up video handling.
2032 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
2035 mlt_producer producer = self->parent;
2037 // Get the properties
2038 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2040 // Fetch the video format context
2041 AVFormatContext *context = self->video_format;
2043 // Get the video_index
2044 int index = mlt_properties_get_int( properties, "video_index" );
2046 // Reopen the file if necessary
2047 if ( !context && index > -1 )
2049 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2050 mlt_properties_get( properties, "resource" ), 1 );
2051 context = self->video_format;
2054 // Exception handling for video_index
2055 if ( context && index >= (int) context->nb_streams )
2057 // Get the last video stream
2058 for ( index = context->nb_streams - 1;
2059 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
2061 mlt_properties_set_int( properties, "video_index", index );
2063 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
2065 // Invalidate the video stream
2067 mlt_properties_set_int( properties, "video_index", index );
2070 // Update the video properties if the index changed
2071 if ( index != self->video_index )
2073 // Reset the video properties if the index changed
2074 self->video_index = index;
2075 pthread_mutex_lock( &self->open_mutex );
2076 if ( self->video_codec )
2077 avcodec_close( self->video_codec );
2078 self->video_codec = NULL;
2079 pthread_mutex_unlock( &self->open_mutex );
2082 // Get the frame properties
2083 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2086 if ( context && index > -1 && video_codec_init( self, index, properties ) )
2088 // Set the frame properties
2089 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
2090 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
2091 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
2093 // Set the width and height
2094 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
2095 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
2096 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
2097 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
2098 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
2099 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
2101 // Workaround 1088 encodings missing cropping info.
2102 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
2104 mlt_properties_set_int( properties, "meta.media.height", 1080 );
2107 // Add our image operation
2108 mlt_frame_push_service( frame, self );
2109 mlt_frame_push_get_image( frame, producer_get_image );
2113 // If something failed, use test card image
2114 mlt_properties_set_int( frame_properties, "test_image", 1 );
2118 static int seek_audio( producer_avformat self, mlt_position position, double timecode )
2122 // Seek if necessary
2123 if ( self->seekable && position != self->audio_expected )
2125 if ( position + 1 == self->audio_expected )
2127 // We're paused - silence required
2130 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
2132 AVFormatContext *context = self->audio_format;
2133 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
2134 if ( context->start_time != AV_NOPTS_VALUE )
2135 timestamp += context->start_time;
2136 if ( timestamp < 0 )
2139 // Set to the real timecode
2140 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
2143 // Clear the usage in the audio buffer
2144 int i = MAX_AUDIO_STREAMS + 1;
2146 self->audio_used[i - 1] = 0;
2152 static int sample_bytes( AVCodecContext *context )
2154 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2155 return av_get_bytes_per_sample( context->sample_fmt );
2156 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2157 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2159 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2163 static void planar_to_interleaved( uint8_t *dest, uint8_t *src, int samples, int channels, int bytes_per_sample )
2166 for ( s = 0; s < samples; s++ )
2168 for ( c = 0; c < channels; c++ )
2170 memcpy( dest, src + ( c * samples + s ) * bytes_per_sample, bytes_per_sample );
2171 dest += bytes_per_sample;
2176 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2178 // Fetch the audio_format
2179 AVFormatContext *context = self->audio_format;
2181 // Get the current stream index
2182 int index = pkt.stream_index;
2184 // Get codec context
2185 AVCodecContext *codec_context = self->audio_codec[ index ];
2187 // Obtain the resample context if it exists (not always needed)
2188 ReSampleContext *resample = self->audio_resample[ index ];
2190 // Obtain the audio buffers
2191 uint8_t *audio_buffer = self->audio_buffer[ index ];
2192 uint8_t *decode_buffer = self->decode_buffer[ index ];
2194 int audio_used = self->audio_used[ index ];
2195 uint8_t *ptr = pkt.data;
2199 while ( ptr && ret >= 0 && len > 0 )
2201 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2202 int data_size = self->audio_buffer_size[ index ];
2205 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2206 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2207 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2208 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2210 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2214 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2218 pkt.size = len -= ret;
2219 pkt.data = ptr += ret;
2221 // If decoded successfully
2222 if ( data_size > 0 )
2224 // Figure out how many samples will be needed after resampling
2225 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2226 int samples_needed = self->resample_factor * convert_samples;
2228 // Resize audio buffer to prevent overflow
2229 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2231 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2232 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2236 // Copy to audio buffer while resampling
2237 uint8_t *source = decode_buffer;
2238 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2239 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2243 uint8_t *source = decode_buffer;
2244 uint8_t *dest = &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ];
2245 switch ( codec_context->sample_fmt )
2247 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2248 case AV_SAMPLE_FMT_S16P:
2249 case AV_SAMPLE_FMT_S32P:
2250 case AV_SAMPLE_FMT_FLTP:
2251 planar_to_interleaved( dest, source, convert_samples, codec_context->channels, sizeof_sample );
2255 // Straight copy to audio buffer
2256 memcpy( dest, decode_buffer, data_size );
2258 audio_used += convert_samples;
2262 while ( *ignore && audio_used )
2265 audio_used -= audio_used > samples ? samples : audio_used;
2266 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2267 audio_used * sizeof_sample );
2272 // If we're behind, ignore this packet
2273 // Skip this on non-seekable, audio-only inputs.
2274 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2276 int64_t pts = pkt.pts;
2277 if ( self->first_pts != 0 )
2278 pts -= self->first_pts;
2279 else if ( context->start_time != AV_NOPTS_VALUE )
2280 pts -= context->start_time;
2281 double timebase = av_q2d( context->streams[ index ]->time_base );
2282 int64_t int_position = ( int64_t )( timebase * pts * fps + 0.5 );
2283 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2285 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
2286 "A pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
2287 pkt.pts, pkt.dts, req_position, self->current_position, int_position );
2289 if ( int_position > 0 )
2291 if ( int_position < req_position )
2292 // We are behind, so skip some
2293 *ignore = req_position - int_position;
2294 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2295 // We are ahead, so seek backwards some more
2296 seek_audio( self, req_position, timecode - 1.0 );
2300 self->audio_used[ index ] = audio_used;
2305 /** Get the audio from a frame.
2307 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2310 producer_avformat self = mlt_frame_pop_audio( frame );
2312 pthread_mutex_lock( &self->audio_mutex );
2314 // Obtain the frame number of this frame
2315 mlt_position position = mlt_frame_original_position( frame );
2317 // Calculate the real time code
2318 double real_timecode = producer_time_of_frame( self->parent, position );
2320 // Get the producer fps
2321 double fps = mlt_producer_get_fps( self->parent );
2323 // Number of frames to ignore (for ffwd)
2324 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2326 // Flag for paused (silence)
2327 int paused = seek_audio( self, position, real_timecode );
2329 // Initialize ignore for all streams from the seek return value
2330 int i = MAX_AUDIO_STREAMS;
2332 ignore[i] = ignore[0];
2334 // Fetch the audio_format
2335 AVFormatContext *context = self->audio_format;
2337 int sizeof_sample = sizeof( int16_t );
2339 // Determine the tracks to use
2340 int index = self->audio_index;
2341 int index_max = self->audio_index + 1;
2342 if ( self->audio_index == INT_MAX )
2345 index_max = FFMIN( MAX_AUDIO_STREAMS, context->nb_streams );
2346 *channels = self->total_channels;
2347 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2348 *frequency = FFMAX( self->max_frequency, *frequency );
2351 // Initialize the resamplers and buffers
2352 for ( ; index < index_max && index < MAX_AUDIO_STREAMS; index++ )
2354 // Get codec context
2355 AVCodecContext *codec_context = self->audio_codec[ index ];
2357 if ( codec_context && !self->audio_buffer[ index ] )
2359 #if LIBAVCODEC_VERSION_INT < ((54<<16)+(26<<8)+0)
2360 // Check for resample and create if necessary
2361 if ( codec_context->channels <= 2 )
2363 // Determine by how much resampling will increase number of samples
2364 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2365 resample_factor *= (double) *frequency / codec_context->sample_rate;
2366 if ( resample_factor > self->resample_factor )
2367 self->resample_factor = resample_factor;
2369 // Create the resampler
2370 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2371 self->audio_resample[ index ] = av_audio_resample_init(
2372 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2373 codec_context->channels, *frequency, codec_context->sample_rate,
2374 AV_SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2376 self->audio_resample[ index ] = audio_resample_init(
2377 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2378 codec_context->channels, *frequency, codec_context->sample_rate );
2384 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2385 sizeof_sample = sample_bytes( codec_context );
2388 // Check for audio buffer and create if necessary
2389 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2390 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2392 // Check for decoder buffer and create if necessary
2393 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2397 // Get the audio if required
2398 if ( !paused && *frequency > 0 )
2404 av_init_packet( &pkt );
2406 // If not resampling, give consumer more than requested.
2407 // It requested number samples based on requested frame rate.
2408 // Do not clean this up with a samples *= ...!
2409 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2410 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2412 while ( ret >= 0 && !got_audio )
2414 // Check if the buffer already contains the samples required
2415 if ( self->audio_index != INT_MAX &&
2416 self->audio_used[ self->audio_index ] >= *samples &&
2417 ignore[ self->audio_index ] == 0 )
2422 else if ( self->audio_index == INT_MAX )
2424 // Check if there is enough audio for all streams
2426 for ( index = 0; got_audio && index < index_max; index++ )
2427 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2434 pthread_mutex_lock( &self->packets_mutex );
2435 if ( mlt_deque_count( self->apackets ) )
2437 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2443 ret = av_read_frame( context, &pkt );
2444 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2446 if ( !av_dup_packet( &pkt ) )
2448 AVPacket *tmp = malloc( sizeof(AVPacket) );
2450 mlt_deque_push_back( self->vpackets, tmp );
2454 pthread_mutex_unlock( &self->packets_mutex );
2456 // We only deal with audio from the selected audio index
2457 index = pkt.stream_index;
2458 if ( index < MAX_AUDIO_STREAMS && ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2459 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2461 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2462 self->audio_codec[index]->channels : *channels;
2463 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2466 if ( self->seekable || index != self->video_index )
2467 av_free_packet( &pkt );
2471 // Set some additional return values
2472 *format = mlt_audio_s16;
2473 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2475 index = self->audio_index;
2476 *channels = self->audio_codec[ index ]->channels;
2477 *frequency = self->audio_codec[ index ]->sample_rate;
2478 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2479 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2481 else if ( self->audio_index == INT_MAX )
2483 for ( index = 0; index < index_max; index++ )
2484 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2486 // XXX: This only works if all audio tracks have the same sample format.
2487 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2488 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2493 // Allocate and set the frame's audio buffer
2494 int size = mlt_audio_format_size( *format, *samples, *channels );
2495 *buffer = mlt_pool_alloc( size );
2496 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2498 // Interleave tracks if audio_index=all
2499 if ( self->audio_index == INT_MAX )
2501 uint8_t *dest = *buffer;
2503 for ( i = 0; i < *samples; i++ )
2505 for ( index = 0; index < index_max; index++ )
2506 if ( self->audio_codec[ index ] )
2508 int current_channels = self->audio_codec[ index ]->channels;
2509 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2510 memcpy( dest, src, current_channels * sizeof_sample );
2511 dest += current_channels * sizeof_sample;
2514 for ( index = 0; index < index_max; index++ )
2515 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2517 int current_channels = self->audio_codec[ index ]->channels;
2518 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2519 self->audio_used[index] -= *samples;
2520 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2523 // Copy a single track to the output buffer
2526 index = self->audio_index;
2528 // Now handle the audio if we have enough
2529 if ( self->audio_used[ index ] > 0 )
2531 uint8_t *src = self->audio_buffer[ index ];
2532 // copy samples from audio_buffer
2533 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2534 memcpy( *buffer, src, size * *channels * sizeof_sample );
2535 // supply the remaining requested samples as silence
2536 if ( *samples > self->audio_used[ index ] )
2537 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2538 // reposition the samples within audio_buffer
2539 self->audio_used[ index ] -= size;
2540 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2544 // Otherwise fill with silence
2545 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2551 // Get silence and don't touch the context
2552 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2555 // Regardless of speed (other than paused), we expect to get the next frame
2557 self->audio_expected = position + 1;
2559 pthread_mutex_unlock( &self->audio_mutex );
2564 /** Initialize the audio codec context.
2567 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2569 // Initialise the codec if necessary
2570 if ( !self->audio_codec[ index ] )
2572 // Get codec context
2573 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2576 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2578 // If we don't have a codec and we can't initialise it, we can't do much more...
2579 pthread_mutex_lock( &self->open_mutex );
2580 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2581 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2583 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2586 // Now store the codec with its destructor
2587 if ( self->audio_codec[ index ] )
2588 avcodec_close( self->audio_codec[ index ] );
2589 self->audio_codec[ index ] = codec_context;
2593 // Remember that we can't use self later
2594 self->audio_index = -1;
2596 pthread_mutex_unlock( &self->open_mutex );
2598 // Process properties as AVOptions
2599 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2600 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
2601 if ( codec && codec->priv_class && codec_context->priv_data )
2602 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2605 return self->audio_codec[ index ] && self->audio_index > -1;
2608 /** Set up audio handling.
2611 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2614 mlt_producer producer = self->parent;
2616 // Get the properties
2617 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2619 // Fetch the audio format context
2620 AVFormatContext *context = self->audio_format;
2622 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2624 // Get the audio_index
2625 int index = mlt_properties_get_int( properties, "audio_index" );
2627 // Handle all audio tracks
2628 if ( self->audio_index > -1 &&
2629 mlt_properties_get( properties, "audio_index" ) &&
2630 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2633 // Reopen the file if necessary
2634 if ( !context && self->audio_index > -1 && index > -1 )
2636 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2637 mlt_properties_get( properties, "resource" ), 1 );
2638 context = self->audio_format;
2641 // Exception handling for audio_index
2642 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2644 for ( index = context->nb_streams - 1;
2645 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2647 mlt_properties_set_int( properties, "audio_index", index );
2649 if ( context && index > -1 && index < INT_MAX &&
2650 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2652 index = self->audio_index;
2653 mlt_properties_set_int( properties, "audio_index", index );
2656 // Update the audio properties if the index changed
2657 if ( context && index > -1 && index != self->audio_index )
2659 pthread_mutex_lock( &self->open_mutex );
2660 if ( self->audio_codec[ self->audio_index ] )
2661 avcodec_close( self->audio_codec[ self->audio_index ] );
2662 self->audio_codec[ self->audio_index ] = NULL;
2663 pthread_mutex_unlock( &self->open_mutex );
2665 if ( self->audio_index != -1 )
2666 self->audio_index = index;
2671 if ( context && index == INT_MAX )
2673 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2674 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2675 for ( index = 0; index < context->nb_streams; index++ )
2677 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2678 audio_codec_init( self, index, properties );
2681 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2683 // Set the frame properties
2684 if ( index < MAX_AUDIO_STREAMS )
2686 mlt_properties_set_int( frame_properties, "audio_frequency", self->audio_codec[ index ]->sample_rate );
2687 mlt_properties_set_int( frame_properties, "audio_channels", self->audio_codec[ index ]->channels );
2690 if ( context && index > -1 )
2692 // Add our audio operation
2693 mlt_frame_push_audio( frame, self );
2694 mlt_frame_push_audio( frame, producer_get_audio );
2698 /** Our get frame implementation.
2701 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2703 // Access the private data
2704 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2705 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2706 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2711 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2712 producer->child = self;
2713 self->parent = producer;
2714 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2715 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2718 // Create an empty frame
2719 *frame = mlt_frame_init( service);
2723 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2727 mlt_cache_item_close( cache_item );
2731 // Update timecode on the frame we're creating
2732 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2735 producer_set_up_video( self, *frame );
2738 producer_set_up_audio( self, *frame );
2740 // Set the position of this producer
2741 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2742 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "original_position", position );
2744 // Calculate the next timecode
2745 mlt_producer_prepare_next( producer );
2750 static void producer_avformat_close( producer_avformat self )
2752 mlt_log_debug( NULL, "producer_avformat_close\n" );
2754 // Cleanup av contexts
2755 av_free_packet( &self->pkt );
2756 av_free( self->av_frame );
2757 pthread_mutex_lock( &self->open_mutex );
2759 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2761 if ( self->audio_resample[i] )
2762 audio_resample_close( self->audio_resample[i] );
2763 mlt_pool_release( self->audio_buffer[i] );
2764 av_free( self->decode_buffer[i] );
2765 if ( self->audio_codec[i] )
2766 avcodec_close( self->audio_codec[i] );
2767 self->audio_codec[i] = NULL;
2769 if ( self->video_codec )
2770 avcodec_close( self->video_codec );
2771 self->video_codec = NULL;
2773 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2774 if ( self->dummy_context )
2775 avformat_close_input( &self->dummy_context );
2776 if ( self->seekable && self->audio_format )
2777 avformat_close_input( &self->audio_format );
2778 if ( self->video_format )
2779 avformat_close_input( &self->video_format );
2781 if ( self->dummy_context )
2782 av_close_input_file( self->dummy_context );
2783 if ( self->seekable && self->audio_format )
2784 av_close_input_file( self->audio_format );
2785 if ( self->video_format )
2786 av_close_input_file( self->video_format );
2788 pthread_mutex_unlock( &self->open_mutex );
2790 vdpau_producer_close( self );
2792 if ( self->image_cache )
2793 mlt_cache_close( self->image_cache );
2795 // Cleanup the mutexes
2796 if ( self->is_mutex_init )
2798 pthread_mutex_destroy( &self->audio_mutex );
2799 pthread_mutex_destroy( &self->video_mutex );
2800 pthread_mutex_destroy( &self->packets_mutex );
2801 pthread_mutex_destroy( &self->open_mutex );
2804 // Cleanup the packet queues
2806 if ( self->apackets )
2808 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2810 av_free_packet( pkt );
2813 mlt_deque_close( self->apackets );
2814 self->apackets = NULL;
2816 if ( self->vpackets )
2818 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2820 av_free_packet( pkt );
2823 mlt_deque_close( self->vpackets );
2824 self->vpackets = NULL;
2830 static void producer_close( mlt_producer parent )
2832 // Remove this instance from the cache
2833 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2836 parent->close = NULL;
2837 mlt_producer_close( parent );