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 );
159 static mlt_audio_format pick_audio_format( int sample_fmt );
165 /** Constructor for libavformat.
168 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
170 if ( list_components( file ) )
173 mlt_producer producer = NULL;
175 // Check that we have a non-NULL argument
178 // Construct the producer
179 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
180 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
183 if ( mlt_producer_init( producer, self ) == 0 )
185 self->parent = producer;
187 // Get the properties
188 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
190 // Set the resource property (required for all producers)
191 mlt_properties_set( properties, "resource", file );
193 // Register transport implementation with the producer
194 producer->close = (mlt_destructor) producer_close;
196 // Register our get_frame implementation
197 producer->get_frame = producer_get_frame;
199 if ( strcmp( service, "avformat-novalidate" ) )
202 if ( producer_open( self, profile, file, 1 ) != 0 )
205 mlt_producer_close( producer );
207 producer_avformat_close( self );
209 else if ( self->seekable )
211 // Close the file to release resources for large playlists - reopen later as needed
212 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
213 if ( self->audio_format )
214 avformat_close_input( &self->audio_format );
215 if ( self->video_format )
216 avformat_close_input( &self->video_format );
218 if ( self->audio_format )
219 av_close_input_file( self->audio_format );
220 if ( self->video_format )
221 av_close_input_file( self->video_format );
223 self->audio_format = NULL;
224 self->video_format = NULL;
229 // Default the user-selectable indices from the auto-detected indices
230 mlt_properties_set_int( properties, "audio_index", self->audio_index );
231 mlt_properties_set_int( properties, "video_index", self->video_index );
233 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
235 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
242 int list_components( char* file )
246 // Report information about available demuxers and codecs as YAML Tiny
247 if ( file && strstr( file, "f-list" ) )
249 fprintf( stderr, "---\nformats:\n" );
250 AVInputFormat *format = NULL;
251 while ( ( format = av_iformat_next( format ) ) )
252 fprintf( stderr, " - %s\n", format->name );
253 fprintf( stderr, "...\n" );
256 if ( file && strstr( file, "acodec-list" ) )
258 fprintf( stderr, "---\naudio_codecs:\n" );
259 AVCodec *codec = NULL;
260 while ( ( codec = av_codec_next( codec ) ) )
261 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
262 fprintf( stderr, " - %s\n", codec->name );
263 fprintf( stderr, "...\n" );
266 if ( file && strstr( file, "vcodec-list" ) )
268 fprintf( stderr, "---\nvideo_codecs:\n" );
269 AVCodec *codec = NULL;
270 while ( ( codec = av_codec_next( codec ) ) )
271 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
272 fprintf( stderr, " - %s\n", codec->name );
273 fprintf( stderr, "...\n" );
280 /** Find the default streams.
283 static mlt_properties find_default_streams( producer_avformat self )
287 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
288 AVDictionaryEntry *tag = NULL;
290 AVMetadataTag *tag = NULL;
292 AVFormatContext *context = self->video_format;
293 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
295 // Default to the first audio and video streams found
296 self->audio_index = -1;
297 self->video_index = -1;
299 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
301 // Allow for multiple audio and video streams in the file and select first of each (if available)
302 for( i = 0; i < context->nb_streams; i++ )
304 // Get the codec context
305 AVStream *stream = context->streams[ i ];
306 if ( ! stream ) continue;
307 AVCodecContext *codec_context = stream->codec;
308 if ( ! codec_context ) continue;
309 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
310 if ( ! codec ) continue;
312 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
314 // Determine the type and obtain the first index of each type
315 switch( codec_context->codec_type )
317 case CODEC_TYPE_VIDEO:
318 // Use first video stream
319 if ( self->video_index < 0 )
320 self->video_index = i;
321 mlt_properties_set( meta_media, key, "video" );
322 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
323 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
324 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
325 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
326 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
327 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
329 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
332 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
333 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
334 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
336 snprintf( key, sizeof(key), "meta.media.%d.codec.width", i );
337 mlt_properties_set_int( meta_media, key, codec_context->width );
338 snprintf( key, sizeof(key), "meta.media.%d.codec.height", i );
339 mlt_properties_set_int( meta_media, key, codec_context->height );
340 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
341 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
342 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
343 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
344 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(3<<8)+0)
345 mlt_properties_set( meta_media, key, av_get_pix_fmt_name( codec_context->pix_fmt ) );
347 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
349 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
350 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
351 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
352 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
353 switch ( codec_context->colorspace )
355 case AVCOL_SPC_SMPTE240M:
356 mlt_properties_set_int( meta_media, key, 240 );
358 case AVCOL_SPC_BT470BG:
359 case AVCOL_SPC_SMPTE170M:
360 mlt_properties_set_int( meta_media, key, 601 );
362 case AVCOL_SPC_BT709:
363 mlt_properties_set_int( meta_media, key, 709 );
366 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
367 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
372 case CODEC_TYPE_AUDIO:
373 if ( !codec_context->channels )
375 // Use first audio stream
376 if ( self->audio_index < 0 && pick_audio_format( codec_context->sample_fmt ) != mlt_audio_none )
377 self->audio_index = i;
379 mlt_properties_set( meta_media, key, "audio" );
380 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
381 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
382 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
383 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
384 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
385 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
387 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
388 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
389 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
390 mlt_properties_set_int( meta_media, key, codec_context->channels );
395 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
396 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
397 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
398 mlt_properties_set( meta_media, key, codec->name );
399 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
400 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
401 mlt_properties_set( meta_media, key, codec->long_name );
403 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
404 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
405 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
406 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
407 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
408 // mlt_properties_set_int( meta_media, key, codec_context->profile );
409 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
410 // mlt_properties_set_int( meta_media, key, codec_context->level );
413 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
414 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
415 while ( ( tag = av_dict_get( stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
417 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
420 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
422 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
423 mlt_properties_set( meta_media, key, tag->value );
428 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
429 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
430 while ( ( tag = av_dict_get( context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
432 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
435 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
437 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
438 mlt_properties_set( meta_media, key, tag->value );
442 if ( context->title && strcmp( context->title, "" ) )
443 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
444 if ( context->author && strcmp( context->author, "" ) )
445 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
446 if ( context->copyright && strcmp( context->copyright, "" ) )
447 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
448 if ( context->comment )
449 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
450 if ( context->album )
451 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
453 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
454 if ( context->track )
455 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
461 static inline int dv_is_pal( AVPacket *pkt )
463 return pkt->data[3] & 0x80;
466 static int dv_is_wide( AVPacket *pkt )
468 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
470 for ( ; i < pkt->size; i += 5 /* packet size */ )
472 if ( pkt->data[ i ] == 0x61 )
474 uint8_t x = pkt->data[ i + 2 ] & 0x7;
475 return ( x == 2 ) || ( x == 7 );
481 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
483 double aspect_ratio = 1.0;
485 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
489 if ( dv_is_pal( pkt ) )
491 if ( dv_is_wide( pkt ) )
493 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
494 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
498 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
499 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
504 if ( dv_is_wide( pkt ) )
506 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
507 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
511 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
512 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
519 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
520 stream->sample_aspect_ratio;
522 codec_context->sample_aspect_ratio;
524 // Override FFmpeg's notion of DV aspect ratios, which are
525 // based upon a width of 704. Since we do not have a normaliser
526 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
527 // we just coerce the values to facilitate a passive behaviour through
528 // the rescale normaliser when using equivalent producers and consumers.
529 // = display_aspect / (width * height)
530 if ( ar.num == 10 && ar.den == 11 )
533 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
534 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
536 else if ( ar.num == 59 && ar.den == 54 )
539 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
540 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
542 else if ( ar.num == 40 && ar.den == 33 )
545 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
546 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
548 else if ( ar.num == 118 && ar.den == 81 )
551 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
552 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
558 AVRational codec_sar = codec_context->sample_aspect_ratio;
559 AVRational stream_sar =
560 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
561 stream->sample_aspect_ratio;
565 if ( codec_sar.num > 0 )
567 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
568 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
570 else if ( stream_sar.num > 0 )
572 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
573 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
577 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
578 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
581 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
582 aspect_ratio = av_q2d( ar );
583 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
588 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
589 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVDictionary **params )
591 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
594 if ( !URL ) return NULL;
597 char *protocol = strdup( URL );
598 char *url = strchr( protocol, ':' );
600 // Only if there is not a protocol specification that avformat can handle
601 #if LIBAVFORMAT_VERSION_MAJOR >= 53
602 if ( url && avio_check( URL, 0 ) < 0 )
604 if ( url && !url_exist( URL ) )
607 // Truncate protocol string
609 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
612 *format = av_find_input_format( protocol );
614 // Eat the format designator
619 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
620 // support for legacy width and height parameters
624 // These are required by video4linux2 (defaults)
625 params->width = profile->width;
626 params->height = profile->height;
627 if ( !strstr( URL, "&frame_rate" ) )
628 params->time_base = (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
629 params->channels = 2;
630 params->sample_rate = 48000;
634 url = strchr( url, '?' );
638 char *name = strdup( ++url );
639 char *value = strchr( name, '=' );
641 // Also accept : as delimiter for backwards compatibility.
642 value = strchr( name, ':' );
647 char *t = strchr( value, '&' );
650 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
651 // translate old parameters to new av_dict names
652 if ( !strcmp( name, "frame_rate" ) )
653 av_dict_set( params, "framerate", value, 0 );
654 else if ( !strcmp( name, "pix_fmt" ) )
655 av_dict_set( params, "pixel_format", value, 0 );
656 else if ( !strcmp( name, "width" ) )
657 width = strdup( value );
658 else if ( !strcmp( name, "height" ) )
659 height = strdup( value );
661 // generic demux/device option support
662 av_dict_set( params, name, value, 0 );
664 if ( !strcmp( name, "frame_rate" ) )
665 params->time_base.den = atoi( value );
666 else if ( !strcmp( name, "frame_rate_base" ) )
667 params->time_base.num = atoi( value );
668 else if ( !strcmp( name, "sample_rate" ) )
669 params->sample_rate = atoi( value );
670 else if ( !strcmp( name, "channel" ) )
671 params->channel = atoi( value );
672 else if ( !strcmp( name, "channels" ) )
673 params->channels = atoi( value );
674 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
675 else if ( !strcmp( name, "pix_fmt" ) )
676 params->pix_fmt = av_get_pix_fmt( value );
678 else if ( !strcmp( name, "width" ) )
679 params->width = atoi( value );
680 else if ( !strcmp( name, "height" ) )
681 params->height = atoi( value );
682 else if ( !strcmp( name, "standard" ) )
683 params->standard = strdup( value );
687 url = strchr( url, '&' );
689 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
690 // continued support for legacy width and height parameters
691 if ( width && height )
693 char *s = malloc( strlen( width ) + strlen( height ) + 2 );
697 av_dict_set( params, "video_size", s, 0 );
700 if ( width ) free( width );
701 if ( height ) free ( height );
704 result = strdup( result );
708 result = strdup( URL );
714 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
718 // Get the properties
719 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
721 AVFormatContext *format = self->video_format;
723 // We will treat everything with the producer fps.
724 // TODO: make this more flexible.
725 double fps = mlt_profile_fps( profile );
728 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
730 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
731 // when producer_open is called after initial call when restoring or reseting the producer.
732 if ( format->duration != AV_NOPTS_VALUE )
734 // This isn't going to be accurate for all formats
735 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
736 mlt_properties_set_position( properties, "out", frames - 1 );
737 mlt_properties_set_position( properties, "length", frames );
738 mlt_properties_set_int( properties, "_length_computed", 1 );
742 // Set live sources to run forever
743 mlt_properties_set_position( properties, "length", INT_MAX );
744 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
745 mlt_properties_set( properties, "eof", "loop" );
746 mlt_properties_set_int( properties, "_length_computed", 1 );
750 // Check if we're seekable
751 // avdevices are typically AVFMT_NOFILE and not seekable
752 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
755 // protocols can indicate if they support seeking
756 #if LIBAVFORMAT_VERSION_MAJOR >= 53
757 self->seekable = format->pb->seekable;
759 URLContext *uc = url_fileno( format->pb );
761 self->seekable = !uc->is_streamed;
764 if ( self->seekable )
766 // Do a more rigourous test of seekable on a disposable context
767 self->seekable = av_seek_frame( format, -1, format->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
768 mlt_properties_set_int( properties, "seekable", self->seekable );
769 self->dummy_context = format;
770 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
771 self->video_format = NULL;
772 avformat_open_input( &self->video_format, filename, NULL, NULL );
773 avformat_find_stream_info( self->video_format, NULL );
775 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
776 av_find_stream_info( self->video_format );
778 format = self->video_format;
781 // Fetch the width, height and aspect ratio
782 if ( self->video_index != -1 )
784 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
785 mlt_properties_set_int( properties, "width", codec_context->width );
786 mlt_properties_set_int( properties, "height", codec_context->height );
788 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
790 // Fetch the first frame of DV so we can read it directly
795 ret = av_read_frame( format, &pkt );
796 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
798 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
799 av_free_packet(&pkt);
803 av_free_packet(&pkt);
808 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
812 // Verify that we can convert this to YUV 4:2:2
813 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
814 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
815 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
817 sws_freeContext( context );
828 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
830 // Return an error code (0 == no error)
832 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
837 if ( !self->is_mutex_init )
839 pthread_mutex_init( &self->audio_mutex, NULL );
840 pthread_mutex_init( &self->video_mutex, NULL );
841 pthread_mutex_init( &self->packets_mutex, NULL );
842 pthread_mutex_init( &self->open_mutex, NULL );
843 self->is_mutex_init = 1;
845 pthread_mutex_lock( &self->audio_mutex );
846 pthread_mutex_lock( &self->video_mutex );
848 mlt_events_block( properties, self->parent );
851 AVInputFormat *format = NULL;
852 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
853 AVDictionary *params = NULL;
855 AVFormatParameters params;
856 memset( ¶ms, 0, sizeof(params) );
858 char *filename = parse_url( profile, URL, &format, ¶ms );
860 // Now attempt to open the file or device with filename
861 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
862 error = avformat_open_input( &self->video_format, filename, format, ¶ms ) < 0;
864 // If the URL is a network stream URL, then we probably need to open with full URL
865 error = avformat_open_input( &self->video_format, URL, format, ¶ms ) < 0;
867 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
869 // If the URL is a network stream URL, then we probably need to open with full URL
870 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
873 // Set MLT properties onto video AVFormatContext
874 if ( !error && self->video_format )
876 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
877 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
878 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
879 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
883 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
884 av_dict_free( ¶ms );
886 // Cleanup AVFormatParameters
887 if ( params.standard )
888 free( (void*) params.standard );
891 // If successful, then try to get additional info
892 if ( !error && self->video_format )
894 // Get the stream info
895 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
896 error = avformat_find_stream_info( self->video_format, NULL ) < 0;
898 error = av_find_stream_info( self->video_format ) < 0;
901 // Continue if no error
902 if ( !error && self->video_format )
904 // Find default audio and video streams
905 find_default_streams( self );
906 error = get_basic_info( self, profile, filename );
908 // Initialize position info
909 self->first_pts = AV_NOPTS_VALUE;
910 self->last_position = POSITION_INITIAL;
912 if ( !self->audio_format )
914 // We're going to cheat here - for seekable A/V files, we will have separate contexts
915 // to support independent seeking of audio from video.
916 // TODO: Is this really necessary?
917 if ( self->audio_index != -1 && self->video_index != -1 )
919 if ( self->seekable )
921 // And open again for our audio context
922 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
923 avformat_open_input( &self->audio_format, filename, NULL, NULL );
924 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
925 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
926 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
927 avformat_find_stream_info( self->audio_format, NULL );
929 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
930 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
931 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
932 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
933 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
935 av_find_stream_info( self->audio_format );
940 self->audio_format = self->video_format;
943 else if ( self->audio_index != -1 )
945 // We only have an audio context
946 self->audio_format = self->video_format;
947 self->video_format = NULL;
949 else if ( self->video_index == -1 )
951 // Something has gone wrong
954 if ( self->audio_format && !self->audio_streams )
955 get_audio_streams_info( self );
963 self->apackets = mlt_deque_init();
964 self->vpackets = mlt_deque_init();
967 if ( self->dummy_context )
969 pthread_mutex_lock( &self->open_mutex );
970 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
971 avformat_close_input( &self->dummy_context );
973 av_close_input_file( self->dummy_context );
975 self->dummy_context = NULL;
976 pthread_mutex_unlock( &self->open_mutex );
979 // Unlock the service
982 pthread_mutex_unlock( &self->audio_mutex );
983 pthread_mutex_unlock( &self->video_mutex );
985 mlt_events_unblock( properties, self->parent );
990 static void reopen_video( producer_avformat self, mlt_producer producer )
992 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
993 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
994 pthread_mutex_lock( &self->audio_mutex );
995 pthread_mutex_lock( &self->open_mutex );
997 if ( self->video_codec )
998 avcodec_close( self->video_codec );
999 self->video_codec = NULL;
1000 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
1001 if ( self->dummy_context )
1002 avformat_close_input( &self->dummy_context );
1003 if ( self->video_format )
1004 avformat_close_input( &self->video_format );
1006 if ( self->dummy_context )
1007 av_close_input_file( self->dummy_context );
1008 if ( self->video_format )
1009 av_close_input_file( self->video_format );
1011 self->dummy_context = NULL;
1012 self->video_format = NULL;
1013 pthread_mutex_unlock( &self->open_mutex );
1015 int audio_index = self->audio_index;
1016 int video_index = self->video_index;
1018 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1019 mlt_properties_get( properties, "resource" ), 0 );
1021 self->audio_index = audio_index;
1022 if ( self->video_format && video_index > -1 )
1024 self->video_index = video_index;
1025 video_codec_init( self, video_index, properties );
1028 pthread_mutex_unlock( &self->audio_mutex );
1029 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1032 static int64_t best_pts( producer_avformat self, int64_t pts, int64_t dts )
1034 self->invalid_pts_counter += pts == AV_NOPTS_VALUE;
1035 self->invalid_dts_counter += dts == AV_NOPTS_VALUE;
1036 if ( ( self->invalid_pts_counter <= self->invalid_dts_counter
1037 || dts == AV_NOPTS_VALUE ) && pts != AV_NOPTS_VALUE )
1043 static int seek_video( producer_avformat self, mlt_position position,
1044 int64_t req_position, int preseek )
1046 mlt_producer producer = self->parent;
1049 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
1051 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1053 // Fetch the video format context
1054 AVFormatContext *context = self->video_format;
1056 // Get the video stream
1057 AVStream *stream = context->streams[ self->video_index ];
1059 // Get codec context
1060 AVCodecContext *codec_context = stream->codec;
1062 // We may want to use the source fps if available
1063 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1064 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1067 if ( self->last_position == POSITION_INITIAL )
1073 while ( ret >= 0 && toscan-- > 0 )
1075 ret = av_read_frame( context, &pkt );
1076 if ( ret >= 0 && pkt.stream_index == self->video_index && ( pkt.flags & PKT_FLAG_KEY ) )
1078 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1079 "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n",
1080 pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
1081 self->first_pts = best_pts( self, pkt.pts, pkt.dts );
1082 if ( self->first_pts != AV_NOPTS_VALUE )
1085 av_free_packet( &pkt );
1087 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1090 if ( self->av_frame && position + 1 == self->video_expected )
1092 // We're paused - use last image
1095 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
1097 // Calculate the timestamp for the requested frame
1098 int64_t timestamp = req_position / ( av_q2d( stream->time_base ) * source_fps );
1099 if ( req_position <= 0 )
1101 else if ( self->first_pts != AV_NOPTS_VALUE )
1102 timestamp += self->first_pts;
1103 else if ( context->start_time != AV_NOPTS_VALUE )
1104 timestamp += context->start_time;
1105 if ( preseek && av_q2d( stream->time_base ) != 0 )
1106 timestamp -= 2 / av_q2d( stream->time_base );
1107 if ( timestamp < 0 )
1109 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
1110 timestamp, position, self->video_expected, self->last_position );
1112 // Seek to the timestamp
1113 // NOTE: reopen_video is disabled at this time because it is causing trouble with A/V sync.
1114 if ( 1 || req_position > 0 || self->last_position <= 0 )
1116 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1117 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1119 // flush any pictures still in decode buffer
1120 avcodec_flush_buffers( codec_context );
1124 // Re-open video stream when rewinding to beginning from somewhere else.
1125 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1126 // not reliably seeking to the first frame across formats.
1127 reopen_video( self, producer );
1130 // Remove the cached info relating to the previous position
1131 self->current_position = POSITION_INVALID;
1132 self->last_position = POSITION_INVALID;
1133 av_freep( &self->av_frame );
1139 /** Convert a frame position to a time code.
1142 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1144 return ( double )position / mlt_producer_get_fps( producer );
1147 // Collect information about all audio streams
1149 static void get_audio_streams_info( producer_avformat self )
1151 // Fetch the audio format context
1152 AVFormatContext *context = self->audio_format;
1156 i < context->nb_streams;
1159 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1161 AVCodecContext *codec_context = context->streams[i]->codec;
1162 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1164 // If we don't have a codec and we can't initialise it, we can't do much more...
1165 pthread_mutex_lock( &self->open_mutex );
1166 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1167 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1169 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1172 self->audio_streams++;
1173 self->audio_max_stream = i;
1174 self->total_channels += codec_context->channels;
1175 if ( codec_context->channels > self->max_channel )
1176 self->max_channel = codec_context->channels;
1177 if ( codec_context->sample_rate > self->max_frequency )
1178 self->max_frequency = codec_context->sample_rate;
1179 avcodec_close( codec_context );
1181 pthread_mutex_unlock( &self->open_mutex );
1184 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1185 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1187 // Other audio-specific initializations
1188 self->resample_factor = 1.0;
1191 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1193 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1195 const int *new_coefficients;
1197 int brightness, contrast, saturation;
1199 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1200 &brightness, &contrast, &saturation ) != -1 )
1202 // Don't change these from defaults unless explicitly told to.
1203 if ( use_full_range >= 0 )
1204 full_range = use_full_range;
1205 switch ( colorspace )
1211 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1214 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1217 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1220 new_coefficients = coefficients;
1223 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1224 brightness, contrast, saturation );
1229 static mlt_image_format pick_pix_format( enum PixelFormat pix_fmt )
1237 return mlt_image_rgb24a;
1238 case PIX_FMT_YUV420P:
1239 case PIX_FMT_YUVJ420P:
1240 case PIX_FMT_YUVA420P:
1241 return mlt_image_yuv420p;
1245 case PIX_FMT_MONOWHITE:
1246 case PIX_FMT_MONOBLACK:
1249 return mlt_image_rgb24;
1251 return mlt_image_yuv422;
1255 static mlt_audio_format pick_audio_format( int sample_fmt )
1257 switch ( sample_fmt )
1260 case AV_SAMPLE_FMT_S16:
1261 return mlt_audio_s16;
1262 case AV_SAMPLE_FMT_S32:
1263 return mlt_audio_s32le;
1264 case AV_SAMPLE_FMT_FLT:
1265 return mlt_audio_f32le;
1266 // planar - this producer converts planar to interleaved
1267 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1268 case AV_SAMPLE_FMT_S16P:
1269 return mlt_audio_s16;
1270 case AV_SAMPLE_FMT_S32P:
1271 return mlt_audio_s32le;
1272 case AV_SAMPLE_FMT_FLTP:
1273 return mlt_audio_f32le;
1276 return mlt_audio_none;
1280 static void convert_image( producer_avformat self, AVFrame *frame, uint8_t *buffer, int pix_fmt,
1281 mlt_image_format *format, int width, int height, uint8_t **alpha )
1284 int flags = SWS_BICUBIC | SWS_ACCURATE_RND;
1287 flags |= SWS_CPU_CAPS_MMX;
1290 flags |= SWS_CPU_CAPS_MMX2;
1293 // extract alpha from planar formats
1294 if ( ( pix_fmt == PIX_FMT_YUVA420P
1295 #if defined(FFUDIV) && LIBAVUTIL_VERSION_INT >= ((51<<16)+(35<<8)+101)
1296 || pix_fmt == PIX_FMT_YUVA444P
1299 *format != mlt_image_rgb24a && *format != mlt_image_opengl &&
1300 frame->data[3] && frame->linesize[3] )
1305 dst = *alpha = mlt_pool_alloc( width * height );
1306 src = frame->data[3];
1308 for ( i = 0; i < height; dst += width, src += frame->linesize[3], i++ )
1309 memcpy( dst, src, FFMIN( width, frame->linesize[3] ) );
1312 if ( *format == mlt_image_yuv420p )
1314 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1315 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1317 output.data[0] = buffer;
1318 output.data[1] = buffer + width * height;
1319 output.data[2] = buffer + ( 5 * width * height ) / 4;
1320 output.linesize[0] = width;
1321 output.linesize[1] = width >> 1;
1322 output.linesize[2] = width >> 1;
1323 set_luma_transfer( context, self->colorspace, -1 );
1324 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1325 output.data, output.linesize);
1326 sws_freeContext( context );
1328 else if ( *format == mlt_image_rgb24 )
1330 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1331 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1333 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1334 set_luma_transfer( context, self->colorspace, self->full_luma );
1335 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1336 output.data, output.linesize);
1337 sws_freeContext( context );
1339 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1341 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1342 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1344 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1345 set_luma_transfer( context, self->colorspace, self->full_luma );
1346 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1347 output.data, output.linesize);
1348 sws_freeContext( context );
1352 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1353 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1355 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1356 set_luma_transfer( context, self->colorspace, -1 );
1357 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1358 output.data, output.linesize);
1359 sws_freeContext( context );
1362 if ( *format == mlt_image_yuv420p )
1365 pict.data[0] = buffer;
1366 pict.data[1] = buffer + width * height;
1367 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1368 pict.linesize[0] = width;
1369 pict.linesize[1] = width >> 1;
1370 pict.linesize[2] = width >> 1;
1371 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1373 else if ( *format == mlt_image_rgb24 )
1376 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1377 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1379 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1382 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1383 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1388 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1389 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1394 /** Allocate the image buffer and set it on the frame.
1397 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1401 if ( codec_context->width == 0 || codec_context->height == 0 )
1403 *width = codec_context->width;
1404 *height = codec_context->height;
1405 size = mlt_image_format_size( *format, *width, *height, NULL );
1406 *buffer = mlt_pool_alloc( size );
1408 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1415 /** Get an image from a frame.
1418 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1421 producer_avformat self = mlt_frame_pop_service( frame );
1422 mlt_producer producer = self->parent;
1424 // Get the properties from the frame
1425 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1427 // Obtain the frame number of this frame
1428 mlt_position position = mlt_frame_original_position( frame );
1430 // Get the producer properties
1431 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1433 pthread_mutex_lock( &self->video_mutex );
1435 // Fetch the video format context
1436 AVFormatContext *context = self->video_format;
1438 // Get the video stream
1439 AVStream *stream = context->streams[ self->video_index ];
1441 // Get codec context
1442 AVCodecContext *codec_context = stream->codec;
1444 uint8_t *alpha = NULL;
1445 int got_picture = 0;
1448 // Get the image cache
1449 if ( ! self->image_cache )
1451 // if cache size supplied by environment variable
1452 int cache_supplied = getenv( "MLT_AVFORMAT_CACHE" ) != NULL;
1453 int cache_size = cache_supplied? atoi( getenv( "MLT_AVFORMAT_CACHE" ) ) : 0;
1455 // cache size supplied via property
1456 if ( mlt_properties_get( properties, "cache" ) )
1459 cache_size = mlt_properties_get_int( properties, "cache" );
1461 if ( mlt_properties_get_int( properties, "noimagecache" ) )
1463 // create cache if not disabled
1464 if ( !cache_supplied || cache_size > 0 )
1465 self->image_cache = mlt_cache_init();
1466 // set cache size if supplied
1467 if ( self->image_cache && cache_supplied )
1468 mlt_cache_set_size( self->image_cache, cache_size );
1470 if ( self->image_cache )
1472 mlt_frame original = mlt_cache_get_frame( self->image_cache, position );
1475 mlt_properties orig_props = MLT_FRAME_PROPERTIES( original );
1478 *buffer = mlt_properties_get_data( orig_props, "alpha", &size );
1480 mlt_frame_set_alpha( frame, *buffer, size, NULL );
1481 *buffer = mlt_properties_get_data( orig_props, "image", &size );
1482 mlt_frame_set_image( frame, *buffer, size, NULL );
1483 mlt_properties_set_data( frame_properties, "avformat.image_cache", original, 0, (mlt_destructor) mlt_frame_close, NULL );
1484 *format = mlt_properties_get_int( orig_props, "format" );
1486 // Set the resolution
1487 *width = codec_context->width;
1488 *height = codec_context->height;
1490 // Workaround 1088 encodings missing cropping info.
1491 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1495 goto exit_get_image;
1500 // We may want to use the source fps if available
1501 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1502 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1504 // This is the physical frame position in the source
1505 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1507 // Determines if we have to decode all frames in a sequence
1508 // Temporary hack to improve intra frame only
1509 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1510 strcmp( codec_context->codec->name, "dnxhd" ) &&
1511 strcmp( codec_context->codec->name, "dvvideo" ) &&
1512 strcmp( codec_context->codec->name, "huffyuv" ) &&
1513 strcmp( codec_context->codec->name, "mjpeg" ) &&
1514 strcmp( codec_context->codec->name, "rawvideo" ) );
1516 double delay = mlt_properties_get_double( properties, "video_delay" );
1518 // Seek if necessary
1519 const char *interp = mlt_properties_get( frame_properties, "rescale.interp" );
1520 int preseek = must_decode
1521 #if defined(FFUDIV) && LIBAVFORMAT_VERSION_INT >= ((53<<16)+(24<<8)+2)
1522 && ( interp && strcmp( interp, "nearest" ) )
1524 && codec_context->has_b_frames;
1525 int paused = seek_video( self, position, req_position, preseek );
1527 // Seek might have reopened the file
1528 context = self->video_format;
1529 stream = context->streams[ self->video_index ];
1530 codec_context = stream->codec;
1531 if ( *format == mlt_image_none ||
1532 codec_context->pix_fmt == PIX_FMT_ARGB ||
1533 codec_context->pix_fmt == PIX_FMT_RGBA ||
1534 codec_context->pix_fmt == PIX_FMT_ABGR ||
1535 codec_context->pix_fmt == PIX_FMT_BGRA )
1536 *format = pick_pix_format( codec_context->pix_fmt );
1538 // Duplicate the last image if necessary
1539 if ( self->av_frame && self->av_frame->linesize[0]
1540 && ( paused || self->current_position >= req_position ) )
1543 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1545 // Workaround 1088 encodings missing cropping info.
1546 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1549 if ( self->vdpau && self->vdpau->buffer )
1552 picture.data[0] = self->vdpau->buffer;
1553 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1554 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1555 picture.linesize[0] = codec_context->width;
1556 picture.linesize[1] = codec_context->width / 2;
1557 picture.linesize[2] = codec_context->width / 2;
1558 convert_image( self, (AVFrame*) &picture, *buffer,
1559 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1563 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1564 format, *width, *height, &alpha );
1571 int64_t int_position = 0;
1572 int decode_errors = 0;
1574 // Construct an AVFrame for YUV422 conversion
1575 if ( !self->av_frame )
1576 self->av_frame = avcodec_alloc_frame( );
1578 while( ret >= 0 && !got_picture )
1581 if ( self->pkt.stream_index == self->video_index )
1582 av_free_packet( &self->pkt );
1583 av_init_packet( &self->pkt );
1584 pthread_mutex_lock( &self->packets_mutex );
1585 if ( mlt_deque_count( self->vpackets ) )
1587 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1593 ret = av_read_frame( context, &self->pkt );
1594 if ( ret >= 0 && !self->seekable && self->pkt.stream_index == self->audio_index )
1596 if ( !av_dup_packet( &self->pkt ) )
1598 AVPacket *tmp = malloc( sizeof(AVPacket) );
1600 mlt_deque_push_back( self->apackets, tmp );
1604 pthread_mutex_unlock( &self->packets_mutex );
1606 // We only deal with video from the selected video_index
1607 if ( ret >= 0 && self->pkt.stream_index == self->video_index && self->pkt.size > 0 )
1609 int64_t pts = best_pts( self, self->pkt.pts, self->pkt.dts );
1610 if ( pts != AV_NOPTS_VALUE )
1612 if ( !self->seekable && self->first_pts == AV_NOPTS_VALUE )
1613 self->first_pts = pts;
1614 if ( self->first_pts != AV_NOPTS_VALUE )
1615 pts -= self->first_pts;
1616 else if ( context->start_time != AV_NOPTS_VALUE )
1617 pts -= context->start_time;
1618 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.5 );
1619 if ( int_position == self->last_position )
1620 int_position = self->last_position + 1;
1622 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1623 "V pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1624 self->pkt.pts, self->pkt.dts, req_position, self->current_position, int_position );
1626 // Make a dumb assumption on streams that contain wild timestamps
1627 if ( abs( req_position - int_position ) > 999 )
1629 int_position = req_position;
1630 mlt_log_warning( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!\n" );
1632 self->last_position = int_position;
1635 if ( must_decode || int_position >= req_position )
1640 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1642 vdpau_decoder_init( self );
1644 self->vdpau->is_decoded = 0;
1647 codec_context->reordered_opaque = int_position;
1648 if ( int_position >= req_position )
1649 codec_context->skip_loop_filter = AVDISCARD_NONE;
1650 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1651 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &self->pkt );
1653 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, self->pkt.data, self->pkt.size );
1655 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1658 if ( ++decode_errors <= 10 )
1669 // Get position of reordered frame
1670 int_position = self->av_frame->reordered_opaque;
1671 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(106<<8)+0))
1672 pts = best_pts( self, self->av_frame->pkt_pts, self->av_frame->pkt_dts );
1673 if ( pts != AV_NOPTS_VALUE )
1675 if ( self->first_pts != AV_NOPTS_VALUE )
1676 pts -= self->first_pts;
1677 else if ( context->start_time != AV_NOPTS_VALUE )
1678 pts -= context->start_time;
1679 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.5 );
1683 if ( int_position < req_position )
1685 else if ( int_position >= req_position )
1686 codec_context->skip_loop_filter = AVDISCARD_NONE;
1688 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, self->pkt.flags & PKT_FLAG_KEY );
1691 // Now handle the picture if we have one
1694 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1696 // Workaround 1088 encodings missing cropping info.
1697 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1702 if ( self->vdpau->is_decoded )
1704 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1706 uint32_t pitches[3];
1707 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1709 if ( !self->vdpau->buffer )
1710 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1711 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1712 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1713 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1714 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1715 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1716 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1718 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1719 if ( status == VDP_STATUS_OK )
1721 convert_image( self, self->av_frame, *buffer, PIX_FMT_YUV420P,
1722 format, *width, *height, &alpha );
1726 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1727 image_size = self->vdpau->is_decoded = 0;
1732 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1733 image_size = got_picture = 0;
1738 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1739 format, *width, *height, &alpha );
1740 self->top_field_first |= self->av_frame->top_field_first;
1741 self->current_position = int_position;
1749 // Free packet data if not video and not live audio packet
1750 if ( self->pkt.stream_index != self->video_index &&
1751 !( !self->seekable && self->pkt.stream_index == self->audio_index ) )
1752 av_free_packet( &self->pkt );
1758 mlt_frame_set_alpha( frame, alpha, (*width) * (*height), mlt_pool_release );
1760 if ( image_size > 0 && self->image_cache )
1762 mlt_properties_set_int( frame_properties, "format", *format );
1763 mlt_cache_put_frame( self->image_cache, frame );
1766 // Try to duplicate last image if there was a decoding failure
1767 // TODO: with multithread decoding a partial frame decoding resulting
1768 // in failure also resets av_frame making test below fail.
1769 if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1772 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1774 // Workaround 1088 encodings missing cropping info.
1775 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1778 if ( self->vdpau && self->vdpau->buffer )
1781 picture.data[0] = self->vdpau->buffer;
1782 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1783 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1784 picture.linesize[0] = codec_context->width;
1785 picture.linesize[1] = codec_context->width / 2;
1786 picture.linesize[2] = codec_context->width / 2;
1787 convert_image( self, (AVFrame*) &picture, *buffer,
1788 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1792 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1793 format, *width, *height, &alpha );
1798 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1799 self->video_expected = position + 1;
1803 pthread_mutex_unlock( &self->video_mutex );
1805 // Set the progressive flag
1806 if ( mlt_properties_get( properties, "force_progressive" ) )
1807 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1808 else if ( self->av_frame )
1809 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1811 // Set the field order property for this frame
1812 if ( mlt_properties_get( properties, "force_tff" ) )
1813 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1815 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1817 // Set immutable properties of the selected track's (or overridden) source attributes.
1818 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1819 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1820 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1821 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1823 // If we already have RGB, then the full range processing either happened already
1824 // or does not apply (RGB source).
1825 if ( *format == mlt_image_rgb24 || *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1826 mlt_properties_set( frame_properties, "force_full_luma", NULL );
1828 return !got_picture;
1831 /** Process properties as AVOptions and apply to AV context obj
1834 static void apply_properties( void *obj, mlt_properties properties, int flags )
1837 int count = mlt_properties_count( properties );
1838 for ( i = 0; i < count; i++ )
1840 const char *opt_name = mlt_properties_get_name( properties, i );
1841 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
1842 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1844 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1846 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1849 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1850 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1851 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1852 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1853 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1854 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1856 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1862 /** Initialize the video codec context.
1865 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1867 // Initialise the codec if necessary
1868 if ( !self->video_codec )
1870 // Get the video stream
1871 AVStream *stream = self->video_format->streams[ index ];
1873 // Get codec context
1874 AVCodecContext *codec_context = stream->codec;
1877 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1879 if ( codec_context->codec_id == CODEC_ID_H264 )
1881 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1883 if ( vdpau_init( self ) )
1885 self->video_codec = codec_context;
1886 if ( !vdpau_decoder_init( self ) )
1891 codec = avcodec_find_decoder( codec_context->codec_id );
1895 // Initialise multi-threading
1896 int thread_count = mlt_properties_get_int( properties, "threads" );
1897 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1898 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1899 if ( thread_count > 1 )
1900 codec_context->thread_count = thread_count;
1902 // If we don't have a codec and we can't initialise it, we can't do much more...
1903 pthread_mutex_lock( &self->open_mutex );
1904 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1905 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1907 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1910 // Now store the codec with its destructor
1911 self->video_codec = codec_context;
1915 // Remember that we can't use this later
1916 self->video_index = -1;
1917 pthread_mutex_unlock( &self->open_mutex );
1920 pthread_mutex_unlock( &self->open_mutex );
1922 // Process properties as AVOptions
1923 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1924 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1925 if ( codec->priv_class && codec_context->priv_data )
1926 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1929 // Reset some image properties
1930 if ( self->video_codec )
1932 mlt_properties_set_int( properties, "width", self->video_codec->width );
1933 mlt_properties_set_int( properties, "height", self->video_codec->height );
1935 // For DV, we'll just use the saved aspect ratio
1936 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1937 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1939 // Determine the fps first from the codec
1940 double source_fps = (double) self->video_codec->time_base.den /
1941 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1944 // If the muxer reports a frame rate different than the codec
1945 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1946 double muxer_fps = av_q2d( stream->avg_frame_rate );
1947 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1948 muxer_fps = av_q2d( stream->r_frame_rate );
1950 double muxer_fps = av_q2d( stream->r_frame_rate );
1952 // Choose the lesser - the wrong tends to be off by some multiple of 10
1953 source_fps = FFMIN( source_fps, muxer_fps );
1954 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1956 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1957 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1959 else if ( muxer_fps > 0 )
1961 AVRational frame_rate = stream->r_frame_rate;
1962 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1963 // avg_frame_rate gives some approximate value that does not well match the media.
1964 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1965 // results in some very choppy output, but some value slightly different works
1967 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1968 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1969 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1971 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1972 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1976 source_fps = mlt_producer_get_fps( self->parent );
1977 AVRational frame_rate = av_d2q( source_fps, 255 );
1978 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1979 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1982 if ( mlt_properties_get( properties, "force_fps" ) )
1984 double source_fps = mlt_properties_get_double( properties, "force_fps" );
1985 AVRational fps = av_d2q( source_fps, 1024 );
1986 stream->time_base.num *= mlt_properties_get_int( properties, "meta.media.frame_rate_num" ) * fps.den;
1987 stream->time_base.den *= mlt_properties_get_int( properties, "meta.media.frame_rate_den" ) * fps.num;
1988 mlt_properties_set_int( properties, "meta.media.frame_rate_num", fps.num );
1989 mlt_properties_set_int( properties, "meta.media.frame_rate_den", fps.den );
1992 // Set the YUV colorspace from override or detect
1993 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1994 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1995 if ( ! self->colorspace )
1997 switch ( self->video_codec->colorspace )
1999 case AVCOL_SPC_SMPTE240M:
2000 self->colorspace = 240;
2002 case AVCOL_SPC_BT470BG:
2003 case AVCOL_SPC_SMPTE170M:
2004 self->colorspace = 601;
2006 case AVCOL_SPC_BT709:
2007 self->colorspace = 709;
2010 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
2011 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
2016 // Let apps get chosen colorspace
2017 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
2019 self->full_luma = -1;
2020 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(72<<8)+2)
2021 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent), "color_range %d\n", codec_context->color_range );
2022 if ( codec_context->color_range == AVCOL_RANGE_JPEG )
2023 self->full_luma = 1;
2025 if ( mlt_properties_get( properties, "set.force_full_luma" ) )
2026 self->full_luma = mlt_properties_get_int( properties, "set.force_full_luma" );
2028 return self->video_codec && self->video_index > -1;
2031 /** Set up video handling.
2034 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
2037 mlt_producer producer = self->parent;
2039 // Get the properties
2040 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2042 // Fetch the video format context
2043 AVFormatContext *context = self->video_format;
2045 // Get the video_index
2046 int index = mlt_properties_get_int( properties, "video_index" );
2048 // Reopen the file if necessary
2049 if ( !context && index > -1 )
2051 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2052 mlt_properties_get( properties, "resource" ), 1 );
2053 context = self->video_format;
2056 // Exception handling for video_index
2057 if ( context && index >= (int) context->nb_streams )
2059 // Get the last video stream
2060 for ( index = context->nb_streams - 1;
2061 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
2063 mlt_properties_set_int( properties, "video_index", index );
2065 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
2067 // Invalidate the video stream
2069 mlt_properties_set_int( properties, "video_index", index );
2072 // Update the video properties if the index changed
2073 if ( index != self->video_index )
2075 // Reset the video properties if the index changed
2076 self->video_index = index;
2077 pthread_mutex_lock( &self->open_mutex );
2078 if ( self->video_codec )
2079 avcodec_close( self->video_codec );
2080 self->video_codec = NULL;
2081 pthread_mutex_unlock( &self->open_mutex );
2084 // Get the frame properties
2085 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2088 if ( context && index > -1 && video_codec_init( self, index, properties ) )
2090 // Set the frame properties
2091 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
2092 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
2093 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
2095 // Set the width and height
2096 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
2097 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
2098 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
2099 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
2100 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
2101 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
2103 // Workaround 1088 encodings missing cropping info.
2104 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
2106 mlt_properties_set_int( properties, "meta.media.height", 1080 );
2109 // Add our image operation
2110 mlt_frame_push_service( frame, self );
2111 mlt_frame_push_get_image( frame, producer_get_image );
2115 // If something failed, use test card image
2116 mlt_properties_set_int( frame_properties, "test_image", 1 );
2120 static int seek_audio( producer_avformat self, mlt_position position, double timecode )
2124 // Seek if necessary
2125 if ( self->seekable && position != self->audio_expected )
2127 if ( position + 1 == self->audio_expected )
2129 // We're paused - silence required
2132 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
2134 AVFormatContext *context = self->audio_format;
2135 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
2136 if ( context->start_time != AV_NOPTS_VALUE )
2137 timestamp += context->start_time;
2138 if ( timestamp < 0 )
2141 // Set to the real timecode
2142 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
2145 // Clear the usage in the audio buffer
2146 int i = MAX_AUDIO_STREAMS + 1;
2148 self->audio_used[i - 1] = 0;
2154 static int sample_bytes( AVCodecContext *context )
2156 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2157 return av_get_bytes_per_sample( context->sample_fmt );
2158 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2159 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2161 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2165 static void planar_to_interleaved( uint8_t *dest, uint8_t *src, int samples, int channels, int bytes_per_sample )
2168 for ( s = 0; s < samples; s++ )
2170 for ( c = 0; c < channels; c++ )
2172 memcpy( dest, src + ( c * samples + s ) * bytes_per_sample, bytes_per_sample );
2173 dest += bytes_per_sample;
2178 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2180 // Fetch the audio_format
2181 AVFormatContext *context = self->audio_format;
2183 // Get the current stream index
2184 int index = pkt.stream_index;
2186 // Get codec context
2187 AVCodecContext *codec_context = self->audio_codec[ index ];
2189 // Obtain the resample context if it exists (not always needed)
2190 ReSampleContext *resample = self->audio_resample[ index ];
2192 // Obtain the audio buffers
2193 uint8_t *audio_buffer = self->audio_buffer[ index ];
2194 uint8_t *decode_buffer = self->decode_buffer[ index ];
2196 int audio_used = self->audio_used[ index ];
2197 uint8_t *ptr = pkt.data;
2201 while ( ptr && ret >= 0 && len > 0 )
2203 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2204 int data_size = self->audio_buffer_size[ index ];
2207 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2208 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2209 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2210 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2212 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2216 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2220 pkt.size = len -= ret;
2221 pkt.data = ptr += ret;
2223 // If decoded successfully
2224 if ( data_size > 0 )
2226 // Figure out how many samples will be needed after resampling
2227 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2228 int samples_needed = self->resample_factor * convert_samples;
2230 // Resize audio buffer to prevent overflow
2231 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2233 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2234 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2238 // Copy to audio buffer while resampling
2239 uint8_t *source = decode_buffer;
2240 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2241 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2245 uint8_t *source = decode_buffer;
2246 uint8_t *dest = &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ];
2247 switch ( codec_context->sample_fmt )
2249 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2250 case AV_SAMPLE_FMT_S16P:
2251 case AV_SAMPLE_FMT_S32P:
2252 case AV_SAMPLE_FMT_FLTP:
2253 planar_to_interleaved( dest, source, convert_samples, codec_context->channels, sizeof_sample );
2257 // Straight copy to audio buffer
2258 memcpy( dest, decode_buffer, data_size );
2260 audio_used += convert_samples;
2264 while ( *ignore && audio_used )
2267 audio_used -= audio_used > samples ? samples : audio_used;
2268 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2269 audio_used * sizeof_sample );
2274 // If we're behind, ignore this packet
2275 // Skip this on non-seekable, audio-only inputs.
2276 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2278 int64_t pts = pkt.pts;
2279 if ( self->first_pts != 0 )
2280 pts -= self->first_pts;
2281 else if ( context->start_time != AV_NOPTS_VALUE )
2282 pts -= context->start_time;
2283 double timebase = av_q2d( context->streams[ index ]->time_base );
2284 int64_t int_position = ( int64_t )( timebase * pts * fps + 0.5 );
2285 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2287 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
2288 "A pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
2289 pkt.pts, pkt.dts, req_position, self->current_position, int_position );
2291 if ( int_position > 0 )
2293 if ( int_position < req_position )
2294 // We are behind, so skip some
2295 *ignore = req_position - int_position;
2296 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2297 // We are ahead, so seek backwards some more
2298 seek_audio( self, req_position, timecode - 1.0 );
2302 self->audio_used[ index ] = audio_used;
2307 /** Get the audio from a frame.
2309 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2312 producer_avformat self = mlt_frame_pop_audio( frame );
2314 pthread_mutex_lock( &self->audio_mutex );
2316 // Obtain the frame number of this frame
2317 mlt_position position = mlt_frame_original_position( frame );
2319 // Calculate the real time code
2320 double real_timecode = producer_time_of_frame( self->parent, position );
2322 // Get the producer fps
2323 double fps = mlt_producer_get_fps( self->parent );
2325 // Number of frames to ignore (for ffwd)
2326 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2328 // Flag for paused (silence)
2329 int paused = seek_audio( self, position, real_timecode );
2331 // Initialize ignore for all streams from the seek return value
2332 int i = MAX_AUDIO_STREAMS;
2334 ignore[i] = ignore[0];
2336 // Fetch the audio_format
2337 AVFormatContext *context = self->audio_format;
2339 int sizeof_sample = sizeof( int16_t );
2341 // Determine the tracks to use
2342 int index = self->audio_index;
2343 int index_max = self->audio_index + 1;
2344 if ( self->audio_index == INT_MAX )
2347 index_max = FFMIN( MAX_AUDIO_STREAMS, context->nb_streams );
2348 *channels = self->total_channels;
2349 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2350 *frequency = FFMAX( self->max_frequency, *frequency );
2353 // Initialize the resamplers and buffers
2354 for ( ; index < index_max && index < MAX_AUDIO_STREAMS; index++ )
2356 // Get codec context
2357 AVCodecContext *codec_context = self->audio_codec[ index ];
2359 if ( codec_context && !self->audio_buffer[ index ] )
2361 #if LIBAVCODEC_VERSION_INT < ((54<<16)+(26<<8)+0)
2362 // Check for resample and create if necessary
2363 if ( codec_context->channels <= 2 )
2365 // Determine by how much resampling will increase number of samples
2366 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2367 resample_factor *= (double) *frequency / codec_context->sample_rate;
2368 if ( resample_factor > self->resample_factor )
2369 self->resample_factor = resample_factor;
2371 // Create the resampler
2372 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2373 self->audio_resample[ index ] = av_audio_resample_init(
2374 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2375 codec_context->channels, *frequency, codec_context->sample_rate,
2376 AV_SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2378 self->audio_resample[ index ] = audio_resample_init(
2379 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2380 codec_context->channels, *frequency, codec_context->sample_rate );
2386 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2387 sizeof_sample = sample_bytes( codec_context );
2390 // Check for audio buffer and create if necessary
2391 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2392 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2394 // Check for decoder buffer and create if necessary
2395 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2399 // Get the audio if required
2400 if ( !paused && *frequency > 0 )
2406 av_init_packet( &pkt );
2408 // If not resampling, give consumer more than requested.
2409 // It requested number samples based on requested frame rate.
2410 // Do not clean this up with a samples *= ...!
2411 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2412 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2414 while ( ret >= 0 && !got_audio )
2416 // Check if the buffer already contains the samples required
2417 if ( self->audio_index != INT_MAX &&
2418 self->audio_used[ self->audio_index ] >= *samples &&
2419 ignore[ self->audio_index ] == 0 )
2424 else if ( self->audio_index == INT_MAX )
2426 // Check if there is enough audio for all streams
2428 for ( index = 0; got_audio && index < index_max; index++ )
2429 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2436 pthread_mutex_lock( &self->packets_mutex );
2437 if ( mlt_deque_count( self->apackets ) )
2439 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2445 ret = av_read_frame( context, &pkt );
2446 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2448 if ( !av_dup_packet( &pkt ) )
2450 AVPacket *tmp = malloc( sizeof(AVPacket) );
2452 mlt_deque_push_back( self->vpackets, tmp );
2456 pthread_mutex_unlock( &self->packets_mutex );
2458 // We only deal with audio from the selected audio index
2459 index = pkt.stream_index;
2460 if ( index < MAX_AUDIO_STREAMS && ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2461 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2463 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2464 self->audio_codec[index]->channels : *channels;
2465 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2468 if ( self->seekable || index != self->video_index )
2469 av_free_packet( &pkt );
2473 // Set some additional return values
2474 *format = mlt_audio_s16;
2475 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2477 index = self->audio_index;
2478 *channels = self->audio_codec[ index ]->channels;
2479 *frequency = self->audio_codec[ index ]->sample_rate;
2480 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2481 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2483 else if ( self->audio_index == INT_MAX )
2485 for ( index = 0; index < index_max; index++ )
2486 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2488 // XXX: This only works if all audio tracks have the same sample format.
2489 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2490 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2495 // Allocate and set the frame's audio buffer
2496 int size = mlt_audio_format_size( *format, *samples, *channels );
2497 *buffer = mlt_pool_alloc( size );
2498 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2500 // Interleave tracks if audio_index=all
2501 if ( self->audio_index == INT_MAX )
2503 uint8_t *dest = *buffer;
2505 for ( i = 0; i < *samples; i++ )
2507 for ( index = 0; index < index_max; index++ )
2508 if ( self->audio_codec[ index ] )
2510 int current_channels = self->audio_codec[ index ]->channels;
2511 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2512 memcpy( dest, src, current_channels * sizeof_sample );
2513 dest += current_channels * sizeof_sample;
2516 for ( index = 0; index < index_max; index++ )
2517 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2519 int current_channels = self->audio_codec[ index ]->channels;
2520 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2521 self->audio_used[index] -= *samples;
2522 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2525 // Copy a single track to the output buffer
2528 index = self->audio_index;
2530 // Now handle the audio if we have enough
2531 if ( self->audio_used[ index ] > 0 )
2533 uint8_t *src = self->audio_buffer[ index ];
2534 // copy samples from audio_buffer
2535 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2536 memcpy( *buffer, src, size * *channels * sizeof_sample );
2537 // supply the remaining requested samples as silence
2538 if ( *samples > self->audio_used[ index ] )
2539 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2540 // reposition the samples within audio_buffer
2541 self->audio_used[ index ] -= size;
2542 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2546 // Otherwise fill with silence
2547 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2553 // Get silence and don't touch the context
2554 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2557 // Regardless of speed (other than paused), we expect to get the next frame
2559 self->audio_expected = position + 1;
2561 pthread_mutex_unlock( &self->audio_mutex );
2566 /** Initialize the audio codec context.
2569 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2571 // Initialise the codec if necessary
2572 if ( !self->audio_codec[ index ] )
2574 // Get codec context
2575 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2578 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2580 // If we don't have a codec and we can't initialise it, we can't do much more...
2581 pthread_mutex_lock( &self->open_mutex );
2582 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2583 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2585 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2588 // Now store the codec with its destructor
2589 if ( self->audio_codec[ index ] )
2590 avcodec_close( self->audio_codec[ index ] );
2591 self->audio_codec[ index ] = codec_context;
2595 // Remember that we can't use self later
2596 self->audio_index = -1;
2598 pthread_mutex_unlock( &self->open_mutex );
2600 // Process properties as AVOptions
2601 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2602 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
2603 if ( codec && codec->priv_class && codec_context->priv_data )
2604 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2607 return self->audio_codec[ index ] && self->audio_index > -1;
2610 /** Set up audio handling.
2613 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2616 mlt_producer producer = self->parent;
2618 // Get the properties
2619 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2621 // Fetch the audio format context
2622 AVFormatContext *context = self->audio_format;
2624 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2626 // Get the audio_index
2627 int index = mlt_properties_get_int( properties, "audio_index" );
2629 // Handle all audio tracks
2630 if ( self->audio_index > -1 &&
2631 mlt_properties_get( properties, "audio_index" ) &&
2632 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2635 // Reopen the file if necessary
2636 if ( !context && self->audio_index > -1 && index > -1 )
2638 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2639 mlt_properties_get( properties, "resource" ), 1 );
2640 context = self->audio_format;
2643 // Exception handling for audio_index
2644 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2646 for ( index = context->nb_streams - 1;
2647 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2649 mlt_properties_set_int( properties, "audio_index", index );
2651 if ( context && index > -1 && index < INT_MAX &&
2652 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2654 index = self->audio_index;
2655 mlt_properties_set_int( properties, "audio_index", index );
2657 if ( context && index > -1 && index < INT_MAX &&
2658 pick_audio_format( context->streams[ index ]->codec->sample_fmt ) == mlt_audio_none )
2663 // Update the audio properties if the index changed
2664 if ( context && index > -1 && index != self->audio_index )
2666 pthread_mutex_lock( &self->open_mutex );
2667 if ( self->audio_codec[ self->audio_index ] )
2668 avcodec_close( self->audio_codec[ self->audio_index ] );
2669 self->audio_codec[ self->audio_index ] = NULL;
2670 pthread_mutex_unlock( &self->open_mutex );
2672 if ( self->audio_index != -1 )
2673 self->audio_index = index;
2678 if ( context && index == INT_MAX )
2680 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2681 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2682 for ( index = 0; index < context->nb_streams; index++ )
2684 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2685 audio_codec_init( self, index, properties );
2688 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2690 // Set the frame properties
2691 if ( index < MAX_AUDIO_STREAMS )
2693 mlt_properties_set_int( frame_properties, "audio_frequency", self->audio_codec[ index ]->sample_rate );
2694 mlt_properties_set_int( frame_properties, "audio_channels", self->audio_codec[ index ]->channels );
2697 if ( context && index > -1 )
2699 // Add our audio operation
2700 mlt_frame_push_audio( frame, self );
2701 mlt_frame_push_audio( frame, producer_get_audio );
2705 /** Our get frame implementation.
2708 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2710 // Access the private data
2711 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2712 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2713 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2718 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2719 producer->child = self;
2720 self->parent = producer;
2721 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2722 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2725 // Create an empty frame
2726 *frame = mlt_frame_init( service);
2730 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2734 mlt_cache_item_close( cache_item );
2738 // Update timecode on the frame we're creating
2739 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2742 producer_set_up_video( self, *frame );
2745 producer_set_up_audio( self, *frame );
2747 // Set the position of this producer
2748 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2749 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "original_position", position );
2751 // Calculate the next timecode
2752 mlt_producer_prepare_next( producer );
2757 static void producer_avformat_close( producer_avformat self )
2759 mlt_log_debug( NULL, "producer_avformat_close\n" );
2761 // Cleanup av contexts
2762 av_free_packet( &self->pkt );
2763 av_free( self->av_frame );
2764 pthread_mutex_lock( &self->open_mutex );
2766 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2768 if ( self->audio_resample[i] )
2769 audio_resample_close( self->audio_resample[i] );
2770 mlt_pool_release( self->audio_buffer[i] );
2771 av_free( self->decode_buffer[i] );
2772 if ( self->audio_codec[i] )
2773 avcodec_close( self->audio_codec[i] );
2774 self->audio_codec[i] = NULL;
2776 if ( self->video_codec )
2777 avcodec_close( self->video_codec );
2778 self->video_codec = NULL;
2780 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2781 if ( self->dummy_context )
2782 avformat_close_input( &self->dummy_context );
2783 if ( self->seekable && self->audio_format )
2784 avformat_close_input( &self->audio_format );
2785 if ( self->video_format )
2786 avformat_close_input( &self->video_format );
2788 if ( self->dummy_context )
2789 av_close_input_file( self->dummy_context );
2790 if ( self->seekable && self->audio_format )
2791 av_close_input_file( self->audio_format );
2792 if ( self->video_format )
2793 av_close_input_file( self->video_format );
2795 pthread_mutex_unlock( &self->open_mutex );
2797 vdpau_producer_close( self );
2799 if ( self->image_cache )
2800 mlt_cache_close( self->image_cache );
2802 // Cleanup the mutexes
2803 if ( self->is_mutex_init )
2805 pthread_mutex_destroy( &self->audio_mutex );
2806 pthread_mutex_destroy( &self->video_mutex );
2807 pthread_mutex_destroy( &self->packets_mutex );
2808 pthread_mutex_destroy( &self->open_mutex );
2811 // Cleanup the packet queues
2813 if ( self->apackets )
2815 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2817 av_free_packet( pkt );
2820 mlt_deque_close( self->apackets );
2821 self->apackets = NULL;
2823 if ( self->vpackets )
2825 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2827 av_free_packet( pkt );
2830 mlt_deque_close( self->vpackets );
2831 self->vpackets = NULL;
2837 static void producer_close( mlt_producer parent )
2839 // Remove this instance from the cache
2840 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2843 parent->close = NULL;
2844 mlt_producer_close( parent );