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 static int first_video_index( producer_avformat self )
283 AVFormatContext *context = self->video_format? self->video_format : self->audio_format;
284 int i = -1; // not found
287 for ( i = 0; i < context->nb_streams; i++ ) {
288 if ( context->streams[i]->codec &&
289 context->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
292 if ( i == context->nb_streams )
298 /** Find the default streams.
301 static mlt_properties find_default_streams( producer_avformat self )
305 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
306 AVDictionaryEntry *tag = NULL;
308 AVMetadataTag *tag = NULL;
310 AVFormatContext *context = self->video_format;
311 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
313 // Default to the first audio and video streams found
314 self->audio_index = -1;
315 self->video_index = -1;
317 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
319 // Allow for multiple audio and video streams in the file and select first of each (if available)
320 for( i = 0; i < context->nb_streams; i++ )
322 // Get the codec context
323 AVStream *stream = context->streams[ i ];
324 if ( ! stream ) continue;
325 AVCodecContext *codec_context = stream->codec;
326 if ( ! codec_context ) continue;
327 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
328 if ( ! codec ) continue;
330 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
332 // Determine the type and obtain the first index of each type
333 switch( codec_context->codec_type )
335 case CODEC_TYPE_VIDEO:
336 // Use first video stream
337 if ( self->video_index < 0 )
338 self->video_index = i;
339 mlt_properties_set( meta_media, key, "video" );
340 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
341 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
342 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
343 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
344 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
345 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
347 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
350 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
351 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
352 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
354 snprintf( key, sizeof(key), "meta.media.%d.codec.width", i );
355 mlt_properties_set_int( meta_media, key, codec_context->width );
356 snprintf( key, sizeof(key), "meta.media.%d.codec.height", i );
357 mlt_properties_set_int( meta_media, key, codec_context->height );
358 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
359 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
360 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
361 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
362 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(3<<8)+0)
363 mlt_properties_set( meta_media, key, av_get_pix_fmt_name( codec_context->pix_fmt ) );
365 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
367 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
368 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
369 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
370 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
371 switch ( codec_context->colorspace )
373 case AVCOL_SPC_SMPTE240M:
374 mlt_properties_set_int( meta_media, key, 240 );
376 case AVCOL_SPC_BT470BG:
377 case AVCOL_SPC_SMPTE170M:
378 mlt_properties_set_int( meta_media, key, 601 );
380 case AVCOL_SPC_BT709:
381 mlt_properties_set_int( meta_media, key, 709 );
384 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
385 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
390 case CODEC_TYPE_AUDIO:
391 if ( !codec_context->channels )
393 // Use first audio stream
394 if ( self->audio_index < 0 && pick_audio_format( codec_context->sample_fmt ) != mlt_audio_none )
395 self->audio_index = i;
397 mlt_properties_set( meta_media, key, "audio" );
398 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
399 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
400 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
401 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
402 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
403 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
405 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
406 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
407 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
408 mlt_properties_set_int( meta_media, key, codec_context->channels );
413 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
414 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
415 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
416 mlt_properties_set( meta_media, key, codec->name );
417 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
418 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
419 mlt_properties_set( meta_media, key, codec->long_name );
421 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
422 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
423 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
424 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
425 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
426 // mlt_properties_set_int( meta_media, key, codec_context->profile );
427 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
428 // mlt_properties_set_int( meta_media, key, codec_context->level );
431 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
432 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
433 while ( ( tag = av_dict_get( stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
435 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
438 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
440 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
441 mlt_properties_set( meta_media, key, tag->value );
446 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
447 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
448 while ( ( tag = av_dict_get( context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
450 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
453 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
455 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
456 mlt_properties_set( meta_media, key, tag->value );
460 if ( context->title && strcmp( context->title, "" ) )
461 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
462 if ( context->author && strcmp( context->author, "" ) )
463 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
464 if ( context->copyright && strcmp( context->copyright, "" ) )
465 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
466 if ( context->comment )
467 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
468 if ( context->album )
469 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
471 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
472 if ( context->track )
473 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
479 static inline int dv_is_pal( AVPacket *pkt )
481 return pkt->data[3] & 0x80;
484 static int dv_is_wide( AVPacket *pkt )
486 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
488 for ( ; i < pkt->size; i += 5 /* packet size */ )
490 if ( pkt->data[ i ] == 0x61 )
492 uint8_t x = pkt->data[ i + 2 ] & 0x7;
493 return ( x == 2 ) || ( x == 7 );
499 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
501 double aspect_ratio = 1.0;
503 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
507 if ( dv_is_pal( pkt ) )
509 if ( dv_is_wide( pkt ) )
511 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
512 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
516 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
517 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
522 if ( dv_is_wide( pkt ) )
524 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
525 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
529 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
530 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
537 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
538 stream->sample_aspect_ratio;
540 codec_context->sample_aspect_ratio;
542 // Override FFmpeg's notion of DV aspect ratios, which are
543 // based upon a width of 704. Since we do not have a normaliser
544 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
545 // we just coerce the values to facilitate a passive behaviour through
546 // the rescale normaliser when using equivalent producers and consumers.
547 // = display_aspect / (width * height)
548 if ( ar.num == 10 && ar.den == 11 )
551 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
552 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
554 else if ( ar.num == 59 && ar.den == 54 )
557 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
558 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
560 else if ( ar.num == 40 && ar.den == 33 )
563 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
564 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
566 else if ( ar.num == 118 && ar.den == 81 )
569 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
570 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
576 AVRational codec_sar = codec_context->sample_aspect_ratio;
577 AVRational stream_sar =
578 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
579 stream->sample_aspect_ratio;
583 if ( codec_sar.num > 0 )
585 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
586 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
588 else if ( stream_sar.num > 0 )
590 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
591 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
595 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
596 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
599 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
600 aspect_ratio = av_q2d( ar );
601 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
606 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
607 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVDictionary **params )
609 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
612 if ( !URL ) return NULL;
615 char *protocol = strdup( URL );
616 char *url = strchr( protocol, ':' );
618 // Only if there is not a protocol specification that avformat can handle
619 #if LIBAVFORMAT_VERSION_MAJOR >= 53
620 if ( url && avio_check( URL, 0 ) < 0 )
622 if ( url && !url_exist( URL ) )
625 // Truncate protocol string
627 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
630 *format = av_find_input_format( protocol );
632 // Eat the format designator
637 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
638 // support for legacy width and height parameters
642 // These are required by video4linux2 (defaults)
643 params->width = profile->width;
644 params->height = profile->height;
645 if ( !strstr( URL, "&frame_rate" ) )
646 params->time_base = (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
647 params->channels = 2;
648 params->sample_rate = 48000;
652 url = strchr( url, '?' );
656 char *name = strdup( ++url );
657 char *value = strchr( name, '=' );
659 // Also accept : as delimiter for backwards compatibility.
660 value = strchr( name, ':' );
665 char *t = strchr( value, '&' );
668 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
669 // translate old parameters to new av_dict names
670 if ( !strcmp( name, "frame_rate" ) )
671 av_dict_set( params, "framerate", value, 0 );
672 else if ( !strcmp( name, "pix_fmt" ) )
673 av_dict_set( params, "pixel_format", value, 0 );
674 else if ( !strcmp( name, "width" ) )
675 width = strdup( value );
676 else if ( !strcmp( name, "height" ) )
677 height = strdup( value );
679 // generic demux/device option support
680 av_dict_set( params, name, value, 0 );
682 if ( !strcmp( name, "frame_rate" ) )
683 params->time_base.den = atoi( value );
684 else if ( !strcmp( name, "frame_rate_base" ) )
685 params->time_base.num = atoi( value );
686 else if ( !strcmp( name, "sample_rate" ) )
687 params->sample_rate = atoi( value );
688 else if ( !strcmp( name, "channel" ) )
689 params->channel = atoi( value );
690 else if ( !strcmp( name, "channels" ) )
691 params->channels = atoi( value );
692 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
693 else if ( !strcmp( name, "pix_fmt" ) )
694 params->pix_fmt = av_get_pix_fmt( value );
696 else if ( !strcmp( name, "width" ) )
697 params->width = atoi( value );
698 else if ( !strcmp( name, "height" ) )
699 params->height = atoi( value );
700 else if ( !strcmp( name, "standard" ) )
701 params->standard = strdup( value );
705 url = strchr( url, '&' );
707 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
708 // continued support for legacy width and height parameters
709 if ( width && height )
711 char *s = malloc( strlen( width ) + strlen( height ) + 2 );
715 av_dict_set( params, "video_size", s, 0 );
718 if ( width ) free( width );
719 if ( height ) free ( height );
722 result = strdup( result );
726 result = strdup( URL );
732 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
736 // Get the properties
737 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
739 AVFormatContext *format = self->video_format;
741 // We will treat everything with the producer fps.
742 // TODO: make this more flexible.
743 double fps = mlt_profile_fps( profile );
746 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
748 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
749 // when producer_open is called after initial call when restoring or reseting the producer.
750 if ( format->duration != AV_NOPTS_VALUE )
752 // This isn't going to be accurate for all formats
753 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
754 mlt_properties_set_position( properties, "out", frames - 1 );
755 mlt_properties_set_position( properties, "length", frames );
756 mlt_properties_set_int( properties, "_length_computed", 1 );
760 // Set live sources to run forever
761 mlt_properties_set_position( properties, "length", INT_MAX );
762 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
763 mlt_properties_set( properties, "eof", "loop" );
764 mlt_properties_set_int( properties, "_length_computed", 1 );
768 // Check if we're seekable
769 // avdevices are typically AVFMT_NOFILE and not seekable
770 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
773 // protocols can indicate if they support seeking
774 #if LIBAVFORMAT_VERSION_MAJOR >= 53
775 self->seekable = format->pb->seekable;
777 URLContext *uc = url_fileno( format->pb );
779 self->seekable = !uc->is_streamed;
782 if ( self->seekable )
784 // Do a more rigourous test of seekable on a disposable context
785 self->seekable = av_seek_frame( format, -1, format->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
786 mlt_properties_set_int( properties, "seekable", self->seekable );
787 self->dummy_context = format;
788 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
789 self->video_format = NULL;
790 avformat_open_input( &self->video_format, filename, NULL, NULL );
791 avformat_find_stream_info( self->video_format, NULL );
793 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
794 av_find_stream_info( self->video_format );
796 format = self->video_format;
799 // Fetch the width, height and aspect ratio
800 if ( self->video_index != -1 )
802 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
803 mlt_properties_set_int( properties, "width", codec_context->width );
804 mlt_properties_set_int( properties, "height", codec_context->height );
806 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
808 // Fetch the first frame of DV so we can read it directly
813 ret = av_read_frame( format, &pkt );
814 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
816 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
817 av_free_packet(&pkt);
821 av_free_packet(&pkt);
826 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
830 // Verify that we can convert this to YUV 4:2:2
831 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
832 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
833 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
835 sws_freeContext( context );
846 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
848 // Return an error code (0 == no error)
850 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
855 if ( !self->is_mutex_init )
857 pthread_mutex_init( &self->audio_mutex, NULL );
858 pthread_mutex_init( &self->video_mutex, NULL );
859 pthread_mutex_init( &self->packets_mutex, NULL );
860 pthread_mutex_init( &self->open_mutex, NULL );
861 self->is_mutex_init = 1;
863 pthread_mutex_lock( &self->audio_mutex );
864 pthread_mutex_lock( &self->video_mutex );
866 mlt_events_block( properties, self->parent );
869 AVInputFormat *format = NULL;
870 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
871 AVDictionary *params = NULL;
873 AVFormatParameters params;
874 memset( ¶ms, 0, sizeof(params) );
876 char *filename = parse_url( profile, URL, &format, ¶ms );
878 // Now attempt to open the file or device with filename
879 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
880 error = avformat_open_input( &self->video_format, filename, format, ¶ms ) < 0;
882 // If the URL is a network stream URL, then we probably need to open with full URL
883 error = avformat_open_input( &self->video_format, URL, format, ¶ms ) < 0;
885 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
887 // If the URL is a network stream URL, then we probably need to open with full URL
888 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
891 // Set MLT properties onto video AVFormatContext
892 if ( !error && self->video_format )
894 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
895 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
896 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
897 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
901 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
902 av_dict_free( ¶ms );
904 // Cleanup AVFormatParameters
905 if ( params.standard )
906 free( (void*) params.standard );
909 // If successful, then try to get additional info
910 if ( !error && self->video_format )
912 // Get the stream info
913 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
914 error = avformat_find_stream_info( self->video_format, NULL ) < 0;
916 error = av_find_stream_info( self->video_format ) < 0;
919 // Continue if no error
920 if ( !error && self->video_format )
922 // Find default audio and video streams
923 find_default_streams( self );
924 error = get_basic_info( self, profile, filename );
926 // Initialize position info
927 self->first_pts = AV_NOPTS_VALUE;
928 self->last_position = POSITION_INITIAL;
930 if ( !self->audio_format )
932 // We're going to cheat here - for seekable A/V files, we will have separate contexts
933 // to support independent seeking of audio from video.
934 // TODO: Is this really necessary?
935 if ( self->audio_index != -1 && self->video_index != -1 )
937 if ( self->seekable )
939 // And open again for our audio context
940 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
941 avformat_open_input( &self->audio_format, filename, NULL, NULL );
942 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
943 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
944 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
945 avformat_find_stream_info( self->audio_format, NULL );
947 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
948 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
949 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
950 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
951 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
953 av_find_stream_info( self->audio_format );
958 self->audio_format = self->video_format;
961 else if ( self->audio_index != -1 )
963 // We only have an audio context
964 self->audio_format = self->video_format;
965 self->video_format = NULL;
967 else if ( self->video_index == -1 )
969 // Something has gone wrong
972 if ( self->audio_format && !self->audio_streams )
973 get_audio_streams_info( self );
981 self->apackets = mlt_deque_init();
982 self->vpackets = mlt_deque_init();
985 if ( self->dummy_context )
987 pthread_mutex_lock( &self->open_mutex );
988 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
989 avformat_close_input( &self->dummy_context );
991 av_close_input_file( self->dummy_context );
993 self->dummy_context = NULL;
994 pthread_mutex_unlock( &self->open_mutex );
997 // Unlock the service
1000 pthread_mutex_unlock( &self->audio_mutex );
1001 pthread_mutex_unlock( &self->video_mutex );
1003 mlt_events_unblock( properties, self->parent );
1008 static void reopen_video( producer_avformat self, mlt_producer producer )
1010 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1011 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1012 pthread_mutex_lock( &self->audio_mutex );
1013 pthread_mutex_lock( &self->open_mutex );
1015 if ( self->video_codec )
1016 avcodec_close( self->video_codec );
1017 self->video_codec = NULL;
1018 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
1019 if ( self->dummy_context )
1020 avformat_close_input( &self->dummy_context );
1021 if ( self->video_format )
1022 avformat_close_input( &self->video_format );
1024 if ( self->dummy_context )
1025 av_close_input_file( self->dummy_context );
1026 if ( self->video_format )
1027 av_close_input_file( self->video_format );
1029 self->dummy_context = NULL;
1030 self->video_format = NULL;
1031 pthread_mutex_unlock( &self->open_mutex );
1033 int audio_index = self->audio_index;
1034 int video_index = self->video_index;
1036 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1037 mlt_properties_get( properties, "resource" ), 0 );
1039 self->audio_index = audio_index;
1040 if ( self->video_format && video_index > -1 )
1042 self->video_index = video_index;
1043 video_codec_init( self, video_index, properties );
1046 pthread_mutex_unlock( &self->audio_mutex );
1047 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1050 static int64_t best_pts( producer_avformat self, int64_t pts, int64_t dts )
1052 self->invalid_pts_counter += pts == AV_NOPTS_VALUE;
1053 self->invalid_dts_counter += dts == AV_NOPTS_VALUE;
1054 if ( ( self->invalid_pts_counter <= self->invalid_dts_counter
1055 || dts == AV_NOPTS_VALUE ) && pts != AV_NOPTS_VALUE )
1061 static void find_first_pts( producer_avformat self, int video_index )
1064 AVFormatContext *context = self->video_format? self->video_format : self->audio_format;
1069 while ( ret >= 0 && toscan-- > 0 )
1071 ret = av_read_frame( context, &pkt );
1072 if ( ret >= 0 && pkt.stream_index == video_index && ( pkt.flags & PKT_FLAG_KEY ) )
1074 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
1075 "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n",
1076 pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
1077 self->first_pts = best_pts( self, pkt.pts, pkt.dts );
1078 if ( self->first_pts != AV_NOPTS_VALUE )
1081 av_free_packet( &pkt );
1083 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1086 static int seek_video( producer_avformat self, mlt_position position,
1087 int64_t req_position, int preseek )
1089 mlt_producer producer = self->parent;
1092 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
1094 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1096 // Fetch the video format context
1097 AVFormatContext *context = self->video_format;
1099 // Get the video stream
1100 AVStream *stream = context->streams[ self->video_index ];
1102 // Get codec context
1103 AVCodecContext *codec_context = stream->codec;
1105 // We may want to use the source fps if available
1106 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1107 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1109 if ( self->last_position == POSITION_INITIAL )
1110 find_first_pts( self, self->video_index );
1112 if ( self->av_frame && position + 1 == self->video_expected )
1114 // We're paused - use last image
1117 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
1119 // Calculate the timestamp for the requested frame
1120 int64_t timestamp = req_position / ( av_q2d( stream->time_base ) * source_fps );
1121 if ( req_position <= 0 )
1123 else if ( self->first_pts != AV_NOPTS_VALUE )
1124 timestamp += self->first_pts;
1125 else if ( context->start_time != AV_NOPTS_VALUE )
1126 timestamp += context->start_time;
1127 if ( preseek && av_q2d( stream->time_base ) != 0 )
1128 timestamp -= 2 / av_q2d( stream->time_base );
1129 if ( timestamp < 0 )
1131 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
1132 timestamp, position, self->video_expected, self->last_position );
1134 // Seek to the timestamp
1135 // NOTE: reopen_video is disabled at this time because it is causing trouble with A/V sync.
1136 if ( 1 || req_position > 0 || self->last_position <= 0 )
1138 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1139 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1141 // flush any pictures still in decode buffer
1142 avcodec_flush_buffers( codec_context );
1146 // Re-open video stream when rewinding to beginning from somewhere else.
1147 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1148 // not reliably seeking to the first frame across formats.
1149 reopen_video( self, producer );
1152 // Remove the cached info relating to the previous position
1153 self->current_position = POSITION_INVALID;
1154 self->last_position = POSITION_INVALID;
1155 av_freep( &self->av_frame );
1161 /** Convert a frame position to a time code.
1164 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1166 return ( double )position / mlt_producer_get_fps( producer );
1169 // Collect information about all audio streams
1171 static void get_audio_streams_info( producer_avformat self )
1173 // Fetch the audio format context
1174 AVFormatContext *context = self->audio_format;
1178 i < context->nb_streams;
1181 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1183 AVCodecContext *codec_context = context->streams[i]->codec;
1184 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1186 // If we don't have a codec and we can't initialise it, we can't do much more...
1187 pthread_mutex_lock( &self->open_mutex );
1188 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1189 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1191 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1194 self->audio_streams++;
1195 self->audio_max_stream = i;
1196 self->total_channels += codec_context->channels;
1197 if ( codec_context->channels > self->max_channel )
1198 self->max_channel = codec_context->channels;
1199 if ( codec_context->sample_rate > self->max_frequency )
1200 self->max_frequency = codec_context->sample_rate;
1201 avcodec_close( codec_context );
1203 pthread_mutex_unlock( &self->open_mutex );
1206 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1207 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1209 // Other audio-specific initializations
1210 self->resample_factor = 1.0;
1213 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1215 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1217 const int *new_coefficients;
1219 int brightness, contrast, saturation;
1221 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1222 &brightness, &contrast, &saturation ) != -1 )
1224 // Don't change these from defaults unless explicitly told to.
1225 if ( use_full_range >= 0 )
1226 full_range = use_full_range;
1227 switch ( colorspace )
1233 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1236 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1239 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1242 new_coefficients = coefficients;
1245 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1246 brightness, contrast, saturation );
1251 static mlt_image_format pick_pix_format( enum PixelFormat pix_fmt )
1259 return mlt_image_rgb24a;
1260 case PIX_FMT_YUV420P:
1261 case PIX_FMT_YUVJ420P:
1262 case PIX_FMT_YUVA420P:
1263 return mlt_image_yuv420p;
1267 case PIX_FMT_MONOWHITE:
1268 case PIX_FMT_MONOBLACK:
1271 return mlt_image_rgb24;
1273 return mlt_image_yuv422;
1277 static mlt_audio_format pick_audio_format( int sample_fmt )
1279 switch ( sample_fmt )
1282 case AV_SAMPLE_FMT_U8:
1283 return mlt_audio_u8;
1284 case AV_SAMPLE_FMT_S16:
1285 return mlt_audio_s16;
1286 case AV_SAMPLE_FMT_S32:
1287 return mlt_audio_s32le;
1288 case AV_SAMPLE_FMT_FLT:
1289 return mlt_audio_f32le;
1290 // planar - this producer converts planar to interleaved
1291 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1292 case AV_SAMPLE_FMT_U8P:
1293 return mlt_audio_u8;
1294 case AV_SAMPLE_FMT_S16P:
1295 return mlt_audio_s16;
1296 case AV_SAMPLE_FMT_S32P:
1297 return mlt_audio_s32le;
1298 case AV_SAMPLE_FMT_FLTP:
1299 return mlt_audio_f32le;
1302 return mlt_audio_none;
1306 static void convert_image( producer_avformat self, AVFrame *frame, uint8_t *buffer, int pix_fmt,
1307 mlt_image_format *format, int width, int height, uint8_t **alpha )
1310 int flags = SWS_BICUBIC | SWS_ACCURATE_RND;
1313 flags |= SWS_CPU_CAPS_MMX;
1316 flags |= SWS_CPU_CAPS_MMX2;
1319 // extract alpha from planar formats
1320 if ( ( pix_fmt == PIX_FMT_YUVA420P
1321 #if defined(FFUDIV) && LIBAVUTIL_VERSION_INT >= ((51<<16)+(35<<8)+101)
1322 || pix_fmt == PIX_FMT_YUVA444P
1325 *format != mlt_image_rgb24a && *format != mlt_image_opengl &&
1326 frame->data[3] && frame->linesize[3] )
1331 dst = *alpha = mlt_pool_alloc( width * height );
1332 src = frame->data[3];
1334 for ( i = 0; i < height; dst += width, src += frame->linesize[3], i++ )
1335 memcpy( dst, src, FFMIN( width, frame->linesize[3] ) );
1338 if ( *format == mlt_image_yuv420p )
1340 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1341 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1343 output.data[0] = buffer;
1344 output.data[1] = buffer + width * height;
1345 output.data[2] = buffer + ( 5 * width * height ) / 4;
1346 output.linesize[0] = width;
1347 output.linesize[1] = width >> 1;
1348 output.linesize[2] = width >> 1;
1349 set_luma_transfer( context, self->colorspace, -1 );
1350 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1351 output.data, output.linesize);
1352 sws_freeContext( context );
1354 else if ( *format == mlt_image_rgb24 )
1356 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1357 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1359 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1360 set_luma_transfer( context, self->colorspace, self->full_luma );
1361 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1362 output.data, output.linesize);
1363 sws_freeContext( context );
1365 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1367 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1368 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1370 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1371 set_luma_transfer( context, self->colorspace, self->full_luma );
1372 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1373 output.data, output.linesize);
1374 sws_freeContext( context );
1378 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1379 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1381 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1382 set_luma_transfer( context, self->colorspace, -1 );
1383 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1384 output.data, output.linesize);
1385 sws_freeContext( context );
1388 if ( *format == mlt_image_yuv420p )
1391 pict.data[0] = buffer;
1392 pict.data[1] = buffer + width * height;
1393 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1394 pict.linesize[0] = width;
1395 pict.linesize[1] = width >> 1;
1396 pict.linesize[2] = width >> 1;
1397 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1399 else if ( *format == mlt_image_rgb24 )
1402 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1403 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1405 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1408 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1409 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1414 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1415 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1420 /** Allocate the image buffer and set it on the frame.
1423 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1427 if ( codec_context->width == 0 || codec_context->height == 0 )
1429 *width = codec_context->width;
1430 *height = codec_context->height;
1431 size = mlt_image_format_size( *format, *width, *height, NULL );
1432 *buffer = mlt_pool_alloc( size );
1434 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1441 /** Get an image from a frame.
1444 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1447 producer_avformat self = mlt_frame_pop_service( frame );
1448 mlt_producer producer = self->parent;
1450 // Get the properties from the frame
1451 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1453 // Obtain the frame number of this frame
1454 mlt_position position = mlt_frame_original_position( frame );
1456 // Get the producer properties
1457 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1459 pthread_mutex_lock( &self->video_mutex );
1461 // Fetch the video format context
1462 AVFormatContext *context = self->video_format;
1464 // Get the video stream
1465 AVStream *stream = context->streams[ self->video_index ];
1467 // Get codec context
1468 AVCodecContext *codec_context = stream->codec;
1470 uint8_t *alpha = NULL;
1471 int got_picture = 0;
1474 // Get the image cache
1475 if ( ! self->image_cache )
1477 // if cache size supplied by environment variable
1478 int cache_supplied = getenv( "MLT_AVFORMAT_CACHE" ) != NULL;
1479 int cache_size = cache_supplied? atoi( getenv( "MLT_AVFORMAT_CACHE" ) ) : 0;
1481 // cache size supplied via property
1482 if ( mlt_properties_get( properties, "cache" ) )
1485 cache_size = mlt_properties_get_int( properties, "cache" );
1487 if ( mlt_properties_get_int( properties, "noimagecache" ) )
1489 // create cache if not disabled
1490 if ( !cache_supplied || cache_size > 0 )
1491 self->image_cache = mlt_cache_init();
1492 // set cache size if supplied
1493 if ( self->image_cache && cache_supplied )
1494 mlt_cache_set_size( self->image_cache, cache_size );
1496 if ( self->image_cache )
1498 mlt_frame original = mlt_cache_get_frame( self->image_cache, position );
1501 mlt_properties orig_props = MLT_FRAME_PROPERTIES( original );
1504 *buffer = mlt_properties_get_data( orig_props, "alpha", &size );
1506 mlt_frame_set_alpha( frame, *buffer, size, NULL );
1507 *buffer = mlt_properties_get_data( orig_props, "image", &size );
1508 mlt_frame_set_image( frame, *buffer, size, NULL );
1509 mlt_properties_set_data( frame_properties, "avformat.image_cache", original, 0, (mlt_destructor) mlt_frame_close, NULL );
1510 *format = mlt_properties_get_int( orig_props, "format" );
1512 // Set the resolution
1513 *width = codec_context->width;
1514 *height = codec_context->height;
1516 // Workaround 1088 encodings missing cropping info.
1517 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1521 goto exit_get_image;
1526 // We may want to use the source fps if available
1527 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1528 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1530 // This is the physical frame position in the source
1531 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1533 // Determines if we have to decode all frames in a sequence
1534 // Temporary hack to improve intra frame only
1535 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1536 strcmp( codec_context->codec->name, "dnxhd" ) &&
1537 strcmp( codec_context->codec->name, "dvvideo" ) &&
1538 strcmp( codec_context->codec->name, "huffyuv" ) &&
1539 strcmp( codec_context->codec->name, "mjpeg" ) &&
1540 strcmp( codec_context->codec->name, "rawvideo" ) );
1542 double delay = mlt_properties_get_double( properties, "video_delay" );
1544 // Seek if necessary
1545 const char *interp = mlt_properties_get( frame_properties, "rescale.interp" );
1546 int preseek = must_decode
1547 #if defined(FFUDIV) && LIBAVFORMAT_VERSION_INT >= ((53<<16)+(24<<8)+2)
1548 && ( interp && strcmp( interp, "nearest" ) )
1550 && codec_context->has_b_frames;
1551 int paused = seek_video( self, position, req_position, preseek );
1553 // Seek might have reopened the file
1554 context = self->video_format;
1555 stream = context->streams[ self->video_index ];
1556 codec_context = stream->codec;
1557 if ( *format == mlt_image_none ||
1558 codec_context->pix_fmt == PIX_FMT_ARGB ||
1559 codec_context->pix_fmt == PIX_FMT_RGBA ||
1560 codec_context->pix_fmt == PIX_FMT_ABGR ||
1561 codec_context->pix_fmt == PIX_FMT_BGRA )
1562 *format = pick_pix_format( codec_context->pix_fmt );
1564 // Duplicate the last image if necessary
1565 if ( self->av_frame && self->av_frame->linesize[0]
1566 && ( paused || self->current_position >= req_position ) )
1569 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1571 // Workaround 1088 encodings missing cropping info.
1572 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1575 if ( self->vdpau && self->vdpau->buffer )
1578 picture.data[0] = self->vdpau->buffer;
1579 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1580 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1581 picture.linesize[0] = codec_context->width;
1582 picture.linesize[1] = codec_context->width / 2;
1583 picture.linesize[2] = codec_context->width / 2;
1584 convert_image( self, (AVFrame*) &picture, *buffer,
1585 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1589 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1590 format, *width, *height, &alpha );
1597 int64_t int_position = 0;
1598 int decode_errors = 0;
1600 // Construct an AVFrame for YUV422 conversion
1601 if ( !self->av_frame )
1602 self->av_frame = avcodec_alloc_frame( );
1604 while( ret >= 0 && !got_picture )
1607 if ( self->pkt.stream_index == self->video_index )
1608 av_free_packet( &self->pkt );
1609 av_init_packet( &self->pkt );
1610 pthread_mutex_lock( &self->packets_mutex );
1611 if ( mlt_deque_count( self->vpackets ) )
1613 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1619 ret = av_read_frame( context, &self->pkt );
1620 if ( ret >= 0 && !self->seekable && self->pkt.stream_index == self->audio_index )
1622 if ( !av_dup_packet( &self->pkt ) )
1624 AVPacket *tmp = malloc( sizeof(AVPacket) );
1626 mlt_deque_push_back( self->apackets, tmp );
1630 pthread_mutex_unlock( &self->packets_mutex );
1632 // We only deal with video from the selected video_index
1633 if ( ret >= 0 && self->pkt.stream_index == self->video_index && self->pkt.size > 0 )
1635 int64_t pts = best_pts( self, self->pkt.pts, self->pkt.dts );
1636 if ( pts != AV_NOPTS_VALUE )
1638 if ( !self->seekable && self->first_pts == AV_NOPTS_VALUE )
1639 self->first_pts = pts;
1640 if ( self->first_pts != AV_NOPTS_VALUE )
1641 pts -= self->first_pts;
1642 else if ( context->start_time != AV_NOPTS_VALUE )
1643 pts -= context->start_time;
1644 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.5 );
1645 if ( int_position == self->last_position )
1646 int_position = self->last_position + 1;
1648 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1649 "V pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1650 self->pkt.pts, self->pkt.dts, req_position, self->current_position, int_position );
1652 // Make a dumb assumption on streams that contain wild timestamps
1653 if ( abs( req_position - int_position ) > 999 )
1655 int_position = req_position;
1656 mlt_log_warning( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!\n" );
1658 self->last_position = int_position;
1661 if ( must_decode || int_position >= req_position )
1666 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1668 vdpau_decoder_init( self );
1670 self->vdpau->is_decoded = 0;
1673 codec_context->reordered_opaque = int_position;
1674 if ( int_position >= req_position )
1675 codec_context->skip_loop_filter = AVDISCARD_NONE;
1676 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1677 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &self->pkt );
1679 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, self->pkt.data, self->pkt.size );
1681 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1684 if ( ++decode_errors <= 10 )
1695 // Get position of reordered frame
1696 int_position = self->av_frame->reordered_opaque;
1697 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(106<<8)+0))
1698 pts = best_pts( self, self->av_frame->pkt_pts, self->av_frame->pkt_dts );
1699 if ( pts != AV_NOPTS_VALUE )
1701 if ( self->first_pts != AV_NOPTS_VALUE )
1702 pts -= self->first_pts;
1703 else if ( context->start_time != AV_NOPTS_VALUE )
1704 pts -= context->start_time;
1705 int_position = ( int64_t )( ( av_q2d( stream->time_base ) * pts + delay ) * source_fps + 0.5 );
1709 if ( int_position < req_position )
1711 else if ( int_position >= req_position )
1712 codec_context->skip_loop_filter = AVDISCARD_NONE;
1714 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, self->pkt.flags & PKT_FLAG_KEY );
1717 // Now handle the picture if we have one
1720 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1722 // Workaround 1088 encodings missing cropping info.
1723 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1728 if ( self->vdpau->is_decoded )
1730 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1732 uint32_t pitches[3];
1733 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1735 if ( !self->vdpau->buffer )
1736 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1737 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1738 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1739 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1740 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1741 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1742 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1744 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1745 if ( status == VDP_STATUS_OK )
1747 convert_image( self, self->av_frame, *buffer, PIX_FMT_YUV420P,
1748 format, *width, *height, &alpha );
1752 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1753 image_size = self->vdpau->is_decoded = 0;
1758 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1759 image_size = got_picture = 0;
1764 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1765 format, *width, *height, &alpha );
1766 self->top_field_first |= self->av_frame->top_field_first;
1767 self->current_position = int_position;
1775 // Free packet data if not video and not live audio packet
1776 if ( self->pkt.stream_index != self->video_index &&
1777 !( !self->seekable && self->pkt.stream_index == self->audio_index ) )
1778 av_free_packet( &self->pkt );
1784 mlt_frame_set_alpha( frame, alpha, (*width) * (*height), mlt_pool_release );
1786 if ( image_size > 0 && self->image_cache )
1788 mlt_properties_set_int( frame_properties, "format", *format );
1789 mlt_cache_put_frame( self->image_cache, frame );
1792 // Try to duplicate last image if there was a decoding failure
1793 // TODO: with multithread decoding a partial frame decoding resulting
1794 // in failure also resets av_frame making test below fail.
1795 if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1798 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1800 // Workaround 1088 encodings missing cropping info.
1801 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1804 if ( self->vdpau && self->vdpau->buffer )
1807 picture.data[0] = self->vdpau->buffer;
1808 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1809 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1810 picture.linesize[0] = codec_context->width;
1811 picture.linesize[1] = codec_context->width / 2;
1812 picture.linesize[2] = codec_context->width / 2;
1813 convert_image( self, (AVFrame*) &picture, *buffer,
1814 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1818 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1819 format, *width, *height, &alpha );
1824 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1825 self->video_expected = position + 1;
1829 pthread_mutex_unlock( &self->video_mutex );
1831 // Set the progressive flag
1832 if ( mlt_properties_get( properties, "force_progressive" ) )
1833 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1834 else if ( self->av_frame )
1835 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1837 // Set the field order property for this frame
1838 if ( mlt_properties_get( properties, "force_tff" ) )
1839 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1841 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1843 // Set immutable properties of the selected track's (or overridden) source attributes.
1844 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1845 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1846 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1847 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1849 // If we already have RGB, then the full range processing either happened already
1850 // or does not apply (RGB source).
1851 if ( *format == mlt_image_rgb24 || *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1852 mlt_properties_set( frame_properties, "force_full_luma", NULL );
1854 return !got_picture;
1857 /** Process properties as AVOptions and apply to AV context obj
1860 static void apply_properties( void *obj, mlt_properties properties, int flags )
1863 int count = mlt_properties_count( properties );
1864 for ( i = 0; i < count; i++ )
1866 const char *opt_name = mlt_properties_get_name( properties, i );
1867 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
1868 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1870 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1872 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1875 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1876 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1877 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1878 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1879 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1880 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1882 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1888 /** Initialize the video codec context.
1891 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1893 // Initialise the codec if necessary
1894 if ( !self->video_codec )
1896 // Get the video stream
1897 AVStream *stream = self->video_format->streams[ index ];
1899 // Get codec context
1900 AVCodecContext *codec_context = stream->codec;
1903 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1905 if ( codec_context->codec_id == CODEC_ID_H264 )
1907 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1909 if ( vdpau_init( self ) )
1911 self->video_codec = codec_context;
1912 if ( !vdpau_decoder_init( self ) )
1917 codec = avcodec_find_decoder( codec_context->codec_id );
1921 // Initialise multi-threading
1922 int thread_count = mlt_properties_get_int( properties, "threads" );
1923 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1924 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1925 if ( thread_count > 1 )
1926 codec_context->thread_count = thread_count;
1928 // If we don't have a codec and we can't initialise it, we can't do much more...
1929 pthread_mutex_lock( &self->open_mutex );
1930 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1931 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1933 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1936 // Now store the codec with its destructor
1937 self->video_codec = codec_context;
1941 // Remember that we can't use this later
1942 self->video_index = -1;
1943 pthread_mutex_unlock( &self->open_mutex );
1946 pthread_mutex_unlock( &self->open_mutex );
1948 // Process properties as AVOptions
1949 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1950 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1951 if ( codec->priv_class && codec_context->priv_data )
1952 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1955 // Reset some image properties
1956 if ( self->video_codec )
1958 mlt_properties_set_int( properties, "width", self->video_codec->width );
1959 mlt_properties_set_int( properties, "height", self->video_codec->height );
1961 // For DV, we'll just use the saved aspect ratio
1962 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1963 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1965 // Determine the fps first from the codec
1966 double source_fps = (double) self->video_codec->time_base.den /
1967 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1970 // If the muxer reports a frame rate different than the codec
1971 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1972 double muxer_fps = av_q2d( stream->avg_frame_rate );
1973 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1974 muxer_fps = av_q2d( stream->r_frame_rate );
1976 double muxer_fps = av_q2d( stream->r_frame_rate );
1978 // Choose the lesser - the wrong tends to be off by some multiple of 10
1979 source_fps = FFMIN( source_fps, muxer_fps );
1980 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1982 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1983 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1985 else if ( muxer_fps > 0 )
1987 AVRational frame_rate = stream->r_frame_rate;
1988 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1989 // avg_frame_rate gives some approximate value that does not well match the media.
1990 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1991 // results in some very choppy output, but some value slightly different works
1993 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1994 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1995 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1997 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1998 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
2002 source_fps = mlt_producer_get_fps( self->parent );
2003 AVRational frame_rate = av_d2q( source_fps, 255 );
2004 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
2005 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
2008 if ( mlt_properties_get( properties, "force_fps" ) )
2010 double source_fps = mlt_properties_get_double( properties, "force_fps" );
2011 AVRational fps = av_d2q( source_fps, 1024 );
2012 stream->time_base.num *= mlt_properties_get_int( properties, "meta.media.frame_rate_num" ) * fps.den;
2013 stream->time_base.den *= mlt_properties_get_int( properties, "meta.media.frame_rate_den" ) * fps.num;
2014 mlt_properties_set_int( properties, "meta.media.frame_rate_num", fps.num );
2015 mlt_properties_set_int( properties, "meta.media.frame_rate_den", fps.den );
2018 // Set the YUV colorspace from override or detect
2019 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
2020 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
2021 if ( ! self->colorspace )
2023 switch ( self->video_codec->colorspace )
2025 case AVCOL_SPC_SMPTE240M:
2026 self->colorspace = 240;
2028 case AVCOL_SPC_BT470BG:
2029 case AVCOL_SPC_SMPTE170M:
2030 self->colorspace = 601;
2032 case AVCOL_SPC_BT709:
2033 self->colorspace = 709;
2036 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
2037 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
2042 // Let apps get chosen colorspace
2043 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
2045 self->full_luma = -1;
2046 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(72<<8)+2)
2047 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent), "color_range %d\n", codec_context->color_range );
2048 if ( codec_context->color_range == AVCOL_RANGE_JPEG )
2049 self->full_luma = 1;
2051 if ( mlt_properties_get( properties, "set.force_full_luma" ) )
2052 self->full_luma = mlt_properties_get_int( properties, "set.force_full_luma" );
2054 return self->video_codec && self->video_index > -1;
2057 /** Set up video handling.
2060 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
2063 mlt_producer producer = self->parent;
2065 // Get the properties
2066 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2068 // Fetch the video format context
2069 AVFormatContext *context = self->video_format;
2071 // Get the video_index
2072 int index = mlt_properties_get_int( properties, "video_index" );
2074 // Reopen the file if necessary
2075 if ( !context && index > -1 )
2077 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2078 mlt_properties_get( properties, "resource" ), 1 );
2079 context = self->video_format;
2082 // Exception handling for video_index
2083 if ( context && index >= (int) context->nb_streams )
2085 // Get the last video stream
2086 for ( index = context->nb_streams - 1;
2087 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
2089 mlt_properties_set_int( properties, "video_index", index );
2091 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
2093 // Invalidate the video stream
2095 mlt_properties_set_int( properties, "video_index", index );
2098 // Update the video properties if the index changed
2099 if ( index != self->video_index )
2101 // Reset the video properties if the index changed
2102 self->video_index = index;
2103 pthread_mutex_lock( &self->open_mutex );
2104 if ( self->video_codec )
2105 avcodec_close( self->video_codec );
2106 self->video_codec = NULL;
2107 pthread_mutex_unlock( &self->open_mutex );
2110 // Get the frame properties
2111 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2114 if ( context && index > -1 && video_codec_init( self, index, properties ) )
2116 // Set the frame properties
2117 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
2118 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
2119 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
2121 // Set the width and height
2122 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
2123 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
2124 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
2125 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
2126 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
2127 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
2129 // Workaround 1088 encodings missing cropping info.
2130 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
2132 mlt_properties_set_int( properties, "meta.media.height", 1080 );
2135 // Add our image operation
2136 mlt_frame_push_service( frame, self );
2137 mlt_frame_push_get_image( frame, producer_get_image );
2141 // If something failed, use test card image
2142 mlt_properties_set_int( frame_properties, "test_image", 1 );
2146 static int seek_audio( producer_avformat self, mlt_position position, double timecode )
2150 // Seek if necessary
2151 if ( self->seekable && position != self->audio_expected )
2153 if ( self->last_position == POSITION_INITIAL )
2155 int video_index = self->video_index;
2156 if ( video_index == -1 )
2157 video_index = first_video_index( self );
2158 if ( video_index >= 0 )
2159 find_first_pts( self, video_index );
2162 if ( position + 1 == self->audio_expected )
2164 // We're paused - silence required
2167 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
2169 AVFormatContext *context = self->audio_format;
2170 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
2171 if ( context->start_time != AV_NOPTS_VALUE )
2172 timestamp += context->start_time;
2173 if ( timestamp < 0 )
2176 // Set to the real timecode
2177 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
2180 // Clear the usage in the audio buffer
2181 int i = MAX_AUDIO_STREAMS + 1;
2183 self->audio_used[i - 1] = 0;
2189 static int sample_bytes( AVCodecContext *context )
2191 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2192 return av_get_bytes_per_sample( context->sample_fmt );
2193 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2194 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2196 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2200 static void planar_to_interleaved( uint8_t *dest, uint8_t *src, int samples, int channels, int bytes_per_sample )
2203 for ( s = 0; s < samples; s++ )
2205 for ( c = 0; c < channels; c++ )
2207 memcpy( dest, src + ( c * samples + s ) * bytes_per_sample, bytes_per_sample );
2208 dest += bytes_per_sample;
2213 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2215 // Fetch the audio_format
2216 AVFormatContext *context = self->audio_format;
2218 // Get the current stream index
2219 int index = pkt.stream_index;
2221 // Get codec context
2222 AVCodecContext *codec_context = self->audio_codec[ index ];
2224 // Obtain the resample context if it exists (not always needed)
2225 ReSampleContext *resample = self->audio_resample[ index ];
2227 // Obtain the audio buffers
2228 uint8_t *audio_buffer = self->audio_buffer[ index ];
2229 uint8_t *decode_buffer = self->decode_buffer[ index ];
2231 int audio_used = self->audio_used[ index ];
2232 uint8_t *ptr = pkt.data;
2236 while ( ptr && ret >= 0 && len > 0 )
2238 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2239 int data_size = self->audio_buffer_size[ index ];
2242 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2243 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2244 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2245 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2247 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2251 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2255 pkt.size = len -= ret;
2256 pkt.data = ptr += ret;
2258 // If decoded successfully
2259 if ( data_size > 0 )
2261 // Figure out how many samples will be needed after resampling
2262 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2263 int samples_needed = self->resample_factor * convert_samples;
2265 // Resize audio buffer to prevent overflow
2266 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2268 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2269 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2273 // Copy to audio buffer while resampling
2274 uint8_t *source = decode_buffer;
2275 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2276 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2280 uint8_t *source = decode_buffer;
2281 uint8_t *dest = &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ];
2282 switch ( codec_context->sample_fmt )
2284 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2285 case AV_SAMPLE_FMT_U8P:
2286 case AV_SAMPLE_FMT_S16P:
2287 case AV_SAMPLE_FMT_S32P:
2288 case AV_SAMPLE_FMT_FLTP:
2289 planar_to_interleaved( dest, source, convert_samples, codec_context->channels, sizeof_sample );
2293 // Straight copy to audio buffer
2294 memcpy( dest, decode_buffer, data_size );
2296 audio_used += convert_samples;
2300 while ( *ignore && audio_used )
2303 audio_used -= audio_used > samples ? samples : audio_used;
2304 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2305 audio_used * sizeof_sample );
2310 // If we're behind, ignore this packet
2311 // Skip this on non-seekable, audio-only inputs.
2312 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2314 int64_t pts = pkt.pts;
2315 if ( self->first_pts != 0 )
2316 pts -= self->first_pts;
2317 else if ( context->start_time != AV_NOPTS_VALUE )
2318 pts -= context->start_time;
2319 double timebase = av_q2d( context->streams[ index ]->time_base );
2320 int64_t int_position = ( int64_t )( timebase * pts * fps + 0.5 );
2321 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2323 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
2324 "A pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
2325 pkt.pts, pkt.dts, req_position, self->current_position, int_position );
2327 if ( int_position > 0 )
2329 if ( int_position < req_position )
2330 // We are behind, so skip some
2331 *ignore = req_position - int_position;
2332 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2333 // We are ahead, so seek backwards some more
2334 seek_audio( self, req_position, timecode - 1.0 );
2336 // Cancel the find_first_pts() in seek_audio()
2337 if ( self->video_index == -1 && self->last_position == POSITION_INITIAL )
2338 self->last_position = int_position;
2341 self->audio_used[ index ] = audio_used;
2346 /** Get the audio from a frame.
2348 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2351 producer_avformat self = mlt_frame_pop_audio( frame );
2353 pthread_mutex_lock( &self->audio_mutex );
2355 // Obtain the frame number of this frame
2356 mlt_position position = mlt_frame_original_position( frame );
2358 // Calculate the real time code
2359 double real_timecode = producer_time_of_frame( self->parent, position );
2361 // Get the producer fps
2362 double fps = mlt_producer_get_fps( self->parent );
2364 // Number of frames to ignore (for ffwd)
2365 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2367 // Flag for paused (silence)
2368 int paused = seek_audio( self, position, real_timecode );
2370 // Initialize ignore for all streams from the seek return value
2371 int i = MAX_AUDIO_STREAMS;
2373 ignore[i] = ignore[0];
2375 // Fetch the audio_format
2376 AVFormatContext *context = self->audio_format;
2378 int sizeof_sample = sizeof( int16_t );
2380 // Determine the tracks to use
2381 int index = self->audio_index;
2382 int index_max = self->audio_index + 1;
2383 if ( self->audio_index == INT_MAX )
2386 index_max = FFMIN( MAX_AUDIO_STREAMS, context->nb_streams );
2387 *channels = self->total_channels;
2388 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2389 *frequency = FFMAX( self->max_frequency, *frequency );
2392 // Initialize the resamplers and buffers
2393 for ( ; index < index_max && index < MAX_AUDIO_STREAMS; index++ )
2395 // Get codec context
2396 AVCodecContext *codec_context = self->audio_codec[ index ];
2398 if ( codec_context && !self->audio_buffer[ index ] )
2400 #if LIBAVCODEC_VERSION_INT < ((54<<16)+(26<<8)+0)
2401 // Check for resample and create if necessary
2402 if ( codec_context->channels <= 2 )
2404 // Determine by how much resampling will increase number of samples
2405 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2406 resample_factor *= (double) *frequency / codec_context->sample_rate;
2407 if ( resample_factor > self->resample_factor )
2408 self->resample_factor = resample_factor;
2410 // Create the resampler
2411 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2412 self->audio_resample[ index ] = av_audio_resample_init(
2413 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2414 codec_context->channels, *frequency, codec_context->sample_rate,
2415 AV_SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2417 self->audio_resample[ index ] = audio_resample_init(
2418 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2419 codec_context->channels, *frequency, codec_context->sample_rate );
2425 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2426 sizeof_sample = sample_bytes( codec_context );
2429 // Check for audio buffer and create if necessary
2430 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2431 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2433 // Check for decoder buffer and create if necessary
2434 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2438 // Get the audio if required
2439 if ( !paused && *frequency > 0 )
2445 av_init_packet( &pkt );
2447 // If not resampling, give consumer more than requested.
2448 // It requested number samples based on requested frame rate.
2449 // Do not clean this up with a samples *= ...!
2450 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2451 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2453 while ( ret >= 0 && !got_audio )
2455 // Check if the buffer already contains the samples required
2456 if ( self->audio_index != INT_MAX &&
2457 self->audio_used[ self->audio_index ] >= *samples &&
2458 ignore[ self->audio_index ] == 0 )
2463 else if ( self->audio_index == INT_MAX )
2465 // Check if there is enough audio for all streams
2467 for ( index = 0; got_audio && index < index_max; index++ )
2468 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2475 pthread_mutex_lock( &self->packets_mutex );
2476 if ( mlt_deque_count( self->apackets ) )
2478 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2484 ret = av_read_frame( context, &pkt );
2485 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2487 if ( !av_dup_packet( &pkt ) )
2489 AVPacket *tmp = malloc( sizeof(AVPacket) );
2491 mlt_deque_push_back( self->vpackets, tmp );
2495 pthread_mutex_unlock( &self->packets_mutex );
2497 // We only deal with audio from the selected audio index
2498 index = pkt.stream_index;
2499 if ( index < MAX_AUDIO_STREAMS && ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2500 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2502 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2503 self->audio_codec[index]->channels : *channels;
2504 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2507 if ( self->seekable || index != self->video_index )
2508 av_free_packet( &pkt );
2512 // Set some additional return values
2513 *format = mlt_audio_s16;
2514 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2516 index = self->audio_index;
2517 *channels = self->audio_codec[ index ]->channels;
2518 *frequency = self->audio_codec[ index ]->sample_rate;
2519 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2520 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2522 else if ( self->audio_index == INT_MAX )
2524 for ( index = 0; index < index_max; index++ )
2525 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2527 // XXX: This only works if all audio tracks have the same sample format.
2528 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2529 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2534 // Allocate and set the frame's audio buffer
2535 int size = mlt_audio_format_size( *format, *samples, *channels );
2536 *buffer = mlt_pool_alloc( size );
2537 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2539 // Interleave tracks if audio_index=all
2540 if ( self->audio_index == INT_MAX )
2542 uint8_t *dest = *buffer;
2544 for ( i = 0; i < *samples; i++ )
2546 for ( index = 0; index < index_max; index++ )
2547 if ( self->audio_codec[ index ] )
2549 int current_channels = self->audio_codec[ index ]->channels;
2550 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2551 memcpy( dest, src, current_channels * sizeof_sample );
2552 dest += current_channels * sizeof_sample;
2555 for ( index = 0; index < index_max; index++ )
2556 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2558 int current_channels = self->audio_codec[ index ]->channels;
2559 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2560 self->audio_used[index] -= *samples;
2561 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2564 // Copy a single track to the output buffer
2567 index = self->audio_index;
2569 // Now handle the audio if we have enough
2570 if ( self->audio_used[ index ] > 0 )
2572 uint8_t *src = self->audio_buffer[ index ];
2573 // copy samples from audio_buffer
2574 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2575 memcpy( *buffer, src, size * *channels * sizeof_sample );
2576 // supply the remaining requested samples as silence
2577 if ( *samples > self->audio_used[ index ] )
2578 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2579 // reposition the samples within audio_buffer
2580 self->audio_used[ index ] -= size;
2581 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2585 // Otherwise fill with silence
2586 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2592 // Get silence and don't touch the context
2593 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2596 // Regardless of speed (other than paused), we expect to get the next frame
2598 self->audio_expected = position + 1;
2600 pthread_mutex_unlock( &self->audio_mutex );
2605 /** Initialize the audio codec context.
2608 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2610 // Initialise the codec if necessary
2611 if ( !self->audio_codec[ index ] )
2613 // Get codec context
2614 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2617 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2619 // If we don't have a codec and we can't initialise it, we can't do much more...
2620 pthread_mutex_lock( &self->open_mutex );
2621 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2622 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2624 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2627 // Now store the codec with its destructor
2628 if ( self->audio_codec[ index ] )
2629 avcodec_close( self->audio_codec[ index ] );
2630 self->audio_codec[ index ] = codec_context;
2634 // Remember that we can't use self later
2635 self->audio_index = -1;
2637 pthread_mutex_unlock( &self->open_mutex );
2639 // Process properties as AVOptions
2640 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2641 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
2642 if ( codec && codec->priv_class && codec_context->priv_data )
2643 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2646 return self->audio_codec[ index ] && self->audio_index > -1;
2649 /** Set up audio handling.
2652 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2655 mlt_producer producer = self->parent;
2657 // Get the properties
2658 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2660 // Fetch the audio format context
2661 AVFormatContext *context = self->audio_format;
2663 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2665 // Get the audio_index
2666 int index = mlt_properties_get_int( properties, "audio_index" );
2668 // Handle all audio tracks
2669 if ( self->audio_index > -1 &&
2670 mlt_properties_get( properties, "audio_index" ) &&
2671 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2674 // Reopen the file if necessary
2675 if ( !context && self->audio_index > -1 && index > -1 )
2677 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2678 mlt_properties_get( properties, "resource" ), 1 );
2679 context = self->audio_format;
2682 // Exception handling for audio_index
2683 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2685 for ( index = context->nb_streams - 1;
2686 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2688 mlt_properties_set_int( properties, "audio_index", index );
2690 if ( context && index > -1 && index < INT_MAX &&
2691 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2693 index = self->audio_index;
2694 mlt_properties_set_int( properties, "audio_index", index );
2696 if ( context && index > -1 && index < INT_MAX &&
2697 pick_audio_format( context->streams[ index ]->codec->sample_fmt ) == mlt_audio_none )
2702 // Update the audio properties if the index changed
2703 if ( context && index > -1 && index != self->audio_index )
2705 pthread_mutex_lock( &self->open_mutex );
2706 if ( self->audio_codec[ self->audio_index ] )
2707 avcodec_close( self->audio_codec[ self->audio_index ] );
2708 self->audio_codec[ self->audio_index ] = NULL;
2709 pthread_mutex_unlock( &self->open_mutex );
2711 if ( self->audio_index != -1 )
2712 self->audio_index = index;
2717 if ( context && index == INT_MAX )
2719 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2720 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2721 for ( index = 0; index < context->nb_streams; index++ )
2723 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2724 audio_codec_init( self, index, properties );
2727 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2729 // Set the frame properties
2730 if ( index < MAX_AUDIO_STREAMS )
2732 mlt_properties_set_int( frame_properties, "audio_frequency", self->audio_codec[ index ]->sample_rate );
2733 mlt_properties_set_int( frame_properties, "audio_channels", self->audio_codec[ index ]->channels );
2736 if ( context && index > -1 )
2738 // Add our audio operation
2739 mlt_frame_push_audio( frame, self );
2740 mlt_frame_push_audio( frame, producer_get_audio );
2744 /** Our get frame implementation.
2747 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2749 // Access the private data
2750 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2751 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2752 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2757 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2758 producer->child = self;
2759 self->parent = producer;
2760 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2761 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2764 // Create an empty frame
2765 *frame = mlt_frame_init( service);
2769 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2773 mlt_cache_item_close( cache_item );
2777 // Update timecode on the frame we're creating
2778 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2781 producer_set_up_video( self, *frame );
2784 producer_set_up_audio( self, *frame );
2786 // Set the position of this producer
2787 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2788 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "original_position", position );
2790 // Calculate the next timecode
2791 mlt_producer_prepare_next( producer );
2796 static void producer_avformat_close( producer_avformat self )
2798 mlt_log_debug( NULL, "producer_avformat_close\n" );
2800 // Cleanup av contexts
2801 av_free_packet( &self->pkt );
2802 av_free( self->av_frame );
2803 pthread_mutex_lock( &self->open_mutex );
2805 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2807 if ( self->audio_resample[i] )
2808 audio_resample_close( self->audio_resample[i] );
2809 mlt_pool_release( self->audio_buffer[i] );
2810 av_free( self->decode_buffer[i] );
2811 if ( self->audio_codec[i] )
2812 avcodec_close( self->audio_codec[i] );
2813 self->audio_codec[i] = NULL;
2815 if ( self->video_codec )
2816 avcodec_close( self->video_codec );
2817 self->video_codec = NULL;
2819 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2820 if ( self->dummy_context )
2821 avformat_close_input( &self->dummy_context );
2822 if ( self->seekable && self->audio_format )
2823 avformat_close_input( &self->audio_format );
2824 if ( self->video_format )
2825 avformat_close_input( &self->video_format );
2827 if ( self->dummy_context )
2828 av_close_input_file( self->dummy_context );
2829 if ( self->seekable && self->audio_format )
2830 av_close_input_file( self->audio_format );
2831 if ( self->video_format )
2832 av_close_input_file( self->video_format );
2834 pthread_mutex_unlock( &self->open_mutex );
2836 vdpau_producer_close( self );
2838 if ( self->image_cache )
2839 mlt_cache_close( self->image_cache );
2841 // Cleanup the mutexes
2842 if ( self->is_mutex_init )
2844 pthread_mutex_destroy( &self->audio_mutex );
2845 pthread_mutex_destroy( &self->video_mutex );
2846 pthread_mutex_destroy( &self->packets_mutex );
2847 pthread_mutex_destroy( &self->open_mutex );
2850 // Cleanup the packet queues
2852 if ( self->apackets )
2854 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2856 av_free_packet( pkt );
2859 mlt_deque_close( self->apackets );
2860 self->apackets = NULL;
2862 if ( self->vpackets )
2864 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2866 av_free_packet( pkt );
2869 mlt_deque_close( self->vpackets );
2870 self->vpackets = NULL;
2876 static void producer_close( mlt_producer parent )
2878 // Remove this instance from the cache
2879 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2882 parent->close = NULL;
2883 mlt_producer_close( parent );