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_U8 SAMPLE_FMT_U8
42 # define AV_SAMPLE_FMT_S16 SAMPLE_FMT_S16
43 # define AV_SAMPLE_FMT_S32 SAMPLE_FMT_S32
44 # define AV_SAMPLE_FMT_FLT SAMPLE_FMT_FLT
45 # if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
46 const char *avcodec_get_sample_fmt_name(int sample_fmt);
51 # include <libavcodec/vdpau.h>
53 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
54 # include <libavutil/pixdesc.h>
56 #if (LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0))
57 # include <libavutil/dict.h>
60 // System header files
66 #if LIBAVUTIL_VERSION_INT < (50<<16)
67 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
68 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
71 #if LIBAVCODEC_VERSION_MAJOR >= 53
72 #include <libavutil/opt.h>
73 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
74 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
75 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
77 #include <libavcodec/opt.h>
80 #define POSITION_INITIAL (-2)
81 #define POSITION_INVALID (-1)
83 #define MAX_AUDIO_STREAMS (32)
84 #define MAX_VDPAU_SURFACES (10)
86 struct producer_avformat_s
89 AVFormatContext *dummy_context;
90 AVFormatContext *audio_format;
91 AVFormatContext *video_format;
92 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
93 AVCodecContext *video_codec;
96 ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
97 mlt_position audio_expected;
98 mlt_position video_expected;
102 int64_t last_position;
104 int64_t current_position;
105 mlt_position nonseek_position;
107 uint8_t *audio_buffer[ MAX_AUDIO_STREAMS ];
108 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
109 uint8_t *decode_buffer[ MAX_AUDIO_STREAMS ];
110 int audio_used[ MAX_AUDIO_STREAMS ];
112 int audio_max_stream;
116 unsigned int invalid_pts_counter;
117 unsigned int invalid_dts_counter;
118 double resample_factor;
119 mlt_cache image_cache;
122 pthread_mutex_t video_mutex;
123 pthread_mutex_t audio_mutex;
126 pthread_mutex_t packets_mutex;
127 pthread_mutex_t open_mutex;
133 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
147 typedef struct producer_avformat_s *producer_avformat;
149 // Forward references.
150 static int list_components( char* file );
151 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock );
152 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
153 static void producer_avformat_close( producer_avformat );
154 static void producer_close( mlt_producer parent );
155 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
156 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
157 static void apply_properties( void *obj, mlt_properties properties, int flags );
158 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
159 static void get_audio_streams_info( producer_avformat self );
160 static mlt_audio_format pick_audio_format( int sample_fmt );
166 /** Constructor for libavformat.
169 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
171 if ( list_components( file ) )
174 mlt_producer producer = NULL;
176 // Check that we have a non-NULL argument
179 // Construct the producer
180 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
181 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
184 if ( mlt_producer_init( producer, self ) == 0 )
186 self->parent = producer;
188 // Get the properties
189 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
191 // Set the resource property (required for all producers)
192 mlt_properties_set( properties, "resource", file );
194 // Register transport implementation with the producer
195 producer->close = (mlt_destructor) producer_close;
197 // Register our get_frame implementation
198 producer->get_frame = producer_get_frame;
200 if ( strcmp( service, "avformat-novalidate" ) )
203 if ( producer_open( self, profile, file, 1 ) != 0 )
206 mlt_producer_close( producer );
208 producer_avformat_close( self );
210 else if ( self->seekable )
212 // Close the file to release resources for large playlists - reopen later as needed
213 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
214 if ( self->audio_format )
215 avformat_close_input( &self->audio_format );
216 if ( self->video_format )
217 avformat_close_input( &self->video_format );
219 if ( self->audio_format )
220 av_close_input_file( self->audio_format );
221 if ( self->video_format )
222 av_close_input_file( self->video_format );
224 self->audio_format = NULL;
225 self->video_format = NULL;
230 // Default the user-selectable indices from the auto-detected indices
231 mlt_properties_set_int( properties, "audio_index", self->audio_index );
232 mlt_properties_set_int( properties, "video_index", self->video_index );
234 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
236 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
243 int list_components( char* file )
247 // Report information about available demuxers and codecs as YAML Tiny
248 if ( file && strstr( file, "f-list" ) )
250 fprintf( stderr, "---\nformats:\n" );
251 AVInputFormat *format = NULL;
252 while ( ( format = av_iformat_next( format ) ) )
253 fprintf( stderr, " - %s\n", format->name );
254 fprintf( stderr, "...\n" );
257 if ( file && strstr( file, "acodec-list" ) )
259 fprintf( stderr, "---\naudio_codecs:\n" );
260 AVCodec *codec = NULL;
261 while ( ( codec = av_codec_next( codec ) ) )
262 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
263 fprintf( stderr, " - %s\n", codec->name );
264 fprintf( stderr, "...\n" );
267 if ( file && strstr( file, "vcodec-list" ) )
269 fprintf( stderr, "---\nvideo_codecs:\n" );
270 AVCodec *codec = NULL;
271 while ( ( codec = av_codec_next( codec ) ) )
272 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
273 fprintf( stderr, " - %s\n", codec->name );
274 fprintf( stderr, "...\n" );
281 /** Find the default streams.
284 static mlt_properties find_default_streams( producer_avformat self )
288 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
289 AVDictionaryEntry *tag = NULL;
291 AVMetadataTag *tag = NULL;
293 AVFormatContext *context = self->video_format;
294 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
296 // Default to the first audio and video streams found
297 self->audio_index = -1;
298 self->video_index = -1;
300 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
302 // Allow for multiple audio and video streams in the file and select first of each (if available)
303 for( i = 0; i < context->nb_streams; i++ )
305 // Get the codec context
306 AVStream *stream = context->streams[ i ];
307 if ( ! stream ) continue;
308 AVCodecContext *codec_context = stream->codec;
309 if ( ! codec_context ) continue;
310 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
311 if ( ! codec ) continue;
313 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
315 // Determine the type and obtain the first index of each type
316 switch( codec_context->codec_type )
318 case CODEC_TYPE_VIDEO:
319 // Use first video stream
320 if ( self->video_index < 0 )
321 self->video_index = i;
322 mlt_properties_set( meta_media, key, "video" );
323 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
324 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
325 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
326 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
327 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
328 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
330 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
333 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
334 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
335 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
337 snprintf( key, sizeof(key), "meta.media.%d.codec.width", i );
338 mlt_properties_set_int( meta_media, key, codec_context->width );
339 snprintf( key, sizeof(key), "meta.media.%d.codec.height", i );
340 mlt_properties_set_int( meta_media, key, codec_context->height );
341 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
342 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
343 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
344 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
345 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(3<<8)+0)
346 mlt_properties_set( meta_media, key, av_get_pix_fmt_name( codec_context->pix_fmt ) );
348 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
350 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
351 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
352 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
353 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
354 switch ( codec_context->colorspace )
356 case AVCOL_SPC_SMPTE240M:
357 mlt_properties_set_int( meta_media, key, 240 );
359 case AVCOL_SPC_BT470BG:
360 case AVCOL_SPC_SMPTE170M:
361 mlt_properties_set_int( meta_media, key, 601 );
363 case AVCOL_SPC_BT709:
364 mlt_properties_set_int( meta_media, key, 709 );
367 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
368 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
373 case CODEC_TYPE_AUDIO:
374 if ( !codec_context->channels )
376 // Use first audio stream
377 if ( self->audio_index < 0 && pick_audio_format( codec_context->sample_fmt ) != mlt_audio_none )
378 self->audio_index = i;
380 mlt_properties_set( meta_media, key, "audio" );
381 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
382 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
383 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
384 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
385 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
386 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
388 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
389 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
390 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
391 mlt_properties_set_int( meta_media, key, codec_context->channels );
396 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
397 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
398 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
399 mlt_properties_set( meta_media, key, codec->name );
400 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
401 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
402 mlt_properties_set( meta_media, key, codec->long_name );
404 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
405 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
406 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
407 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
408 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
409 // mlt_properties_set_int( meta_media, key, codec_context->profile );
410 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
411 // mlt_properties_set_int( meta_media, key, codec_context->level );
414 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
415 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
416 while ( ( tag = av_dict_get( stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
418 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
421 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
423 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
424 mlt_properties_set( meta_media, key, tag->value );
429 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
430 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
431 while ( ( tag = av_dict_get( context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
433 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
436 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
438 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
439 mlt_properties_set( meta_media, key, tag->value );
443 if ( context->title && strcmp( context->title, "" ) )
444 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
445 if ( context->author && strcmp( context->author, "" ) )
446 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
447 if ( context->copyright && strcmp( context->copyright, "" ) )
448 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
449 if ( context->comment )
450 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
451 if ( context->album )
452 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
454 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
455 if ( context->track )
456 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
462 static inline int dv_is_pal( AVPacket *pkt )
464 return pkt->data[3] & 0x80;
467 static int dv_is_wide( AVPacket *pkt )
469 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
471 for ( ; i < pkt->size; i += 5 /* packet size */ )
473 if ( pkt->data[ i ] == 0x61 )
475 uint8_t x = pkt->data[ i + 2 ] & 0x7;
476 return ( x == 2 ) || ( x == 7 );
482 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
484 double aspect_ratio = 1.0;
486 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
490 if ( dv_is_pal( pkt ) )
492 if ( dv_is_wide( pkt ) )
494 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
495 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
499 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
500 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
505 if ( dv_is_wide( pkt ) )
507 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
508 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
512 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
513 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
520 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
521 stream->sample_aspect_ratio;
523 codec_context->sample_aspect_ratio;
525 // Override FFmpeg's notion of DV aspect ratios, which are
526 // based upon a width of 704. Since we do not have a normaliser
527 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
528 // we just coerce the values to facilitate a passive behaviour through
529 // the rescale normaliser when using equivalent producers and consumers.
530 // = display_aspect / (width * height)
531 if ( ar.num == 10 && ar.den == 11 )
534 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
535 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
537 else if ( ar.num == 59 && ar.den == 54 )
540 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
541 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
543 else if ( ar.num == 40 && ar.den == 33 )
546 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
547 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
549 else if ( ar.num == 118 && ar.den == 81 )
552 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
553 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
559 AVRational codec_sar = codec_context->sample_aspect_ratio;
560 AVRational stream_sar =
561 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
562 stream->sample_aspect_ratio;
566 if ( codec_sar.num > 0 )
568 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
569 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
571 else if ( stream_sar.num > 0 )
573 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
574 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
578 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
579 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
582 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
583 aspect_ratio = av_q2d( ar );
584 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
589 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
590 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVDictionary **params )
592 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
595 if ( !URL ) return NULL;
598 char *protocol = strdup( URL );
599 char *url = strchr( protocol, ':' );
601 // Only if there is not a protocol specification that avformat can handle
602 #if LIBAVFORMAT_VERSION_MAJOR >= 53
603 if ( url && avio_check( URL, 0 ) < 0 )
605 if ( url && !url_exist( URL ) )
608 // Truncate protocol string
610 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
613 *format = av_find_input_format( protocol );
615 // Eat the format designator
620 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
621 // support for legacy width and height parameters
625 // These are required by video4linux2 (defaults)
626 params->width = profile->width;
627 params->height = profile->height;
628 if ( !strstr( URL, "&frame_rate" ) )
629 params->time_base = (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
630 params->channels = 2;
631 params->sample_rate = 48000;
635 url = strchr( url, '?' );
639 char *name = strdup( ++url );
640 char *value = strchr( name, '=' );
642 // Also accept : as delimiter for backwards compatibility.
643 value = strchr( name, ':' );
648 char *t = strchr( value, '&' );
651 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
652 // translate old parameters to new av_dict names
653 if ( !strcmp( name, "frame_rate" ) )
654 av_dict_set( params, "framerate", value, 0 );
655 else if ( !strcmp( name, "pix_fmt" ) )
656 av_dict_set( params, "pixel_format", value, 0 );
657 else if ( !strcmp( name, "width" ) )
658 width = strdup( value );
659 else if ( !strcmp( name, "height" ) )
660 height = strdup( value );
662 // generic demux/device option support
663 av_dict_set( params, name, value, 0 );
665 if ( !strcmp( name, "frame_rate" ) )
666 params->time_base.den = atoi( value );
667 else if ( !strcmp( name, "frame_rate_base" ) )
668 params->time_base.num = atoi( value );
669 else if ( !strcmp( name, "sample_rate" ) )
670 params->sample_rate = atoi( value );
671 else if ( !strcmp( name, "channel" ) )
672 params->channel = atoi( value );
673 else if ( !strcmp( name, "channels" ) )
674 params->channels = atoi( value );
675 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
676 else if ( !strcmp( name, "pix_fmt" ) )
677 params->pix_fmt = av_get_pix_fmt( value );
679 else if ( !strcmp( name, "width" ) )
680 params->width = atoi( value );
681 else if ( !strcmp( name, "height" ) )
682 params->height = atoi( value );
683 else if ( !strcmp( name, "standard" ) )
684 params->standard = strdup( value );
688 url = strchr( url, '&' );
690 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
691 // continued support for legacy width and height parameters
692 if ( width && height )
694 char *s = malloc( strlen( width ) + strlen( height ) + 2 );
698 av_dict_set( params, "video_size", s, 0 );
701 if ( width ) free( width );
702 if ( height ) free ( height );
705 result = strdup( result );
709 result = strdup( URL );
715 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
719 // Get the properties
720 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
722 AVFormatContext *format = self->video_format;
724 // We will treat everything with the producer fps.
725 // TODO: make this more flexible.
726 double fps = mlt_profile_fps( profile );
729 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
731 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
732 // when producer_open is called after initial call when restoring or reseting the producer.
733 if ( format->duration != AV_NOPTS_VALUE )
735 // This isn't going to be accurate for all formats
736 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
737 mlt_properties_set_position( properties, "out", frames - 1 );
738 mlt_properties_set_position( properties, "length", frames );
739 mlt_properties_set_int( properties, "_length_computed", 1 );
743 // Set live sources to run forever
744 mlt_properties_set_position( properties, "length", INT_MAX );
745 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
746 mlt_properties_set( properties, "eof", "loop" );
747 mlt_properties_set_int( properties, "_length_computed", 1 );
751 // Check if we're seekable
752 // avdevices are typically AVFMT_NOFILE and not seekable
753 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
756 // protocols can indicate if they support seeking
757 #if LIBAVFORMAT_VERSION_MAJOR >= 53
758 self->seekable = format->pb->seekable;
760 URLContext *uc = url_fileno( format->pb );
762 self->seekable = !uc->is_streamed;
765 if ( self->seekable )
767 // Do a more rigourous test of seekable on a disposable context
768 self->seekable = av_seek_frame( format, -1, format->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
769 mlt_properties_set_int( properties, "seekable", self->seekable );
770 self->dummy_context = format;
771 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
772 self->video_format = NULL;
773 avformat_open_input( &self->video_format, filename, NULL, NULL );
774 avformat_find_stream_info( self->video_format, NULL );
776 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
777 av_find_stream_info( self->video_format );
779 format = self->video_format;
782 // Fetch the width, height and aspect ratio
783 if ( self->video_index != -1 )
785 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
786 mlt_properties_set_int( properties, "width", codec_context->width );
787 mlt_properties_set_int( properties, "height", codec_context->height );
789 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
791 // Fetch the first frame of DV so we can read it directly
796 ret = av_read_frame( format, &pkt );
797 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
799 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
800 av_free_packet(&pkt);
804 av_free_packet(&pkt);
809 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
813 // Verify that we can convert this to YUV 4:2:2
814 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
815 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
816 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
818 sws_freeContext( context );
829 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
831 // Return an error code (0 == no error)
833 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
838 if ( !self->is_mutex_init )
840 pthread_mutex_init( &self->audio_mutex, NULL );
841 pthread_mutex_init( &self->video_mutex, NULL );
842 pthread_mutex_init( &self->packets_mutex, NULL );
843 pthread_mutex_init( &self->open_mutex, NULL );
844 self->is_mutex_init = 1;
846 pthread_mutex_lock( &self->audio_mutex );
847 pthread_mutex_lock( &self->video_mutex );
849 mlt_events_block( properties, self->parent );
852 AVInputFormat *format = NULL;
853 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
854 AVDictionary *params = NULL;
856 AVFormatParameters params;
857 memset( ¶ms, 0, sizeof(params) );
859 char *filename = parse_url( profile, URL, &format, ¶ms );
861 // Now attempt to open the file or device with filename
862 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
863 error = avformat_open_input( &self->video_format, filename, format, ¶ms ) < 0;
865 // If the URL is a network stream URL, then we probably need to open with full URL
866 error = avformat_open_input( &self->video_format, URL, format, ¶ms ) < 0;
868 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
870 // If the URL is a network stream URL, then we probably need to open with full URL
871 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
874 // Set MLT properties onto video AVFormatContext
875 if ( !error && self->video_format )
877 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
878 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
879 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
880 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
884 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
885 av_dict_free( ¶ms );
887 // Cleanup AVFormatParameters
888 if ( params.standard )
889 free( (void*) params.standard );
892 // If successful, then try to get additional info
893 if ( !error && self->video_format )
895 // Get the stream info
896 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
897 error = avformat_find_stream_info( self->video_format, NULL ) < 0;
899 error = av_find_stream_info( self->video_format ) < 0;
902 // Continue if no error
903 if ( !error && self->video_format )
905 // Find default audio and video streams
906 find_default_streams( self );
907 error = get_basic_info( self, profile, filename );
909 // Initialize position info
910 self->first_pts = AV_NOPTS_VALUE;
911 self->last_position = POSITION_INITIAL;
913 if ( !self->audio_format )
915 // We're going to cheat here - for seekable A/V files, we will have separate contexts
916 // to support independent seeking of audio from video.
917 // TODO: Is this really necessary?
918 if ( self->audio_index != -1 && self->video_index != -1 )
920 if ( self->seekable )
922 // And open again for our audio context
923 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
924 avformat_open_input( &self->audio_format, filename, NULL, NULL );
925 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
926 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
927 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
928 avformat_find_stream_info( self->audio_format, NULL );
930 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
931 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
932 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
933 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
934 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
936 av_find_stream_info( self->audio_format );
941 self->audio_format = self->video_format;
944 else if ( self->audio_index != -1 )
946 // We only have an audio context
947 self->audio_format = self->video_format;
948 self->video_format = NULL;
950 else if ( self->video_index == -1 )
952 // Something has gone wrong
955 if ( self->audio_format && !self->audio_streams )
956 get_audio_streams_info( self );
964 self->apackets = mlt_deque_init();
965 self->vpackets = mlt_deque_init();
968 if ( self->dummy_context )
970 pthread_mutex_lock( &self->open_mutex );
971 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
972 avformat_close_input( &self->dummy_context );
974 av_close_input_file( self->dummy_context );
976 self->dummy_context = NULL;
977 pthread_mutex_unlock( &self->open_mutex );
980 // Unlock the service
983 pthread_mutex_unlock( &self->audio_mutex );
984 pthread_mutex_unlock( &self->video_mutex );
986 mlt_events_unblock( properties, self->parent );
991 static void reopen_video( producer_avformat self, mlt_producer producer )
993 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
994 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
995 pthread_mutex_lock( &self->audio_mutex );
996 pthread_mutex_lock( &self->open_mutex );
998 if ( self->video_codec )
999 avcodec_close( self->video_codec );
1000 self->video_codec = NULL;
1001 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
1002 if ( self->dummy_context )
1003 avformat_close_input( &self->dummy_context );
1004 if ( self->video_format )
1005 avformat_close_input( &self->video_format );
1007 if ( self->dummy_context )
1008 av_close_input_file( self->dummy_context );
1009 if ( self->video_format )
1010 av_close_input_file( self->video_format );
1012 self->dummy_context = NULL;
1013 self->video_format = NULL;
1014 pthread_mutex_unlock( &self->open_mutex );
1016 int audio_index = self->audio_index;
1017 int video_index = self->video_index;
1019 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1020 mlt_properties_get( properties, "resource" ), 0 );
1022 self->audio_index = audio_index;
1023 if ( self->video_format && video_index > -1 )
1025 self->video_index = video_index;
1026 video_codec_init( self, video_index, properties );
1029 pthread_mutex_unlock( &self->audio_mutex );
1030 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1033 static int64_t best_pts( producer_avformat self, int64_t pts, int64_t dts )
1035 self->invalid_pts_counter += pts == AV_NOPTS_VALUE;
1036 self->invalid_dts_counter += dts == AV_NOPTS_VALUE;
1037 if ( ( self->invalid_pts_counter <= self->invalid_dts_counter
1038 || dts == AV_NOPTS_VALUE ) && pts != AV_NOPTS_VALUE )
1044 static int seek_video( producer_avformat self, mlt_position position,
1045 int64_t req_position, int preseek )
1047 mlt_producer producer = self->parent;
1050 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
1052 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1054 // Fetch the video format context
1055 AVFormatContext *context = self->video_format;
1057 // Get the video stream
1058 AVStream *stream = context->streams[ self->video_index ];
1060 // Get codec context
1061 AVCodecContext *codec_context = stream->codec;
1063 // We may want to use the source fps if available
1064 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1065 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1068 if ( self->last_position == POSITION_INITIAL )
1074 while ( ret >= 0 && toscan-- > 0 )
1076 ret = av_read_frame( context, &pkt );
1077 if ( ret >= 0 && pkt.stream_index == self->video_index && ( pkt.flags & PKT_FLAG_KEY ) )
1079 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1080 "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n",
1081 pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
1082 self->first_pts = best_pts( self, pkt.pts, pkt.dts );
1083 if ( self->first_pts != AV_NOPTS_VALUE )
1086 av_free_packet( &pkt );
1088 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1091 if ( self->av_frame && position + 1 == self->video_expected )
1093 // We're paused - use last image
1096 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
1098 // Calculate the timestamp for the requested frame
1099 int64_t timestamp = req_position / ( av_q2d( stream->time_base ) * source_fps );
1100 if ( req_position <= 0 )
1102 else if ( self->first_pts != AV_NOPTS_VALUE )
1103 timestamp += self->first_pts;
1104 else if ( context->start_time != AV_NOPTS_VALUE )
1105 timestamp += context->start_time;
1106 if ( preseek && av_q2d( stream->time_base ) != 0 )
1107 timestamp -= 2 / av_q2d( stream->time_base );
1108 if ( timestamp < 0 )
1110 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
1111 timestamp, position, self->video_expected, self->last_position );
1113 // Seek to the timestamp
1114 // NOTE: reopen_video is disabled at this time because it is causing trouble with A/V sync.
1115 if ( 1 || req_position > 0 || self->last_position <= 0 )
1117 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1118 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1120 // flush any pictures still in decode buffer
1121 avcodec_flush_buffers( codec_context );
1125 // Re-open video stream when rewinding to beginning from somewhere else.
1126 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1127 // not reliably seeking to the first frame across formats.
1128 reopen_video( self, producer );
1131 // Remove the cached info relating to the previous position
1132 self->current_position = POSITION_INVALID;
1133 self->last_position = POSITION_INVALID;
1134 av_freep( &self->av_frame );
1140 /** Convert a frame position to a time code.
1143 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1145 return ( double )position / mlt_producer_get_fps( producer );
1148 // Collect information about all audio streams
1150 static void get_audio_streams_info( producer_avformat self )
1152 // Fetch the audio format context
1153 AVFormatContext *context = self->audio_format;
1157 i < context->nb_streams;
1160 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1162 AVCodecContext *codec_context = context->streams[i]->codec;
1163 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1165 // If we don't have a codec and we can't initialise it, we can't do much more...
1166 pthread_mutex_lock( &self->open_mutex );
1167 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1168 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1170 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1173 self->audio_streams++;
1174 self->audio_max_stream = i;
1175 self->total_channels += codec_context->channels;
1176 if ( codec_context->channels > self->max_channel )
1177 self->max_channel = codec_context->channels;
1178 if ( codec_context->sample_rate > self->max_frequency )
1179 self->max_frequency = codec_context->sample_rate;
1180 avcodec_close( codec_context );
1182 pthread_mutex_unlock( &self->open_mutex );
1185 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1186 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1188 // Other audio-specific initializations
1189 self->resample_factor = 1.0;
1192 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1194 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1196 const int *new_coefficients;
1198 int brightness, contrast, saturation;
1200 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1201 &brightness, &contrast, &saturation ) != -1 )
1203 // Don't change these from defaults unless explicitly told to.
1204 if ( use_full_range >= 0 )
1205 full_range = use_full_range;
1206 switch ( colorspace )
1212 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1215 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1218 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1221 new_coefficients = coefficients;
1224 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1225 brightness, contrast, saturation );
1230 static mlt_image_format pick_pix_format( enum PixelFormat pix_fmt )
1238 return mlt_image_rgb24a;
1239 case PIX_FMT_YUV420P:
1240 case PIX_FMT_YUVJ420P:
1241 case PIX_FMT_YUVA420P:
1242 return mlt_image_yuv420p;
1246 case PIX_FMT_MONOWHITE:
1247 case PIX_FMT_MONOBLACK:
1250 return mlt_image_rgb24;
1252 return mlt_image_yuv422;
1256 static mlt_audio_format pick_audio_format( int sample_fmt )
1258 switch ( sample_fmt )
1261 case AV_SAMPLE_FMT_U8:
1262 return mlt_audio_u8;
1263 case AV_SAMPLE_FMT_S16:
1264 return mlt_audio_s16;
1265 case AV_SAMPLE_FMT_S32:
1266 return mlt_audio_s32le;
1267 case AV_SAMPLE_FMT_FLT:
1268 return mlt_audio_f32le;
1269 // planar - this producer converts planar to interleaved
1270 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1271 case AV_SAMPLE_FMT_U8P:
1272 return mlt_audio_u8;
1273 case AV_SAMPLE_FMT_S16P:
1274 return mlt_audio_s16;
1275 case AV_SAMPLE_FMT_S32P:
1276 return mlt_audio_s32le;
1277 case AV_SAMPLE_FMT_FLTP:
1278 return mlt_audio_f32le;
1281 return mlt_audio_none;
1285 static void convert_image( producer_avformat self, AVFrame *frame, uint8_t *buffer, int pix_fmt,
1286 mlt_image_format *format, int width, int height, uint8_t **alpha )
1289 int flags = SWS_BICUBIC | SWS_ACCURATE_RND;
1292 flags |= SWS_CPU_CAPS_MMX;
1295 flags |= SWS_CPU_CAPS_MMX2;
1298 // extract alpha from planar formats
1299 if ( ( pix_fmt == PIX_FMT_YUVA420P
1300 #if defined(FFUDIV) && LIBAVUTIL_VERSION_INT >= ((51<<16)+(35<<8)+101)
1301 || pix_fmt == PIX_FMT_YUVA444P
1304 *format != mlt_image_rgb24a && *format != mlt_image_opengl &&
1305 frame->data[3] && frame->linesize[3] )
1310 dst = *alpha = mlt_pool_alloc( width * height );
1311 src = frame->data[3];
1313 for ( i = 0; i < height; dst += width, src += frame->linesize[3], i++ )
1314 memcpy( dst, src, FFMIN( width, frame->linesize[3] ) );
1317 if ( *format == mlt_image_yuv420p )
1319 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1320 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1322 output.data[0] = buffer;
1323 output.data[1] = buffer + width * height;
1324 output.data[2] = buffer + ( 5 * width * height ) / 4;
1325 output.linesize[0] = width;
1326 output.linesize[1] = width >> 1;
1327 output.linesize[2] = width >> 1;
1328 set_luma_transfer( context, self->colorspace, -1 );
1329 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1330 output.data, output.linesize);
1331 sws_freeContext( context );
1333 else if ( *format == mlt_image_rgb24 )
1335 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1336 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1338 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1339 set_luma_transfer( context, self->colorspace, self->full_luma );
1340 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1341 output.data, output.linesize);
1342 sws_freeContext( context );
1344 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1346 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1347 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1349 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1350 set_luma_transfer( context, self->colorspace, self->full_luma );
1351 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1352 output.data, output.linesize);
1353 sws_freeContext( context );
1357 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1358 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1360 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1361 set_luma_transfer( context, self->colorspace, -1 );
1362 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1363 output.data, output.linesize);
1364 sws_freeContext( context );
1367 if ( *format == mlt_image_yuv420p )
1370 pict.data[0] = buffer;
1371 pict.data[1] = buffer + width * height;
1372 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1373 pict.linesize[0] = width;
1374 pict.linesize[1] = width >> 1;
1375 pict.linesize[2] = width >> 1;
1376 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1378 else if ( *format == mlt_image_rgb24 )
1381 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1382 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1384 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1387 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1388 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1393 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1394 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1399 /** Allocate the image buffer and set it on the frame.
1402 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1406 if ( codec_context->width == 0 || codec_context->height == 0 )
1408 *width = codec_context->width;
1409 *height = codec_context->height;
1410 size = mlt_image_format_size( *format, *width, *height, NULL );
1411 *buffer = mlt_pool_alloc( size );
1413 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1420 /** Get an image from a frame.
1423 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1426 producer_avformat self = mlt_frame_pop_service( frame );
1427 mlt_producer producer = self->parent;
1429 // Get the properties from the frame
1430 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1432 // Obtain the frame number of this frame
1433 mlt_position position = mlt_frame_original_position( frame );
1435 // Get the producer properties
1436 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1438 pthread_mutex_lock( &self->video_mutex );
1440 // Fetch the video format context
1441 AVFormatContext *context = self->video_format;
1443 // Get the video stream
1444 AVStream *stream = context->streams[ self->video_index ];
1446 // Get codec context
1447 AVCodecContext *codec_context = stream->codec;
1449 uint8_t *alpha = NULL;
1450 int got_picture = 0;
1453 // Get the image cache
1454 if ( ! self->image_cache )
1456 // if cache size supplied by environment variable
1457 int cache_supplied = getenv( "MLT_AVFORMAT_CACHE" ) != NULL;
1458 int cache_size = cache_supplied? atoi( getenv( "MLT_AVFORMAT_CACHE" ) ) : 0;
1460 // cache size supplied via property
1461 if ( mlt_properties_get( properties, "cache" ) )
1464 cache_size = mlt_properties_get_int( properties, "cache" );
1466 if ( mlt_properties_get_int( properties, "noimagecache" ) )
1468 // create cache if not disabled
1469 if ( !cache_supplied || cache_size > 0 )
1470 self->image_cache = mlt_cache_init();
1471 // set cache size if supplied
1472 if ( self->image_cache && cache_supplied )
1473 mlt_cache_set_size( self->image_cache, cache_size );
1475 if ( self->image_cache )
1477 mlt_frame original = mlt_cache_get_frame( self->image_cache, position );
1480 mlt_properties orig_props = MLT_FRAME_PROPERTIES( original );
1483 *buffer = mlt_properties_get_data( orig_props, "alpha", &size );
1485 mlt_frame_set_alpha( frame, *buffer, size, NULL );
1486 *buffer = mlt_properties_get_data( orig_props, "image", &size );
1487 mlt_frame_set_image( frame, *buffer, size, NULL );
1488 mlt_properties_set_data( frame_properties, "avformat.image_cache", original, 0, (mlt_destructor) mlt_frame_close, NULL );
1489 *format = mlt_properties_get_int( orig_props, "format" );
1491 // Set the resolution
1492 *width = codec_context->width;
1493 *height = codec_context->height;
1495 // Workaround 1088 encodings missing cropping info.
1496 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1500 goto exit_get_image;
1505 // We may want to use the source fps if available
1506 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1507 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1509 // This is the physical frame position in the source
1510 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1512 // Determines if we have to decode all frames in a sequence
1513 // Temporary hack to improve intra frame only
1514 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1515 strcmp( codec_context->codec->name, "dnxhd" ) &&
1516 strcmp( codec_context->codec->name, "dvvideo" ) &&
1517 strcmp( codec_context->codec->name, "huffyuv" ) &&
1518 strcmp( codec_context->codec->name, "mjpeg" ) &&
1519 strcmp( codec_context->codec->name, "rawvideo" ) );
1521 double delay = mlt_properties_get_double( properties, "video_delay" );
1523 // Seek if necessary
1524 const char *interp = mlt_properties_get( frame_properties, "rescale.interp" );
1525 int preseek = must_decode
1526 #if defined(FFUDIV) && LIBAVFORMAT_VERSION_INT >= ((53<<16)+(24<<8)+2)
1527 && ( interp && strcmp( interp, "nearest" ) )
1529 && codec_context->has_b_frames;
1530 int paused = seek_video( self, position, req_position, preseek );
1532 // Seek might have reopened the file
1533 context = self->video_format;
1534 stream = context->streams[ self->video_index ];
1535 codec_context = stream->codec;
1536 if ( *format == mlt_image_none ||
1537 codec_context->pix_fmt == PIX_FMT_ARGB ||
1538 codec_context->pix_fmt == PIX_FMT_RGBA ||
1539 codec_context->pix_fmt == PIX_FMT_ABGR ||
1540 codec_context->pix_fmt == PIX_FMT_BGRA )
1541 *format = pick_pix_format( codec_context->pix_fmt );
1543 // Duplicate the last image if necessary
1544 if ( self->av_frame && self->av_frame->linesize[0]
1545 && ( paused || self->current_position >= req_position ) )
1548 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1550 // Workaround 1088 encodings missing cropping info.
1551 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1554 if ( self->vdpau && self->vdpau->buffer )
1557 picture.data[0] = self->vdpau->buffer;
1558 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1559 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1560 picture.linesize[0] = codec_context->width;
1561 picture.linesize[1] = codec_context->width / 2;
1562 picture.linesize[2] = codec_context->width / 2;
1563 convert_image( self, (AVFrame*) &picture, *buffer,
1564 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1568 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1569 format, *width, *height, &alpha );
1576 int64_t int_position = 0;
1577 int decode_errors = 0;
1579 // Construct an AVFrame for YUV422 conversion
1580 if ( !self->av_frame )
1581 self->av_frame = avcodec_alloc_frame( );
1583 while( ret >= 0 && !got_picture )
1586 if ( self->pkt.stream_index == self->video_index )
1587 av_free_packet( &self->pkt );
1588 av_init_packet( &self->pkt );
1589 pthread_mutex_lock( &self->packets_mutex );
1590 if ( mlt_deque_count( self->vpackets ) )
1592 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1598 ret = av_read_frame( context, &self->pkt );
1599 if ( ret >= 0 && !self->seekable && self->pkt.stream_index == self->audio_index )
1601 if ( !av_dup_packet( &self->pkt ) )
1603 AVPacket *tmp = malloc( sizeof(AVPacket) );
1605 mlt_deque_push_back( self->apackets, tmp );
1609 pthread_mutex_unlock( &self->packets_mutex );
1611 // We only deal with video from the selected video_index
1612 if ( ret >= 0 && self->pkt.stream_index == self->video_index && self->pkt.size > 0 )
1614 int64_t pts = best_pts( self, self->pkt.pts, self->pkt.dts );
1615 if ( pts != AV_NOPTS_VALUE )
1617 if ( !self->seekable && self->first_pts == AV_NOPTS_VALUE )
1618 self->first_pts = pts;
1619 if ( self->first_pts != AV_NOPTS_VALUE )
1620 pts -= self->first_pts;
1621 else if ( context->start_time != AV_NOPTS_VALUE )
1622 pts -= context->start_time;
1623 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.5 );
1624 if ( int_position == self->last_position )
1625 int_position = self->last_position + 1;
1627 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1628 "V pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1629 self->pkt.pts, self->pkt.dts, req_position, self->current_position, int_position );
1631 // Make a dumb assumption on streams that contain wild timestamps
1632 if ( abs( req_position - int_position ) > 999 )
1634 int_position = req_position;
1635 mlt_log_warning( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!\n" );
1637 self->last_position = int_position;
1640 if ( must_decode || int_position >= req_position )
1645 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1647 vdpau_decoder_init( self );
1649 self->vdpau->is_decoded = 0;
1652 codec_context->reordered_opaque = int_position;
1653 if ( int_position >= req_position )
1654 codec_context->skip_loop_filter = AVDISCARD_NONE;
1655 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1656 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &self->pkt );
1658 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, self->pkt.data, self->pkt.size );
1660 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1663 if ( ++decode_errors <= 10 )
1674 // Get position of reordered frame
1675 int_position = self->av_frame->reordered_opaque;
1676 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(106<<8)+0))
1677 pts = best_pts( self, self->av_frame->pkt_pts, self->av_frame->pkt_dts );
1678 if ( pts != AV_NOPTS_VALUE )
1680 if ( self->first_pts != AV_NOPTS_VALUE )
1681 pts -= self->first_pts;
1682 else if ( context->start_time != AV_NOPTS_VALUE )
1683 pts -= context->start_time;
1684 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.5 );
1688 if ( int_position < req_position )
1690 else if ( int_position >= req_position )
1691 codec_context->skip_loop_filter = AVDISCARD_NONE;
1693 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, self->pkt.flags & PKT_FLAG_KEY );
1696 // Now handle the picture if we have one
1699 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1701 // Workaround 1088 encodings missing cropping info.
1702 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1707 if ( self->vdpau->is_decoded )
1709 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1711 uint32_t pitches[3];
1712 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1714 if ( !self->vdpau->buffer )
1715 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1716 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1717 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1718 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1719 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1720 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1721 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1723 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1724 if ( status == VDP_STATUS_OK )
1726 convert_image( self, self->av_frame, *buffer, PIX_FMT_YUV420P,
1727 format, *width, *height, &alpha );
1731 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1732 image_size = self->vdpau->is_decoded = 0;
1737 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1738 image_size = got_picture = 0;
1743 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1744 format, *width, *height, &alpha );
1745 self->top_field_first |= self->av_frame->top_field_first;
1746 self->current_position = int_position;
1754 // Free packet data if not video and not live audio packet
1755 if ( self->pkt.stream_index != self->video_index &&
1756 !( !self->seekable && self->pkt.stream_index == self->audio_index ) )
1757 av_free_packet( &self->pkt );
1763 mlt_frame_set_alpha( frame, alpha, (*width) * (*height), mlt_pool_release );
1765 if ( image_size > 0 && self->image_cache )
1767 mlt_properties_set_int( frame_properties, "format", *format );
1768 mlt_cache_put_frame( self->image_cache, frame );
1771 // Try to duplicate last image if there was a decoding failure
1772 // TODO: with multithread decoding a partial frame decoding resulting
1773 // in failure also resets av_frame making test below fail.
1774 if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1777 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1779 // Workaround 1088 encodings missing cropping info.
1780 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1783 if ( self->vdpau && self->vdpau->buffer )
1786 picture.data[0] = self->vdpau->buffer;
1787 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1788 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1789 picture.linesize[0] = codec_context->width;
1790 picture.linesize[1] = codec_context->width / 2;
1791 picture.linesize[2] = codec_context->width / 2;
1792 convert_image( self, (AVFrame*) &picture, *buffer,
1793 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1797 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1798 format, *width, *height, &alpha );
1803 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1804 self->video_expected = position + 1;
1808 pthread_mutex_unlock( &self->video_mutex );
1810 // Set the progressive flag
1811 if ( mlt_properties_get( properties, "force_progressive" ) )
1812 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1813 else if ( self->av_frame )
1814 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1816 // Set the field order property for this frame
1817 if ( mlt_properties_get( properties, "force_tff" ) )
1818 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1820 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1822 // Set immutable properties of the selected track's (or overridden) source attributes.
1823 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1824 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1825 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1826 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1828 // If we already have RGB, then the full range processing either happened already
1829 // or does not apply (RGB source).
1830 if ( *format == mlt_image_rgb24 || *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1831 mlt_properties_set( frame_properties, "force_full_luma", NULL );
1833 return !got_picture;
1836 /** Process properties as AVOptions and apply to AV context obj
1839 static void apply_properties( void *obj, mlt_properties properties, int flags )
1842 int count = mlt_properties_count( properties );
1843 for ( i = 0; i < count; i++ )
1845 const char *opt_name = mlt_properties_get_name( properties, i );
1846 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
1847 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1849 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1851 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1854 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1855 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1856 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1857 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1858 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1859 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1861 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1867 /** Initialize the video codec context.
1870 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1872 // Initialise the codec if necessary
1873 if ( !self->video_codec )
1875 // Get the video stream
1876 AVStream *stream = self->video_format->streams[ index ];
1878 // Get codec context
1879 AVCodecContext *codec_context = stream->codec;
1882 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1884 if ( codec_context->codec_id == CODEC_ID_H264 )
1886 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1888 if ( vdpau_init( self ) )
1890 self->video_codec = codec_context;
1891 if ( !vdpau_decoder_init( self ) )
1896 codec = avcodec_find_decoder( codec_context->codec_id );
1900 // Initialise multi-threading
1901 int thread_count = mlt_properties_get_int( properties, "threads" );
1902 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1903 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1904 if ( thread_count > 1 )
1905 codec_context->thread_count = thread_count;
1907 // If we don't have a codec and we can't initialise it, we can't do much more...
1908 pthread_mutex_lock( &self->open_mutex );
1909 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1910 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1912 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1915 // Now store the codec with its destructor
1916 self->video_codec = codec_context;
1920 // Remember that we can't use this later
1921 self->video_index = -1;
1922 pthread_mutex_unlock( &self->open_mutex );
1925 pthread_mutex_unlock( &self->open_mutex );
1927 // Process properties as AVOptions
1928 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1929 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1930 if ( codec->priv_class && codec_context->priv_data )
1931 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1934 // Reset some image properties
1935 if ( self->video_codec )
1937 mlt_properties_set_int( properties, "width", self->video_codec->width );
1938 mlt_properties_set_int( properties, "height", self->video_codec->height );
1940 // For DV, we'll just use the saved aspect ratio
1941 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1942 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1944 // Determine the fps first from the codec
1945 double source_fps = (double) self->video_codec->time_base.den /
1946 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1949 // If the muxer reports a frame rate different than the codec
1950 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1951 double muxer_fps = av_q2d( stream->avg_frame_rate );
1952 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1953 muxer_fps = av_q2d( stream->r_frame_rate );
1955 double muxer_fps = av_q2d( stream->r_frame_rate );
1957 // Choose the lesser - the wrong tends to be off by some multiple of 10
1958 source_fps = FFMIN( source_fps, muxer_fps );
1959 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1961 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1962 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1964 else if ( muxer_fps > 0 )
1966 AVRational frame_rate = stream->r_frame_rate;
1967 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1968 // avg_frame_rate gives some approximate value that does not well match the media.
1969 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1970 // results in some very choppy output, but some value slightly different works
1972 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1973 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1974 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
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 );
1981 source_fps = mlt_producer_get_fps( self->parent );
1982 AVRational frame_rate = av_d2q( source_fps, 255 );
1983 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1984 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1987 if ( mlt_properties_get( properties, "force_fps" ) )
1989 double source_fps = mlt_properties_get_double( properties, "force_fps" );
1990 AVRational fps = av_d2q( source_fps, 1024 );
1991 stream->time_base.num *= mlt_properties_get_int( properties, "meta.media.frame_rate_num" ) * fps.den;
1992 stream->time_base.den *= mlt_properties_get_int( properties, "meta.media.frame_rate_den" ) * fps.num;
1993 mlt_properties_set_int( properties, "meta.media.frame_rate_num", fps.num );
1994 mlt_properties_set_int( properties, "meta.media.frame_rate_den", fps.den );
1997 // Set the YUV colorspace from override or detect
1998 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1999 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
2000 if ( ! self->colorspace )
2002 switch ( self->video_codec->colorspace )
2004 case AVCOL_SPC_SMPTE240M:
2005 self->colorspace = 240;
2007 case AVCOL_SPC_BT470BG:
2008 case AVCOL_SPC_SMPTE170M:
2009 self->colorspace = 601;
2011 case AVCOL_SPC_BT709:
2012 self->colorspace = 709;
2015 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
2016 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
2021 // Let apps get chosen colorspace
2022 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
2024 self->full_luma = -1;
2025 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(72<<8)+2)
2026 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent), "color_range %d\n", codec_context->color_range );
2027 if ( codec_context->color_range == AVCOL_RANGE_JPEG )
2028 self->full_luma = 1;
2030 if ( mlt_properties_get( properties, "set.force_full_luma" ) )
2031 self->full_luma = mlt_properties_get_int( properties, "set.force_full_luma" );
2033 return self->video_codec && self->video_index > -1;
2036 /** Set up video handling.
2039 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
2042 mlt_producer producer = self->parent;
2044 // Get the properties
2045 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2047 // Fetch the video format context
2048 AVFormatContext *context = self->video_format;
2050 // Get the video_index
2051 int index = mlt_properties_get_int( properties, "video_index" );
2053 // Reopen the file if necessary
2054 if ( !context && index > -1 )
2056 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2057 mlt_properties_get( properties, "resource" ), 1 );
2058 context = self->video_format;
2061 // Exception handling for video_index
2062 if ( context && index >= (int) context->nb_streams )
2064 // Get the last video stream
2065 for ( index = context->nb_streams - 1;
2066 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
2068 mlt_properties_set_int( properties, "video_index", index );
2070 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
2072 // Invalidate the video stream
2074 mlt_properties_set_int( properties, "video_index", index );
2077 // Update the video properties if the index changed
2078 if ( index != self->video_index )
2080 // Reset the video properties if the index changed
2081 self->video_index = index;
2082 pthread_mutex_lock( &self->open_mutex );
2083 if ( self->video_codec )
2084 avcodec_close( self->video_codec );
2085 self->video_codec = NULL;
2086 pthread_mutex_unlock( &self->open_mutex );
2089 // Get the frame properties
2090 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2093 if ( context && index > -1 && video_codec_init( self, index, properties ) )
2095 // Set the frame properties
2096 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
2097 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
2098 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
2100 // Set the width and height
2101 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
2102 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
2103 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
2104 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
2105 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
2106 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
2108 // Workaround 1088 encodings missing cropping info.
2109 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
2111 mlt_properties_set_int( properties, "meta.media.height", 1080 );
2114 // Add our image operation
2115 mlt_frame_push_service( frame, self );
2116 mlt_frame_push_get_image( frame, producer_get_image );
2120 // If something failed, use test card image
2121 mlt_properties_set_int( frame_properties, "test_image", 1 );
2125 static int seek_audio( producer_avformat self, mlt_position position, double timecode )
2129 // Seek if necessary
2130 if ( self->seekable && position != self->audio_expected )
2132 if ( position + 1 == self->audio_expected )
2134 // We're paused - silence required
2137 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
2139 AVFormatContext *context = self->audio_format;
2140 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
2141 if ( context->start_time != AV_NOPTS_VALUE )
2142 timestamp += context->start_time;
2143 if ( timestamp < 0 )
2146 // Set to the real timecode
2147 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
2150 // Clear the usage in the audio buffer
2151 int i = MAX_AUDIO_STREAMS + 1;
2153 self->audio_used[i - 1] = 0;
2159 static int sample_bytes( AVCodecContext *context )
2161 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2162 return av_get_bytes_per_sample( context->sample_fmt );
2163 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2164 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2166 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2170 static void planar_to_interleaved( uint8_t *dest, uint8_t *src, int samples, int channels, int bytes_per_sample )
2173 for ( s = 0; s < samples; s++ )
2175 for ( c = 0; c < channels; c++ )
2177 memcpy( dest, src + ( c * samples + s ) * bytes_per_sample, bytes_per_sample );
2178 dest += bytes_per_sample;
2183 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2185 // Fetch the audio_format
2186 AVFormatContext *context = self->audio_format;
2188 // Get the current stream index
2189 int index = pkt.stream_index;
2191 // Get codec context
2192 AVCodecContext *codec_context = self->audio_codec[ index ];
2194 // Obtain the resample context if it exists (not always needed)
2195 ReSampleContext *resample = self->audio_resample[ index ];
2197 // Obtain the audio buffers
2198 uint8_t *audio_buffer = self->audio_buffer[ index ];
2199 uint8_t *decode_buffer = self->decode_buffer[ index ];
2201 int audio_used = self->audio_used[ index ];
2202 uint8_t *ptr = pkt.data;
2206 while ( ptr && ret >= 0 && len > 0 )
2208 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2209 int data_size = self->audio_buffer_size[ index ];
2212 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2213 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2214 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2215 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2217 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2221 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2225 pkt.size = len -= ret;
2226 pkt.data = ptr += ret;
2228 // If decoded successfully
2229 if ( data_size > 0 )
2231 // Figure out how many samples will be needed after resampling
2232 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2233 int samples_needed = self->resample_factor * convert_samples;
2235 // Resize audio buffer to prevent overflow
2236 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2238 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2239 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2243 // Copy to audio buffer while resampling
2244 uint8_t *source = decode_buffer;
2245 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2246 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2250 uint8_t *source = decode_buffer;
2251 uint8_t *dest = &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ];
2252 switch ( codec_context->sample_fmt )
2254 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2255 case AV_SAMPLE_FMT_U8P:
2256 case AV_SAMPLE_FMT_S16P:
2257 case AV_SAMPLE_FMT_S32P:
2258 case AV_SAMPLE_FMT_FLTP:
2259 planar_to_interleaved( dest, source, convert_samples, codec_context->channels, sizeof_sample );
2263 // Straight copy to audio buffer
2264 memcpy( dest, decode_buffer, data_size );
2266 audio_used += convert_samples;
2270 while ( *ignore && audio_used )
2273 audio_used -= audio_used > samples ? samples : audio_used;
2274 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2275 audio_used * sizeof_sample );
2280 // If we're behind, ignore this packet
2281 // Skip this on non-seekable, audio-only inputs.
2282 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2284 int64_t pts = pkt.pts;
2285 if ( self->first_pts != 0 )
2286 pts -= self->first_pts;
2287 else if ( context->start_time != AV_NOPTS_VALUE )
2288 pts -= context->start_time;
2289 double timebase = av_q2d( context->streams[ index ]->time_base );
2290 int64_t int_position = ( int64_t )( timebase * pts * fps + 0.5 );
2291 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2293 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
2294 "A pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
2295 pkt.pts, pkt.dts, req_position, self->current_position, int_position );
2297 if ( int_position > 0 )
2299 if ( int_position < req_position )
2300 // We are behind, so skip some
2301 *ignore = req_position - int_position;
2302 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2303 // We are ahead, so seek backwards some more
2304 seek_audio( self, req_position, timecode - 1.0 );
2308 self->audio_used[ index ] = audio_used;
2313 /** Get the audio from a frame.
2315 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2318 producer_avformat self = mlt_frame_pop_audio( frame );
2320 pthread_mutex_lock( &self->audio_mutex );
2322 // Obtain the frame number of this frame
2323 mlt_position position = mlt_frame_original_position( frame );
2325 // Calculate the real time code
2326 double real_timecode = producer_time_of_frame( self->parent, position );
2328 // Get the producer fps
2329 double fps = mlt_producer_get_fps( self->parent );
2331 // Number of frames to ignore (for ffwd)
2332 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2334 // Flag for paused (silence)
2335 int paused = seek_audio( self, position, real_timecode );
2337 // Initialize ignore for all streams from the seek return value
2338 int i = MAX_AUDIO_STREAMS;
2340 ignore[i] = ignore[0];
2342 // Fetch the audio_format
2343 AVFormatContext *context = self->audio_format;
2345 int sizeof_sample = sizeof( int16_t );
2347 // Determine the tracks to use
2348 int index = self->audio_index;
2349 int index_max = self->audio_index + 1;
2350 if ( self->audio_index == INT_MAX )
2353 index_max = FFMIN( MAX_AUDIO_STREAMS, context->nb_streams );
2354 *channels = self->total_channels;
2355 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2356 *frequency = FFMAX( self->max_frequency, *frequency );
2359 // Initialize the resamplers and buffers
2360 for ( ; index < index_max && index < MAX_AUDIO_STREAMS; index++ )
2362 // Get codec context
2363 AVCodecContext *codec_context = self->audio_codec[ index ];
2365 if ( codec_context && !self->audio_buffer[ index ] )
2367 #if LIBAVCODEC_VERSION_INT < ((54<<16)+(26<<8)+0)
2368 // Check for resample and create if necessary
2369 if ( codec_context->channels <= 2 )
2371 // Determine by how much resampling will increase number of samples
2372 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2373 resample_factor *= (double) *frequency / codec_context->sample_rate;
2374 if ( resample_factor > self->resample_factor )
2375 self->resample_factor = resample_factor;
2377 // Create the resampler
2378 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2379 self->audio_resample[ index ] = av_audio_resample_init(
2380 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2381 codec_context->channels, *frequency, codec_context->sample_rate,
2382 AV_SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2384 self->audio_resample[ index ] = audio_resample_init(
2385 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2386 codec_context->channels, *frequency, codec_context->sample_rate );
2392 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2393 sizeof_sample = sample_bytes( codec_context );
2396 // Check for audio buffer and create if necessary
2397 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2398 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2400 // Check for decoder buffer and create if necessary
2401 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2405 // Get the audio if required
2406 if ( !paused && *frequency > 0 )
2412 av_init_packet( &pkt );
2414 // If not resampling, give consumer more than requested.
2415 // It requested number samples based on requested frame rate.
2416 // Do not clean this up with a samples *= ...!
2417 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2418 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2420 while ( ret >= 0 && !got_audio )
2422 // Check if the buffer already contains the samples required
2423 if ( self->audio_index != INT_MAX &&
2424 self->audio_used[ self->audio_index ] >= *samples &&
2425 ignore[ self->audio_index ] == 0 )
2430 else if ( self->audio_index == INT_MAX )
2432 // Check if there is enough audio for all streams
2434 for ( index = 0; got_audio && index < index_max; index++ )
2435 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2442 pthread_mutex_lock( &self->packets_mutex );
2443 if ( mlt_deque_count( self->apackets ) )
2445 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2451 ret = av_read_frame( context, &pkt );
2452 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2454 if ( !av_dup_packet( &pkt ) )
2456 AVPacket *tmp = malloc( sizeof(AVPacket) );
2458 mlt_deque_push_back( self->vpackets, tmp );
2462 pthread_mutex_unlock( &self->packets_mutex );
2464 // We only deal with audio from the selected audio index
2465 index = pkt.stream_index;
2466 if ( index < MAX_AUDIO_STREAMS && ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2467 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2469 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2470 self->audio_codec[index]->channels : *channels;
2471 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2474 if ( self->seekable || index != self->video_index )
2475 av_free_packet( &pkt );
2479 // Set some additional return values
2480 *format = mlt_audio_s16;
2481 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2483 index = self->audio_index;
2484 *channels = self->audio_codec[ index ]->channels;
2485 *frequency = self->audio_codec[ index ]->sample_rate;
2486 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2487 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2489 else if ( self->audio_index == INT_MAX )
2491 for ( index = 0; index < index_max; index++ )
2492 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2494 // XXX: This only works if all audio tracks have the same sample format.
2495 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2496 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2501 // Allocate and set the frame's audio buffer
2502 int size = mlt_audio_format_size( *format, *samples, *channels );
2503 *buffer = mlt_pool_alloc( size );
2504 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2506 // Interleave tracks if audio_index=all
2507 if ( self->audio_index == INT_MAX )
2509 uint8_t *dest = *buffer;
2511 for ( i = 0; i < *samples; i++ )
2513 for ( index = 0; index < index_max; index++ )
2514 if ( self->audio_codec[ index ] )
2516 int current_channels = self->audio_codec[ index ]->channels;
2517 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2518 memcpy( dest, src, current_channels * sizeof_sample );
2519 dest += current_channels * sizeof_sample;
2522 for ( index = 0; index < index_max; index++ )
2523 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2525 int current_channels = self->audio_codec[ index ]->channels;
2526 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2527 self->audio_used[index] -= *samples;
2528 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2531 // Copy a single track to the output buffer
2534 index = self->audio_index;
2536 // Now handle the audio if we have enough
2537 if ( self->audio_used[ index ] > 0 )
2539 uint8_t *src = self->audio_buffer[ index ];
2540 // copy samples from audio_buffer
2541 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2542 memcpy( *buffer, src, size * *channels * sizeof_sample );
2543 // supply the remaining requested samples as silence
2544 if ( *samples > self->audio_used[ index ] )
2545 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2546 // reposition the samples within audio_buffer
2547 self->audio_used[ index ] -= size;
2548 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2552 // Otherwise fill with silence
2553 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2559 // Get silence and don't touch the context
2560 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2563 // Regardless of speed (other than paused), we expect to get the next frame
2565 self->audio_expected = position + 1;
2567 pthread_mutex_unlock( &self->audio_mutex );
2572 /** Initialize the audio codec context.
2575 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2577 // Initialise the codec if necessary
2578 if ( !self->audio_codec[ index ] )
2580 // Get codec context
2581 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2584 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2586 // If we don't have a codec and we can't initialise it, we can't do much more...
2587 pthread_mutex_lock( &self->open_mutex );
2588 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2589 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2591 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2594 // Now store the codec with its destructor
2595 if ( self->audio_codec[ index ] )
2596 avcodec_close( self->audio_codec[ index ] );
2597 self->audio_codec[ index ] = codec_context;
2601 // Remember that we can't use self later
2602 self->audio_index = -1;
2604 pthread_mutex_unlock( &self->open_mutex );
2606 // Process properties as AVOptions
2607 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2608 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
2609 if ( codec && codec->priv_class && codec_context->priv_data )
2610 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2613 return self->audio_codec[ index ] && self->audio_index > -1;
2616 /** Set up audio handling.
2619 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2622 mlt_producer producer = self->parent;
2624 // Get the properties
2625 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2627 // Fetch the audio format context
2628 AVFormatContext *context = self->audio_format;
2630 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2632 // Get the audio_index
2633 int index = mlt_properties_get_int( properties, "audio_index" );
2635 // Handle all audio tracks
2636 if ( self->audio_index > -1 &&
2637 mlt_properties_get( properties, "audio_index" ) &&
2638 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2641 // Reopen the file if necessary
2642 if ( !context && self->audio_index > -1 && index > -1 )
2644 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2645 mlt_properties_get( properties, "resource" ), 1 );
2646 context = self->audio_format;
2649 // Exception handling for audio_index
2650 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2652 for ( index = context->nb_streams - 1;
2653 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2655 mlt_properties_set_int( properties, "audio_index", index );
2657 if ( context && index > -1 && index < INT_MAX &&
2658 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2660 index = self->audio_index;
2661 mlt_properties_set_int( properties, "audio_index", index );
2663 if ( context && index > -1 && index < INT_MAX &&
2664 pick_audio_format( context->streams[ index ]->codec->sample_fmt ) == mlt_audio_none )
2669 // Update the audio properties if the index changed
2670 if ( context && index > -1 && index != self->audio_index )
2672 pthread_mutex_lock( &self->open_mutex );
2673 if ( self->audio_codec[ self->audio_index ] )
2674 avcodec_close( self->audio_codec[ self->audio_index ] );
2675 self->audio_codec[ self->audio_index ] = NULL;
2676 pthread_mutex_unlock( &self->open_mutex );
2678 if ( self->audio_index != -1 )
2679 self->audio_index = index;
2684 if ( context && index == INT_MAX )
2686 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2687 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2688 for ( index = 0; index < context->nb_streams; index++ )
2690 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2691 audio_codec_init( self, index, properties );
2694 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2696 // Set the frame properties
2697 if ( index < MAX_AUDIO_STREAMS )
2699 mlt_properties_set_int( frame_properties, "audio_frequency", self->audio_codec[ index ]->sample_rate );
2700 mlt_properties_set_int( frame_properties, "audio_channels", self->audio_codec[ index ]->channels );
2703 if ( context && index > -1 )
2705 // Add our audio operation
2706 mlt_frame_push_audio( frame, self );
2707 mlt_frame_push_audio( frame, producer_get_audio );
2711 /** Our get frame implementation.
2714 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2716 // Access the private data
2717 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2718 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2719 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2724 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2725 producer->child = self;
2726 self->parent = producer;
2727 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2728 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2731 // Create an empty frame
2732 *frame = mlt_frame_init( service);
2736 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2740 mlt_cache_item_close( cache_item );
2744 // Update timecode on the frame we're creating
2745 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2748 producer_set_up_video( self, *frame );
2751 producer_set_up_audio( self, *frame );
2753 // Set the position of this producer
2754 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2755 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "original_position", position );
2757 // Calculate the next timecode
2758 mlt_producer_prepare_next( producer );
2763 static void producer_avformat_close( producer_avformat self )
2765 mlt_log_debug( NULL, "producer_avformat_close\n" );
2767 // Cleanup av contexts
2768 av_free_packet( &self->pkt );
2769 av_free( self->av_frame );
2770 pthread_mutex_lock( &self->open_mutex );
2772 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2774 if ( self->audio_resample[i] )
2775 audio_resample_close( self->audio_resample[i] );
2776 mlt_pool_release( self->audio_buffer[i] );
2777 av_free( self->decode_buffer[i] );
2778 if ( self->audio_codec[i] )
2779 avcodec_close( self->audio_codec[i] );
2780 self->audio_codec[i] = NULL;
2782 if ( self->video_codec )
2783 avcodec_close( self->video_codec );
2784 self->video_codec = NULL;
2786 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2787 if ( self->dummy_context )
2788 avformat_close_input( &self->dummy_context );
2789 if ( self->seekable && self->audio_format )
2790 avformat_close_input( &self->audio_format );
2791 if ( self->video_format )
2792 avformat_close_input( &self->video_format );
2794 if ( self->dummy_context )
2795 av_close_input_file( self->dummy_context );
2796 if ( self->seekable && self->audio_format )
2797 av_close_input_file( self->audio_format );
2798 if ( self->video_format )
2799 av_close_input_file( self->video_format );
2801 pthread_mutex_unlock( &self->open_mutex );
2803 vdpau_producer_close( self );
2805 if ( self->image_cache )
2806 mlt_cache_close( self->image_cache );
2808 // Cleanup the mutexes
2809 if ( self->is_mutex_init )
2811 pthread_mutex_destroy( &self->audio_mutex );
2812 pthread_mutex_destroy( &self->video_mutex );
2813 pthread_mutex_destroy( &self->packets_mutex );
2814 pthread_mutex_destroy( &self->open_mutex );
2817 // Cleanup the packet queues
2819 if ( self->apackets )
2821 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2823 av_free_packet( pkt );
2826 mlt_deque_close( self->apackets );
2827 self->apackets = NULL;
2829 if ( self->vpackets )
2831 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2833 av_free_packet( pkt );
2836 mlt_deque_close( self->vpackets );
2837 self->vpackets = NULL;
2843 static void producer_close( mlt_producer parent )
2845 // Remove this instance from the cache
2846 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2849 parent->close = NULL;
2850 mlt_producer_close( parent );