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 #ifndef AVCODEC_MAX_AUDIO_FRAME_SIZE
87 #define AVCODEC_MAX_AUDIO_FRAME_SIZE 192000 // 1 second of 48khz 32bit audio
90 struct producer_avformat_s
93 AVFormatContext *dummy_context;
94 AVFormatContext *audio_format;
95 AVFormatContext *video_format;
96 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
97 AVCodecContext *video_codec;
100 mlt_position audio_expected;
101 mlt_position video_expected;
105 int64_t last_position;
107 int64_t current_position;
108 mlt_position nonseek_position;
110 uint8_t *audio_buffer[ MAX_AUDIO_STREAMS ];
111 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
112 uint8_t *decode_buffer[ MAX_AUDIO_STREAMS ];
113 int audio_used[ MAX_AUDIO_STREAMS ];
115 int audio_max_stream;
119 unsigned int invalid_pts_counter;
120 unsigned int invalid_dts_counter;
121 mlt_cache image_cache;
124 pthread_mutex_t video_mutex;
125 pthread_mutex_t audio_mutex;
128 pthread_mutex_t packets_mutex;
129 pthread_mutex_t open_mutex;
131 AVRational video_time_base;
136 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
150 typedef struct producer_avformat_s *producer_avformat;
152 // Forward references.
153 static int list_components( char* file );
154 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock );
155 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
156 static void producer_avformat_close( producer_avformat );
157 static void producer_close( mlt_producer parent );
158 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
159 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
160 static void apply_properties( void *obj, mlt_properties properties, int flags );
161 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
162 static void get_audio_streams_info( producer_avformat self );
163 static mlt_audio_format pick_audio_format( int sample_fmt );
169 /** Constructor for libavformat.
172 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
174 if ( list_components( file ) )
177 mlt_producer producer = NULL;
179 // Check that we have a non-NULL argument
182 // Construct the producer
183 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
184 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
187 if ( mlt_producer_init( producer, self ) == 0 )
189 self->parent = producer;
191 // Get the properties
192 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
194 // Set the resource property (required for all producers)
195 mlt_properties_set( properties, "resource", file );
197 // Register transport implementation with the producer
198 producer->close = (mlt_destructor) producer_close;
200 // Register our get_frame implementation
201 producer->get_frame = producer_get_frame;
203 if ( strcmp( service, "avformat-novalidate" ) )
206 if ( producer_open( self, profile, file, 1 ) != 0 )
209 mlt_producer_close( producer );
211 producer_avformat_close( self );
213 else if ( self->seekable )
215 // Close the file to release resources for large playlists - reopen later as needed
216 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
217 if ( self->audio_format )
218 avformat_close_input( &self->audio_format );
219 if ( self->video_format )
220 avformat_close_input( &self->video_format );
222 if ( self->audio_format )
223 av_close_input_file( self->audio_format );
224 if ( self->video_format )
225 av_close_input_file( self->video_format );
227 self->audio_format = NULL;
228 self->video_format = NULL;
233 // Default the user-selectable indices from the auto-detected indices
234 mlt_properties_set_int( properties, "audio_index", self->audio_index );
235 mlt_properties_set_int( properties, "video_index", self->video_index );
237 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
239 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
246 int list_components( char* file )
250 // Report information about available demuxers and codecs as YAML Tiny
251 if ( file && strstr( file, "f-list" ) )
253 fprintf( stderr, "---\nformats:\n" );
254 AVInputFormat *format = NULL;
255 while ( ( format = av_iformat_next( format ) ) )
256 fprintf( stderr, " - %s\n", format->name );
257 fprintf( stderr, "...\n" );
260 if ( file && strstr( file, "acodec-list" ) )
262 fprintf( stderr, "---\naudio_codecs:\n" );
263 AVCodec *codec = NULL;
264 while ( ( codec = av_codec_next( codec ) ) )
265 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
266 fprintf( stderr, " - %s\n", codec->name );
267 fprintf( stderr, "...\n" );
270 if ( file && strstr( file, "vcodec-list" ) )
272 fprintf( stderr, "---\nvideo_codecs:\n" );
273 AVCodec *codec = NULL;
274 while ( ( codec = av_codec_next( codec ) ) )
275 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
276 fprintf( stderr, " - %s\n", codec->name );
277 fprintf( stderr, "...\n" );
284 static int first_video_index( producer_avformat self )
286 AVFormatContext *context = self->video_format? self->video_format : self->audio_format;
287 int i = -1; // not found
290 for ( i = 0; i < context->nb_streams; i++ ) {
291 if ( context->streams[i]->codec &&
292 context->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
295 if ( i == context->nb_streams )
301 /** Find the default streams.
304 static mlt_properties find_default_streams( producer_avformat self )
308 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
309 AVDictionaryEntry *tag = NULL;
311 AVMetadataTag *tag = NULL;
313 AVFormatContext *context = self->video_format;
314 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
316 // Default to the first audio and video streams found
317 self->audio_index = -1;
318 self->video_index = -1;
320 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
322 // Allow for multiple audio and video streams in the file and select first of each (if available)
323 for( i = 0; i < context->nb_streams; i++ )
325 // Get the codec context
326 AVStream *stream = context->streams[ i ];
327 if ( ! stream ) continue;
328 AVCodecContext *codec_context = stream->codec;
329 if ( ! codec_context ) continue;
330 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
331 if ( ! codec ) continue;
333 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
335 // Determine the type and obtain the first index of each type
336 switch( codec_context->codec_type )
338 case CODEC_TYPE_VIDEO:
339 // Use first video stream
340 if ( self->video_index < 0 )
341 self->video_index = i;
342 mlt_properties_set( meta_media, key, "video" );
343 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
344 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
345 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
346 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
347 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
348 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
350 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
353 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
354 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
355 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
357 snprintf( key, sizeof(key), "meta.media.%d.codec.width", i );
358 mlt_properties_set_int( meta_media, key, codec_context->width );
359 snprintf( key, sizeof(key), "meta.media.%d.codec.height", i );
360 mlt_properties_set_int( meta_media, key, codec_context->height );
361 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
362 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
363 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
364 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
365 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(3<<8)+0)
366 mlt_properties_set( meta_media, key, av_get_pix_fmt_name( codec_context->pix_fmt ) );
368 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
370 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
371 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
372 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
373 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
374 switch ( codec_context->colorspace )
376 case AVCOL_SPC_SMPTE240M:
377 mlt_properties_set_int( meta_media, key, 240 );
379 case AVCOL_SPC_BT470BG:
380 case AVCOL_SPC_SMPTE170M:
381 mlt_properties_set_int( meta_media, key, 601 );
383 case AVCOL_SPC_BT709:
384 mlt_properties_set_int( meta_media, key, 709 );
387 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
388 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
393 case CODEC_TYPE_AUDIO:
394 if ( !codec_context->channels )
396 // Use first audio stream
397 if ( self->audio_index < 0 && pick_audio_format( codec_context->sample_fmt ) != mlt_audio_none )
398 self->audio_index = i;
400 mlt_properties_set( meta_media, key, "audio" );
401 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
402 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
403 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
404 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
405 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
406 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
408 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
409 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
410 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
411 mlt_properties_set_int( meta_media, key, codec_context->channels );
416 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
417 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
418 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
419 mlt_properties_set( meta_media, key, codec->name );
420 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
421 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
422 mlt_properties_set( meta_media, key, codec->long_name );
424 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
425 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
426 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
427 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
428 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
429 // mlt_properties_set_int( meta_media, key, codec_context->profile );
430 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
431 // mlt_properties_set_int( meta_media, key, codec_context->level );
434 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
435 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
436 while ( ( tag = av_dict_get( stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
438 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
441 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
443 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
444 mlt_properties_set( meta_media, key, tag->value );
449 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
450 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
451 while ( ( tag = av_dict_get( context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
453 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
456 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
458 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
459 mlt_properties_set( meta_media, key, tag->value );
463 if ( context->title && strcmp( context->title, "" ) )
464 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
465 if ( context->author && strcmp( context->author, "" ) )
466 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
467 if ( context->copyright && strcmp( context->copyright, "" ) )
468 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
469 if ( context->comment )
470 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
471 if ( context->album )
472 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
474 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
475 if ( context->track )
476 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
482 static inline int dv_is_pal( AVPacket *pkt )
484 return pkt->data[3] & 0x80;
487 static int dv_is_wide( AVPacket *pkt )
489 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
491 for ( ; i < pkt->size; i += 5 /* packet size */ )
493 if ( pkt->data[ i ] == 0x61 )
495 uint8_t x = pkt->data[ i + 2 ] & 0x7;
496 return ( x == 2 ) || ( x == 7 );
502 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
504 double aspect_ratio = 1.0;
506 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
510 if ( dv_is_pal( pkt ) )
512 if ( dv_is_wide( pkt ) )
514 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
515 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
519 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
520 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
525 if ( dv_is_wide( pkt ) )
527 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
528 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
532 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
533 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
540 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
541 stream->sample_aspect_ratio;
543 codec_context->sample_aspect_ratio;
545 // Override FFmpeg's notion of DV aspect ratios, which are
546 // based upon a width of 704. Since we do not have a normaliser
547 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
548 // we just coerce the values to facilitate a passive behaviour through
549 // the rescale normaliser when using equivalent producers and consumers.
550 // = display_aspect / (width * height)
551 if ( ar.num == 10 && ar.den == 11 )
554 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
555 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
557 else if ( ar.num == 59 && ar.den == 54 )
560 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
561 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
563 else if ( ar.num == 40 && ar.den == 33 )
566 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
567 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
569 else if ( ar.num == 118 && ar.den == 81 )
572 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
573 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
579 AVRational codec_sar = codec_context->sample_aspect_ratio;
580 AVRational stream_sar =
581 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
582 stream->sample_aspect_ratio;
586 if ( codec_sar.num > 0 )
588 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
589 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
591 else if ( stream_sar.num > 0 )
593 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
594 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
598 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
599 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
602 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
603 aspect_ratio = av_q2d( ar );
604 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
609 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
610 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVDictionary **params )
612 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
615 if ( !URL ) return NULL;
618 char *protocol = strdup( URL );
619 char *url = strchr( protocol, ':' );
621 // Only if there is not a protocol specification that avformat can handle
622 #if LIBAVFORMAT_VERSION_MAJOR >= 53
623 if ( url && avio_check( URL, 0 ) < 0 )
625 if ( url && !url_exist( URL ) )
628 // Truncate protocol string
630 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
633 *format = av_find_input_format( protocol );
635 // Eat the format designator
640 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
641 // support for legacy width and height parameters
645 // These are required by video4linux2 (defaults)
646 params->width = profile->width;
647 params->height = profile->height;
648 if ( !strstr( URL, "&frame_rate" ) )
649 params->time_base = (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
650 params->channels = 2;
651 params->sample_rate = 48000;
655 url = strchr( url, '?' );
659 char *name = strdup( ++url );
660 char *value = strchr( name, '=' );
662 // Also accept : as delimiter for backwards compatibility.
663 value = strchr( name, ':' );
668 char *t = strchr( value, '&' );
671 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
672 // translate old parameters to new av_dict names
673 if ( !strcmp( name, "frame_rate" ) )
674 av_dict_set( params, "framerate", value, 0 );
675 else if ( !strcmp( name, "pix_fmt" ) )
676 av_dict_set( params, "pixel_format", value, 0 );
677 else if ( !strcmp( name, "width" ) )
678 width = strdup( value );
679 else if ( !strcmp( name, "height" ) )
680 height = strdup( value );
682 // generic demux/device option support
683 av_dict_set( params, name, value, 0 );
685 if ( !strcmp( name, "frame_rate" ) )
686 params->time_base.den = atoi( value );
687 else if ( !strcmp( name, "frame_rate_base" ) )
688 params->time_base.num = atoi( value );
689 else if ( !strcmp( name, "sample_rate" ) )
690 params->sample_rate = atoi( value );
691 else if ( !strcmp( name, "channel" ) )
692 params->channel = atoi( value );
693 else if ( !strcmp( name, "channels" ) )
694 params->channels = atoi( value );
695 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
696 else if ( !strcmp( name, "pix_fmt" ) )
697 params->pix_fmt = av_get_pix_fmt( value );
699 else if ( !strcmp( name, "width" ) )
700 params->width = atoi( value );
701 else if ( !strcmp( name, "height" ) )
702 params->height = atoi( value );
703 else if ( !strcmp( name, "standard" ) )
704 params->standard = strdup( value );
708 url = strchr( url, '&' );
710 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
711 // continued support for legacy width and height parameters
712 if ( width && height )
714 char *s = malloc( strlen( width ) + strlen( height ) + 2 );
718 av_dict_set( params, "video_size", s, 0 );
721 if ( width ) free( width );
722 if ( height ) free ( height );
725 result = strdup( result );
729 result = strdup( URL );
735 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
739 // Get the properties
740 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
742 AVFormatContext *format = self->video_format;
744 // We will treat everything with the producer fps.
745 // TODO: make this more flexible.
746 double fps = mlt_profile_fps( profile );
749 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
751 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
752 // when producer_open is called after initial call when restoring or reseting the producer.
753 if ( format->duration != AV_NOPTS_VALUE )
755 // This isn't going to be accurate for all formats
756 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
757 mlt_properties_set_position( properties, "out", frames - 1 );
758 mlt_properties_set_position( properties, "length", frames );
759 mlt_properties_set_int( properties, "_length_computed", 1 );
763 // Set live sources to run forever
764 mlt_properties_set_position( properties, "length", INT_MAX );
765 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
766 mlt_properties_set( properties, "eof", "loop" );
767 mlt_properties_set_int( properties, "_length_computed", 1 );
771 // Check if we're seekable
772 // avdevices are typically AVFMT_NOFILE and not seekable
773 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
776 // protocols can indicate if they support seeking
777 #if LIBAVFORMAT_VERSION_MAJOR >= 53
778 self->seekable = format->pb->seekable;
780 URLContext *uc = url_fileno( format->pb );
782 self->seekable = !uc->is_streamed;
785 if ( self->seekable )
787 // Do a more rigourous test of seekable on a disposable context
788 self->seekable = av_seek_frame( format, -1, format->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
789 mlt_properties_set_int( properties, "seekable", self->seekable );
790 self->dummy_context = format;
791 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
792 self->video_format = NULL;
793 avformat_open_input( &self->video_format, filename, NULL, NULL );
794 avformat_find_stream_info( self->video_format, NULL );
796 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
797 av_find_stream_info( self->video_format );
799 format = self->video_format;
802 // Fetch the width, height and aspect ratio
803 if ( self->video_index != -1 )
805 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
806 mlt_properties_set_int( properties, "width", codec_context->width );
807 mlt_properties_set_int( properties, "height", codec_context->height );
809 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
811 // Fetch the first frame of DV so we can read it directly
816 ret = av_read_frame( format, &pkt );
817 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
819 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
820 av_free_packet(&pkt);
824 av_free_packet(&pkt);
829 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
833 // Verify that we can convert this to YUV 4:2:2
834 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
835 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
836 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
838 sws_freeContext( context );
849 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
851 // Return an error code (0 == no error)
853 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
858 if ( !self->is_mutex_init )
860 pthread_mutex_init( &self->audio_mutex, NULL );
861 pthread_mutex_init( &self->video_mutex, NULL );
862 pthread_mutex_init( &self->packets_mutex, NULL );
863 pthread_mutex_init( &self->open_mutex, NULL );
864 self->is_mutex_init = 1;
866 pthread_mutex_lock( &self->audio_mutex );
867 pthread_mutex_lock( &self->video_mutex );
869 mlt_events_block( properties, self->parent );
872 AVInputFormat *format = NULL;
873 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
874 AVDictionary *params = NULL;
876 AVFormatParameters params;
877 memset( ¶ms, 0, sizeof(params) );
879 char *filename = parse_url( profile, URL, &format, ¶ms );
881 // Now attempt to open the file or device with filename
882 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
883 error = avformat_open_input( &self->video_format, filename, format, ¶ms ) < 0;
885 // If the URL is a network stream URL, then we probably need to open with full URL
886 error = avformat_open_input( &self->video_format, URL, format, ¶ms ) < 0;
888 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
890 // If the URL is a network stream URL, then we probably need to open with full URL
891 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
894 // Set MLT properties onto video AVFormatContext
895 if ( !error && self->video_format )
897 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
898 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
899 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
900 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
904 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
905 av_dict_free( ¶ms );
907 // Cleanup AVFormatParameters
908 if ( params.standard )
909 free( (void*) params.standard );
912 // If successful, then try to get additional info
913 if ( !error && self->video_format )
915 // Get the stream info
916 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
917 error = avformat_find_stream_info( self->video_format, NULL ) < 0;
919 error = av_find_stream_info( self->video_format ) < 0;
922 // Continue if no error
923 if ( !error && self->video_format )
925 // Find default audio and video streams
926 find_default_streams( self );
927 error = get_basic_info( self, profile, filename );
929 // Initialize position info
930 self->first_pts = AV_NOPTS_VALUE;
931 self->last_position = POSITION_INITIAL;
933 if ( !self->audio_format )
935 // We're going to cheat here - for seekable A/V files, we will have separate contexts
936 // to support independent seeking of audio from video.
937 // TODO: Is this really necessary?
938 if ( self->audio_index != -1 && self->video_index != -1 )
940 if ( self->seekable )
942 // And open again for our audio context
943 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
944 avformat_open_input( &self->audio_format, filename, NULL, NULL );
945 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
946 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
947 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
948 avformat_find_stream_info( self->audio_format, NULL );
950 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
951 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
952 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
953 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
954 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
956 av_find_stream_info( self->audio_format );
961 self->audio_format = self->video_format;
964 else if ( self->audio_index != -1 )
966 // We only have an audio context
967 self->audio_format = self->video_format;
968 self->video_format = NULL;
970 else if ( self->video_index == -1 )
972 // Something has gone wrong
975 if ( self->audio_format && !self->audio_streams )
976 get_audio_streams_info( self );
984 self->apackets = mlt_deque_init();
985 self->vpackets = mlt_deque_init();
988 if ( self->dummy_context )
990 pthread_mutex_lock( &self->open_mutex );
991 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
992 avformat_close_input( &self->dummy_context );
994 av_close_input_file( self->dummy_context );
996 self->dummy_context = NULL;
997 pthread_mutex_unlock( &self->open_mutex );
1000 // Unlock the service
1003 pthread_mutex_unlock( &self->audio_mutex );
1004 pthread_mutex_unlock( &self->video_mutex );
1006 mlt_events_unblock( properties, self->parent );
1011 static void reopen_video( producer_avformat self, mlt_producer producer )
1013 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1014 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1015 pthread_mutex_lock( &self->audio_mutex );
1016 pthread_mutex_lock( &self->open_mutex );
1018 if ( self->video_codec )
1019 avcodec_close( self->video_codec );
1020 self->video_codec = NULL;
1021 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
1022 if ( self->dummy_context )
1023 avformat_close_input( &self->dummy_context );
1024 if ( self->video_format )
1025 avformat_close_input( &self->video_format );
1027 if ( self->dummy_context )
1028 av_close_input_file( self->dummy_context );
1029 if ( self->video_format )
1030 av_close_input_file( self->video_format );
1032 self->dummy_context = NULL;
1033 self->video_format = NULL;
1034 pthread_mutex_unlock( &self->open_mutex );
1036 int audio_index = self->audio_index;
1037 int video_index = self->video_index;
1039 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1040 mlt_properties_get( properties, "resource" ), 0 );
1042 self->audio_index = audio_index;
1043 if ( self->video_format && video_index > -1 )
1045 self->video_index = video_index;
1046 video_codec_init( self, video_index, properties );
1049 pthread_mutex_unlock( &self->audio_mutex );
1050 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1053 static int64_t best_pts( producer_avformat self, int64_t pts, int64_t dts )
1055 self->invalid_pts_counter += pts == AV_NOPTS_VALUE;
1056 self->invalid_dts_counter += dts == AV_NOPTS_VALUE;
1057 if ( ( self->invalid_pts_counter <= self->invalid_dts_counter
1058 || dts == AV_NOPTS_VALUE ) && pts != AV_NOPTS_VALUE )
1064 static void find_first_pts( producer_avformat self, int video_index )
1067 AVFormatContext *context = self->video_format? self->video_format : self->audio_format;
1072 while ( ret >= 0 && toscan-- > 0 )
1074 ret = av_read_frame( context, &pkt );
1075 if ( ret >= 0 && pkt.stream_index == video_index && ( pkt.flags & PKT_FLAG_KEY ) )
1077 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
1078 "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n",
1079 pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
1080 self->first_pts = best_pts( self, pkt.pts, pkt.dts );
1081 if ( self->first_pts != AV_NOPTS_VALUE )
1084 av_free_packet( &pkt );
1086 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1089 static int seek_video( producer_avformat self, mlt_position position,
1090 int64_t req_position, int preseek )
1092 mlt_producer producer = self->parent;
1095 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
1097 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1099 // Fetch the video format context
1100 AVFormatContext *context = self->video_format;
1102 // Get the video stream
1103 AVStream *stream = context->streams[ self->video_index ];
1105 // Get codec context
1106 AVCodecContext *codec_context = stream->codec;
1108 // We may want to use the source fps if available
1109 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1110 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1112 if ( self->last_position == POSITION_INITIAL )
1113 find_first_pts( self, self->video_index );
1115 if ( self->av_frame && position + 1 == self->video_expected )
1117 // We're paused - use last image
1120 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
1122 // Calculate the timestamp for the requested frame
1123 int64_t timestamp = req_position / ( av_q2d( self->video_time_base ) * source_fps );
1124 if ( req_position <= 0 )
1126 else if ( self->first_pts != AV_NOPTS_VALUE )
1127 timestamp += self->first_pts;
1128 else if ( context->start_time != AV_NOPTS_VALUE )
1129 timestamp += context->start_time;
1130 if ( preseek && av_q2d( self->video_time_base ) != 0 )
1131 timestamp -= 2 / av_q2d( self->video_time_base );
1132 if ( timestamp < 0 )
1134 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
1135 timestamp, position, self->video_expected, self->last_position );
1137 // Seek to the timestamp
1138 // NOTE: reopen_video is disabled at this time because it is causing trouble with A/V sync.
1139 if ( 1 || req_position > 0 || self->last_position <= 0 )
1141 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1142 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1144 // flush any pictures still in decode buffer
1145 avcodec_flush_buffers( codec_context );
1149 // Re-open video stream when rewinding to beginning from somewhere else.
1150 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1151 // not reliably seeking to the first frame across formats.
1152 reopen_video( self, producer );
1155 // Remove the cached info relating to the previous position
1156 self->current_position = POSITION_INVALID;
1157 self->last_position = POSITION_INVALID;
1158 av_freep( &self->av_frame );
1164 /** Convert a frame position to a time code.
1167 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1169 return ( double )position / mlt_producer_get_fps( producer );
1172 // Collect information about all audio streams
1174 static void get_audio_streams_info( producer_avformat self )
1176 // Fetch the audio format context
1177 AVFormatContext *context = self->audio_format;
1181 i < context->nb_streams;
1184 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1186 AVCodecContext *codec_context = context->streams[i]->codec;
1187 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1189 // If we don't have a codec and we can't initialise it, we can't do much more...
1190 pthread_mutex_lock( &self->open_mutex );
1191 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1192 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1194 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1197 self->audio_streams++;
1198 self->audio_max_stream = i;
1199 self->total_channels += codec_context->channels;
1200 if ( codec_context->channels > self->max_channel )
1201 self->max_channel = codec_context->channels;
1202 if ( codec_context->sample_rate > self->max_frequency )
1203 self->max_frequency = codec_context->sample_rate;
1204 avcodec_close( codec_context );
1206 pthread_mutex_unlock( &self->open_mutex );
1209 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1210 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
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 )
1430 if ( *format == mlt_image_glsl )
1431 *format = pick_pix_format( codec_context->pix_fmt );
1433 *width = codec_context->width;
1434 *height = codec_context->height;
1435 size = mlt_image_format_size( *format, *width, *height, NULL );
1436 *buffer = mlt_pool_alloc( size );
1438 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1445 /** Get an image from a frame.
1448 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1451 producer_avformat self = mlt_frame_pop_service( frame );
1452 mlt_producer producer = self->parent;
1454 // Get the properties from the frame
1455 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1457 // Obtain the frame number of this frame
1458 mlt_position position = mlt_frame_original_position( frame );
1460 // Get the producer properties
1461 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1463 pthread_mutex_lock( &self->video_mutex );
1465 // Fetch the video format context
1466 AVFormatContext *context = self->video_format;
1468 // Get the video stream
1469 AVStream *stream = context->streams[ self->video_index ];
1471 // Get codec context
1472 AVCodecContext *codec_context = stream->codec;
1474 uint8_t *alpha = NULL;
1475 int got_picture = 0;
1478 // Get the image cache
1479 if ( ! self->image_cache )
1481 // if cache size supplied by environment variable
1482 int cache_supplied = getenv( "MLT_AVFORMAT_CACHE" ) != NULL;
1483 int cache_size = cache_supplied? atoi( getenv( "MLT_AVFORMAT_CACHE" ) ) : 0;
1485 // cache size supplied via property
1486 if ( mlt_properties_get( properties, "cache" ) )
1489 cache_size = mlt_properties_get_int( properties, "cache" );
1491 if ( mlt_properties_get_int( properties, "noimagecache" ) )
1493 // create cache if not disabled
1494 if ( !cache_supplied || cache_size > 0 )
1495 self->image_cache = mlt_cache_init();
1496 // set cache size if supplied
1497 if ( self->image_cache && cache_supplied )
1498 mlt_cache_set_size( self->image_cache, cache_size );
1500 if ( self->image_cache )
1502 mlt_frame original = mlt_cache_get_frame( self->image_cache, position );
1505 mlt_properties orig_props = MLT_FRAME_PROPERTIES( original );
1508 *buffer = mlt_properties_get_data( orig_props, "alpha", &size );
1510 mlt_frame_set_alpha( frame, *buffer, size, NULL );
1511 *buffer = mlt_properties_get_data( orig_props, "image", &size );
1512 mlt_frame_set_image( frame, *buffer, size, NULL );
1513 mlt_properties_set_data( frame_properties, "avformat.image_cache", original, 0, (mlt_destructor) mlt_frame_close, NULL );
1514 *format = mlt_properties_get_int( orig_props, "format" );
1516 // Set the resolution
1517 *width = codec_context->width;
1518 *height = codec_context->height;
1520 // Workaround 1088 encodings missing cropping info.
1521 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1525 goto exit_get_image;
1530 // We may want to use the source fps if available
1531 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1532 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1534 // This is the physical frame position in the source
1535 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1537 // Determines if we have to decode all frames in a sequence
1538 // Temporary hack to improve intra frame only
1539 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1540 strcmp( codec_context->codec->name, "dnxhd" ) &&
1541 strcmp( codec_context->codec->name, "dvvideo" ) &&
1542 strcmp( codec_context->codec->name, "huffyuv" ) &&
1543 strcmp( codec_context->codec->name, "mjpeg" ) &&
1544 strcmp( codec_context->codec->name, "rawvideo" ) );
1546 double delay = mlt_properties_get_double( properties, "video_delay" );
1548 // Seek if necessary
1549 const char *interp = mlt_properties_get( frame_properties, "rescale.interp" );
1550 int preseek = must_decode
1551 #if defined(FFUDIV) && LIBAVFORMAT_VERSION_INT >= ((53<<16)+(24<<8)+2)
1552 && ( interp && strcmp( interp, "nearest" ) )
1554 && codec_context->has_b_frames;
1555 int paused = seek_video( self, position, req_position, preseek );
1557 // Seek might have reopened the file
1558 context = self->video_format;
1559 stream = context->streams[ self->video_index ];
1560 codec_context = stream->codec;
1561 if ( *format == mlt_image_none ||
1562 codec_context->pix_fmt == PIX_FMT_ARGB ||
1563 codec_context->pix_fmt == PIX_FMT_RGBA ||
1564 codec_context->pix_fmt == PIX_FMT_ABGR ||
1565 codec_context->pix_fmt == PIX_FMT_BGRA )
1566 *format = pick_pix_format( codec_context->pix_fmt );
1568 // Duplicate the last image if necessary
1569 if ( self->av_frame && self->av_frame->linesize[0]
1570 && ( paused || self->current_position >= req_position ) )
1573 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1575 // Workaround 1088 encodings missing cropping info.
1576 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1579 if ( self->vdpau && self->vdpau->buffer )
1582 picture.data[0] = self->vdpau->buffer;
1583 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1584 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1585 picture.linesize[0] = codec_context->width;
1586 picture.linesize[1] = codec_context->width / 2;
1587 picture.linesize[2] = codec_context->width / 2;
1588 convert_image( self, (AVFrame*) &picture, *buffer,
1589 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1593 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1594 format, *width, *height, &alpha );
1601 int64_t int_position = 0;
1602 int decode_errors = 0;
1604 // Construct an AVFrame for YUV422 conversion
1605 if ( !self->av_frame )
1606 self->av_frame = avcodec_alloc_frame( );
1608 while( ret >= 0 && !got_picture )
1611 if ( self->pkt.stream_index == self->video_index )
1612 av_free_packet( &self->pkt );
1613 av_init_packet( &self->pkt );
1614 pthread_mutex_lock( &self->packets_mutex );
1615 if ( mlt_deque_count( self->vpackets ) )
1617 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1623 ret = av_read_frame( context, &self->pkt );
1624 if ( ret >= 0 && !self->seekable && self->pkt.stream_index == self->audio_index )
1626 if ( !av_dup_packet( &self->pkt ) )
1628 AVPacket *tmp = malloc( sizeof(AVPacket) );
1630 mlt_deque_push_back( self->apackets, tmp );
1634 pthread_mutex_unlock( &self->packets_mutex );
1636 // We only deal with video from the selected video_index
1637 if ( ret >= 0 && self->pkt.stream_index == self->video_index && self->pkt.size > 0 )
1639 int64_t pts = best_pts( self, self->pkt.pts, self->pkt.dts );
1640 if ( pts != AV_NOPTS_VALUE )
1642 if ( !self->seekable && self->first_pts == AV_NOPTS_VALUE )
1643 self->first_pts = pts;
1644 if ( self->first_pts != AV_NOPTS_VALUE )
1645 pts -= self->first_pts;
1646 else if ( context->start_time != AV_NOPTS_VALUE )
1647 pts -= context->start_time;
1648 int_position = ( int64_t )( ( av_q2d( self->video_time_base ) * pts + delay ) * source_fps + 0.5 );
1649 if ( int_position == self->last_position )
1650 int_position = self->last_position + 1;
1652 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1653 "V pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1654 self->pkt.pts, self->pkt.dts, req_position, self->current_position, int_position );
1656 // Make a dumb assumption on streams that contain wild timestamps
1657 if ( abs( req_position - int_position ) > 999 )
1659 int_position = req_position;
1660 mlt_log_warning( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!\n" );
1662 self->last_position = int_position;
1665 if ( must_decode || int_position >= req_position )
1670 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1672 vdpau_decoder_init( self );
1674 self->vdpau->is_decoded = 0;
1677 codec_context->reordered_opaque = int_position;
1678 if ( int_position >= req_position )
1679 codec_context->skip_loop_filter = AVDISCARD_NONE;
1680 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1681 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &self->pkt );
1683 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, self->pkt.data, self->pkt.size );
1685 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1688 if ( ++decode_errors <= 10 )
1699 // Get position of reordered frame
1700 int_position = self->av_frame->reordered_opaque;
1701 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(106<<8)+0))
1702 pts = best_pts( self, self->av_frame->pkt_pts, self->av_frame->pkt_dts );
1703 if ( pts != AV_NOPTS_VALUE )
1705 if ( self->first_pts != AV_NOPTS_VALUE )
1706 pts -= self->first_pts;
1707 else if ( context->start_time != AV_NOPTS_VALUE )
1708 pts -= context->start_time;
1709 int_position = ( int64_t )( ( av_q2d( self->video_time_base ) * pts + delay ) * source_fps + 0.5 );
1713 if ( int_position < req_position )
1715 else if ( int_position >= req_position )
1716 codec_context->skip_loop_filter = AVDISCARD_NONE;
1718 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, self->pkt.flags & PKT_FLAG_KEY );
1721 // Now handle the picture if we have one
1724 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1726 // Workaround 1088 encodings missing cropping info.
1727 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1732 if ( self->vdpau->is_decoded )
1734 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1736 uint32_t pitches[3];
1737 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1739 if ( !self->vdpau->buffer )
1740 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1741 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1742 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1743 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1744 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1745 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1746 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1748 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1749 if ( status == VDP_STATUS_OK )
1751 convert_image( self, self->av_frame, *buffer, PIX_FMT_YUV420P,
1752 format, *width, *height, &alpha );
1756 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1757 image_size = self->vdpau->is_decoded = 0;
1762 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1763 image_size = got_picture = 0;
1768 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1769 format, *width, *height, &alpha );
1770 self->top_field_first |= self->av_frame->top_field_first;
1771 self->current_position = int_position;
1779 // Free packet data if not video and not live audio packet
1780 if ( self->pkt.stream_index != self->video_index &&
1781 !( !self->seekable && self->pkt.stream_index == self->audio_index ) )
1782 av_free_packet( &self->pkt );
1788 mlt_frame_set_alpha( frame, alpha, (*width) * (*height), mlt_pool_release );
1790 if ( image_size > 0 && self->image_cache )
1792 mlt_properties_set_int( frame_properties, "format", *format );
1793 mlt_cache_put_frame( self->image_cache, frame );
1796 // Try to duplicate last image if there was a decoding failure
1797 // TODO: with multithread decoding a partial frame decoding resulting
1798 // in failure also resets av_frame making test below fail.
1799 if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1802 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1804 // Workaround 1088 encodings missing cropping info.
1805 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1808 if ( self->vdpau && self->vdpau->buffer )
1811 picture.data[0] = self->vdpau->buffer;
1812 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1813 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1814 picture.linesize[0] = codec_context->width;
1815 picture.linesize[1] = codec_context->width / 2;
1816 picture.linesize[2] = codec_context->width / 2;
1817 convert_image( self, (AVFrame*) &picture, *buffer,
1818 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1822 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1823 format, *width, *height, &alpha );
1828 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1829 self->video_expected = position + 1;
1833 pthread_mutex_unlock( &self->video_mutex );
1835 // Set the progressive flag
1836 if ( mlt_properties_get( properties, "force_progressive" ) )
1837 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1838 else if ( self->av_frame )
1839 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1841 // Set the field order property for this frame
1842 if ( mlt_properties_get( properties, "force_tff" ) )
1843 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1845 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1847 // Set immutable properties of the selected track's (or overridden) source attributes.
1848 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1849 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1850 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1851 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1853 // If we already have RGB, then the full range processing either happened already
1854 // or does not apply (RGB source).
1855 if ( *format == mlt_image_rgb24 || *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1856 mlt_properties_set( frame_properties, "force_full_luma", NULL );
1858 return !got_picture;
1861 /** Process properties as AVOptions and apply to AV context obj
1864 static void apply_properties( void *obj, mlt_properties properties, int flags )
1867 int count = mlt_properties_count( properties );
1868 for ( i = 0; i < count; i++ )
1870 const char *opt_name = mlt_properties_get_name( properties, i );
1871 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
1872 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1874 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1876 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1879 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1880 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1881 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1882 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1883 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1884 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1886 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1892 /** Initialize the video codec context.
1895 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1897 // Initialise the codec if necessary
1898 if ( !self->video_codec )
1900 // Get the video stream
1901 AVStream *stream = self->video_format->streams[ index ];
1903 // Get codec context
1904 AVCodecContext *codec_context = stream->codec;
1907 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1909 if ( codec_context->codec_id == CODEC_ID_H264 )
1911 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1913 if ( vdpau_init( self ) )
1915 self->video_codec = codec_context;
1916 if ( !vdpau_decoder_init( self ) )
1921 codec = avcodec_find_decoder( codec_context->codec_id );
1925 // Initialise multi-threading
1926 int thread_count = mlt_properties_get_int( properties, "threads" );
1927 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1928 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1929 if ( thread_count > 1 )
1930 codec_context->thread_count = thread_count;
1932 // If we don't have a codec and we can't initialise it, we can't do much more...
1933 pthread_mutex_lock( &self->open_mutex );
1934 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1935 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1937 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1940 // Now store the codec with its destructor
1941 self->video_codec = codec_context;
1945 // Remember that we can't use this later
1946 self->video_index = -1;
1947 pthread_mutex_unlock( &self->open_mutex );
1950 pthread_mutex_unlock( &self->open_mutex );
1952 // Process properties as AVOptions
1953 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1954 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1955 if ( codec->priv_class && codec_context->priv_data )
1956 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1959 // Reset some image properties
1960 if ( self->video_codec )
1962 mlt_properties_set_int( properties, "width", self->video_codec->width );
1963 mlt_properties_set_int( properties, "height", self->video_codec->height );
1965 // For DV, we'll just use the saved aspect ratio
1966 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1967 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1969 // Determine the fps first from the codec
1970 double source_fps = (double) self->video_codec->time_base.den /
1971 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1974 // If the muxer reports a frame rate different than the codec
1975 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1976 double muxer_fps = av_q2d( stream->avg_frame_rate );
1977 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1978 muxer_fps = av_q2d( stream->r_frame_rate );
1980 double muxer_fps = av_q2d( stream->r_frame_rate );
1982 // Choose the lesser - the wrong tends to be off by some multiple of 10
1983 source_fps = FFMIN( source_fps, muxer_fps );
1984 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1986 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1987 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1989 else if ( muxer_fps > 0 )
1991 AVRational frame_rate = stream->r_frame_rate;
1992 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1993 // avg_frame_rate gives some approximate value that does not well match the media.
1994 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1995 // results in some very choppy output, but some value slightly different works
1997 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1998 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1999 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
2001 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
2002 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
2006 source_fps = mlt_producer_get_fps( self->parent );
2007 AVRational frame_rate = av_d2q( source_fps, 255 );
2008 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
2009 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
2012 self->video_time_base = stream->time_base;
2013 if ( mlt_properties_get( properties, "force_fps" ) )
2015 double source_fps = mlt_properties_get_double( properties, "force_fps" );
2016 AVRational fps = av_d2q( source_fps, 1024 );
2017 self->video_time_base.num *= mlt_properties_get_int( properties, "meta.media.frame_rate_num" ) * fps.den;
2018 self->video_time_base.den *= mlt_properties_get_int( properties, "meta.media.frame_rate_den" ) * fps.num;
2019 mlt_properties_set_int( properties, "meta.media.frame_rate_num", fps.num );
2020 mlt_properties_set_int( properties, "meta.media.frame_rate_den", fps.den );
2023 // Set the YUV colorspace from override or detect
2024 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
2025 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
2026 if ( ! self->colorspace )
2028 switch ( self->video_codec->colorspace )
2030 case AVCOL_SPC_SMPTE240M:
2031 self->colorspace = 240;
2033 case AVCOL_SPC_BT470BG:
2034 case AVCOL_SPC_SMPTE170M:
2035 self->colorspace = 601;
2037 case AVCOL_SPC_BT709:
2038 self->colorspace = 709;
2041 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
2042 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
2047 // Let apps get chosen colorspace
2048 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
2050 self->full_luma = -1;
2051 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(72<<8)+2)
2052 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent), "color_range %d\n", codec_context->color_range );
2053 if ( codec_context->color_range == AVCOL_RANGE_JPEG )
2054 self->full_luma = 1;
2056 if ( mlt_properties_get( properties, "set.force_full_luma" ) )
2057 self->full_luma = mlt_properties_get_int( properties, "set.force_full_luma" );
2059 return self->video_codec && self->video_index > -1;
2062 /** Set up video handling.
2065 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
2068 mlt_producer producer = self->parent;
2070 // Get the properties
2071 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2073 // Fetch the video format context
2074 AVFormatContext *context = self->video_format;
2076 // Get the video_index
2077 int index = mlt_properties_get_int( properties, "video_index" );
2079 // Reopen the file if necessary
2080 if ( !context && index > -1 )
2082 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2083 mlt_properties_get( properties, "resource" ), 1 );
2084 context = self->video_format;
2087 // Exception handling for video_index
2088 if ( context && index >= (int) context->nb_streams )
2090 // Get the last video stream
2091 for ( index = context->nb_streams - 1;
2092 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
2094 mlt_properties_set_int( properties, "video_index", index );
2096 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
2098 // Invalidate the video stream
2100 mlt_properties_set_int( properties, "video_index", index );
2103 // Update the video properties if the index changed
2104 if ( index != self->video_index )
2106 // Reset the video properties if the index changed
2107 self->video_index = index;
2108 pthread_mutex_lock( &self->open_mutex );
2109 if ( self->video_codec )
2110 avcodec_close( self->video_codec );
2111 self->video_codec = NULL;
2112 pthread_mutex_unlock( &self->open_mutex );
2115 // Get the frame properties
2116 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2119 if ( context && index > -1 && video_codec_init( self, index, properties ) )
2121 // Set the frame properties
2122 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
2123 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
2124 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
2126 // Set the width and height
2127 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
2128 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
2129 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
2130 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
2131 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
2132 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
2134 // Workaround 1088 encodings missing cropping info.
2135 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
2137 mlt_properties_set_int( properties, "meta.media.height", 1080 );
2140 // Add our image operation
2141 mlt_frame_push_service( frame, self );
2142 mlt_frame_push_get_image( frame, producer_get_image );
2146 // If something failed, use test card image
2147 mlt_properties_set_int( frame_properties, "test_image", 1 );
2151 static int seek_audio( producer_avformat self, mlt_position position, double timecode )
2155 // Seek if necessary
2156 if ( self->seekable && ( position != self->audio_expected || self->last_position < 0 ) )
2158 if ( self->last_position == POSITION_INITIAL )
2160 int video_index = self->video_index;
2161 if ( video_index == -1 )
2162 video_index = first_video_index( self );
2163 if ( video_index >= 0 )
2164 find_first_pts( self, video_index );
2167 if ( position + 1 == self->audio_expected )
2169 // We're paused - silence required
2172 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
2174 AVFormatContext *context = self->audio_format;
2175 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
2176 if ( context->start_time != AV_NOPTS_VALUE )
2177 timestamp += context->start_time;
2178 if ( timestamp < 0 )
2181 // Set to the real timecode
2182 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
2185 // Clear the usage in the audio buffer
2186 int i = MAX_AUDIO_STREAMS + 1;
2188 self->audio_used[i - 1] = 0;
2194 static int sample_bytes( AVCodecContext *context )
2196 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2197 return av_get_bytes_per_sample( context->sample_fmt );
2198 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2199 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2201 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2205 static void planar_to_interleaved( uint8_t *dest, uint8_t *src, int samples, int channels, int bytes_per_sample )
2208 for ( s = 0; s < samples; s++ )
2210 for ( c = 0; c < channels; c++ )
2212 memcpy( dest, src + ( c * samples + s ) * bytes_per_sample, bytes_per_sample );
2213 dest += bytes_per_sample;
2218 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2220 // Fetch the audio_format
2221 AVFormatContext *context = self->audio_format;
2223 // Get the current stream index
2224 int index = pkt.stream_index;
2226 // Get codec context
2227 AVCodecContext *codec_context = self->audio_codec[ index ];
2229 // Obtain the audio buffers
2230 uint8_t *audio_buffer = self->audio_buffer[ index ];
2231 uint8_t *decode_buffer = self->decode_buffer[ index ];
2233 int audio_used = self->audio_used[ index ];
2234 uint8_t *ptr = pkt.data;
2238 while ( ptr && ret >= 0 && len > 0 )
2240 int sizeof_sample = sample_bytes( codec_context );
2241 int data_size = self->audio_buffer_size[ index ];
2244 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2245 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2246 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2247 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2249 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2253 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2257 pkt.size = len -= ret;
2258 pkt.data = ptr += ret;
2260 // If decoded successfully
2261 if ( data_size > 0 )
2263 // Figure out how many samples will be needed after resampling
2264 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2266 // Resize audio buffer to prevent overflow
2267 if ( ( audio_used + convert_samples ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2269 self->audio_buffer_size[ index ] = ( audio_used + convert_samples * 2 ) * channels * sizeof_sample;
2270 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2272 uint8_t *source = decode_buffer;
2273 uint8_t *dest = &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ];
2274 switch ( codec_context->sample_fmt )
2276 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2277 case AV_SAMPLE_FMT_U8P:
2278 case AV_SAMPLE_FMT_S16P:
2279 case AV_SAMPLE_FMT_S32P:
2280 case AV_SAMPLE_FMT_FLTP:
2281 planar_to_interleaved( dest, source, convert_samples, codec_context->channels, sizeof_sample );
2285 // Straight copy to audio buffer
2286 memcpy( dest, decode_buffer, data_size );
2288 audio_used += convert_samples;
2291 while ( *ignore && audio_used )
2294 audio_used -= audio_used > samples ? samples : audio_used;
2295 memmove( audio_buffer, &audio_buffer[ samples * codec_context->channels * sizeof_sample ],
2296 audio_used * sizeof_sample );
2301 // If we're behind, ignore this packet
2302 // Skip this on non-seekable, audio-only inputs.
2303 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2305 int64_t pts = pkt.pts;
2306 if ( self->first_pts != AV_NOPTS_VALUE )
2307 pts -= self->first_pts;
2308 else if ( context->start_time != AV_NOPTS_VALUE )
2309 pts -= context->start_time;
2310 double timebase = av_q2d( context->streams[ index ]->time_base );
2311 int64_t int_position = ( int64_t )( timebase * pts * fps + 0.5 );
2312 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2314 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
2315 "A pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
2316 pkt.pts, pkt.dts, req_position, self->current_position, int_position );
2318 if ( int_position > 0 )
2320 if ( int_position < req_position )
2321 // We are behind, so skip some
2322 *ignore = req_position - int_position;
2323 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2324 // We are ahead, so seek backwards some more
2325 seek_audio( self, req_position, timecode - 1.0 );
2327 // Cancel the find_first_pts() in seek_audio()
2328 if ( self->video_index == -1 && self->last_position == POSITION_INITIAL )
2329 self->last_position = int_position;
2332 self->audio_used[ index ] = audio_used;
2337 /** Get the audio from a frame.
2339 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2342 producer_avformat self = mlt_frame_pop_audio( frame );
2344 pthread_mutex_lock( &self->audio_mutex );
2346 // Obtain the frame number of this frame
2347 mlt_position position = mlt_frame_original_position( frame );
2349 // Calculate the real time code
2350 double real_timecode = producer_time_of_frame( self->parent, position );
2352 // Get the producer fps
2353 double fps = mlt_producer_get_fps( self->parent );
2355 // Number of frames to ignore (for ffwd)
2356 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2358 // Flag for paused (silence)
2359 int paused = seek_audio( self, position, real_timecode );
2361 // Initialize ignore for all streams from the seek return value
2362 int i = MAX_AUDIO_STREAMS;
2364 ignore[i] = ignore[0];
2366 // Fetch the audio_format
2367 AVFormatContext *context = self->audio_format;
2369 int sizeof_sample = sizeof( int16_t );
2371 // Determine the tracks to use
2372 int index = self->audio_index;
2373 int index_max = self->audio_index + 1;
2374 if ( self->audio_index == INT_MAX )
2377 index_max = FFMIN( MAX_AUDIO_STREAMS, context->nb_streams );
2378 *channels = self->total_channels;
2379 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2380 *frequency = FFMAX( self->max_frequency, *frequency );
2383 // Initialize the buffers
2384 for ( ; index < index_max && index < MAX_AUDIO_STREAMS; index++ )
2386 // Get codec context
2387 AVCodecContext *codec_context = self->audio_codec[ index ];
2389 if ( codec_context && !self->audio_buffer[ index ] )
2391 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2392 sizeof_sample = sample_bytes( codec_context );
2394 // Check for audio buffer and create if necessary
2395 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2396 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2398 // Check for decoder buffer and create if necessary
2399 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2403 // Get the audio if required
2404 if ( !paused && *frequency > 0 )
2410 av_init_packet( &pkt );
2412 // It requested number samples based on requested frame rate.
2413 // Do not clean this up with a samples *= ...!
2414 if ( self->audio_index != INT_MAX )
2415 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2417 while ( ret >= 0 && !got_audio )
2419 // Check if the buffer already contains the samples required
2420 if ( self->audio_index != INT_MAX &&
2421 self->audio_used[ self->audio_index ] >= *samples &&
2422 ignore[ self->audio_index ] == 0 )
2427 else if ( self->audio_index == INT_MAX )
2429 // Check if there is enough audio for all streams
2431 for ( index = 0; got_audio && index < index_max; index++ )
2432 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2439 pthread_mutex_lock( &self->packets_mutex );
2440 if ( mlt_deque_count( self->apackets ) )
2442 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2448 ret = av_read_frame( context, &pkt );
2449 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2451 if ( !av_dup_packet( &pkt ) )
2453 AVPacket *tmp = malloc( sizeof(AVPacket) );
2455 mlt_deque_push_back( self->vpackets, tmp );
2459 pthread_mutex_unlock( &self->packets_mutex );
2461 // We only deal with audio from the selected audio index
2462 index = pkt.stream_index;
2463 if ( index < MAX_AUDIO_STREAMS && ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2464 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2466 int channels2 = self->audio_codec[index]->channels;
2467 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2470 if ( self->seekable || index != self->video_index )
2471 av_free_packet( &pkt );
2475 // Set some additional return values
2476 *format = mlt_audio_s16;
2477 if ( self->audio_index != INT_MAX )
2479 index = self->audio_index;
2480 *channels = self->audio_codec[ index ]->channels;
2481 *frequency = self->audio_codec[ index ]->sample_rate;
2482 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2483 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2485 else if ( self->audio_index == INT_MAX )
2487 for ( index = 0; index < index_max; index++ )
2488 if ( self->audio_codec[ index ] )
2490 // XXX: This only works if all audio tracks have the same sample format.
2491 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2492 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2497 // Allocate and set the frame's audio buffer
2498 int size = mlt_audio_format_size( *format, *samples, *channels );
2499 *buffer = mlt_pool_alloc( size );
2500 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2502 // Interleave tracks if audio_index=all
2503 if ( self->audio_index == INT_MAX )
2505 uint8_t *dest = *buffer;
2507 for ( i = 0; i < *samples; i++ )
2509 for ( index = 0; index < index_max; index++ )
2510 if ( self->audio_codec[ index ] )
2512 int current_channels = self->audio_codec[ index ]->channels;
2513 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2514 memcpy( dest, src, current_channels * sizeof_sample );
2515 dest += current_channels * sizeof_sample;
2518 for ( index = 0; index < index_max; index++ )
2519 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2521 int current_channels = self->audio_codec[ index ]->channels;
2522 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2523 self->audio_used[index] -= *samples;
2524 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2527 // Copy a single track to the output buffer
2530 index = self->audio_index;
2532 // Now handle the audio if we have enough
2533 if ( self->audio_used[ index ] > 0 )
2535 uint8_t *src = self->audio_buffer[ index ];
2536 // copy samples from audio_buffer
2537 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2538 memcpy( *buffer, src, size * *channels * sizeof_sample );
2539 // supply the remaining requested samples as silence
2540 if ( *samples > self->audio_used[ index ] )
2541 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2542 // reposition the samples within audio_buffer
2543 self->audio_used[ index ] -= size;
2544 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2548 // Otherwise fill with silence
2549 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2555 // Get silence and don't touch the context
2556 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2559 // Regardless of speed (other than paused), we expect to get the next frame
2561 self->audio_expected = position + 1;
2563 pthread_mutex_unlock( &self->audio_mutex );
2568 /** Initialize the audio codec context.
2571 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2573 // Initialise the codec if necessary
2574 if ( !self->audio_codec[ index ] )
2576 // Get codec context
2577 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2580 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2582 // If we don't have a codec and we can't initialise it, we can't do much more...
2583 pthread_mutex_lock( &self->open_mutex );
2584 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2585 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2587 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2590 // Now store the codec with its destructor
2591 if ( self->audio_codec[ index ] )
2592 avcodec_close( self->audio_codec[ index ] );
2593 self->audio_codec[ index ] = codec_context;
2597 // Remember that we can't use self later
2598 self->audio_index = -1;
2600 pthread_mutex_unlock( &self->open_mutex );
2602 // Process properties as AVOptions
2603 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2604 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
2605 if ( codec && codec->priv_class && codec_context->priv_data )
2606 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2609 return self->audio_codec[ index ] && self->audio_index > -1;
2612 /** Set up audio handling.
2615 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2618 mlt_producer producer = self->parent;
2620 // Get the properties
2621 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2623 // Fetch the audio format context
2624 AVFormatContext *context = self->audio_format;
2626 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2628 // Get the audio_index
2629 int index = mlt_properties_get_int( properties, "audio_index" );
2631 // Handle all audio tracks
2632 if ( self->audio_index > -1 &&
2633 mlt_properties_get( properties, "audio_index" ) &&
2634 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2637 // Reopen the file if necessary
2638 if ( !context && self->audio_index > -1 && index > -1 )
2640 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2641 mlt_properties_get( properties, "resource" ), 1 );
2642 context = self->audio_format;
2645 // Exception handling for audio_index
2646 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2648 for ( index = context->nb_streams - 1;
2649 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2651 mlt_properties_set_int( properties, "audio_index", index );
2653 if ( context && index > -1 && index < INT_MAX &&
2654 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2656 index = self->audio_index;
2657 mlt_properties_set_int( properties, "audio_index", index );
2659 if ( context && index > -1 && index < INT_MAX &&
2660 pick_audio_format( context->streams[ index ]->codec->sample_fmt ) == mlt_audio_none )
2665 // Update the audio properties if the index changed
2666 if ( context && index > -1 && index != self->audio_index )
2668 pthread_mutex_lock( &self->open_mutex );
2669 if ( self->audio_codec[ self->audio_index ] )
2670 avcodec_close( self->audio_codec[ self->audio_index ] );
2671 self->audio_codec[ self->audio_index ] = NULL;
2672 pthread_mutex_unlock( &self->open_mutex );
2674 if ( self->audio_index != -1 )
2675 self->audio_index = index;
2680 if ( context && index == INT_MAX )
2682 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2683 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2684 for ( index = 0; index < context->nb_streams; index++ )
2686 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2687 audio_codec_init( self, index, properties );
2690 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2692 // Set the frame properties
2693 if ( index < MAX_AUDIO_STREAMS )
2695 mlt_properties_set_int( frame_properties, "audio_frequency", self->audio_codec[ index ]->sample_rate );
2696 mlt_properties_set_int( frame_properties, "audio_channels", self->audio_codec[ index ]->channels );
2699 if ( context && index > -1 )
2701 // Add our audio operation
2702 mlt_frame_push_audio( frame, self );
2703 mlt_frame_push_audio( frame, producer_get_audio );
2707 /** Our get frame implementation.
2710 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2712 // Access the private data
2713 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2714 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2715 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2720 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2721 producer->child = self;
2722 self->parent = producer;
2723 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2724 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2727 // Create an empty frame
2728 *frame = mlt_frame_init( service);
2732 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2736 mlt_cache_item_close( cache_item );
2740 // Update timecode on the frame we're creating
2741 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2744 producer_set_up_video( self, *frame );
2747 producer_set_up_audio( self, *frame );
2749 // Set the position of this producer
2750 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2751 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "original_position", position );
2753 // Calculate the next timecode
2754 mlt_producer_prepare_next( producer );
2759 static void producer_avformat_close( producer_avformat self )
2761 mlt_log_debug( NULL, "producer_avformat_close\n" );
2763 // Cleanup av contexts
2764 av_free_packet( &self->pkt );
2765 av_free( self->av_frame );
2766 pthread_mutex_lock( &self->open_mutex );
2768 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2770 mlt_pool_release( self->audio_buffer[i] );
2771 av_free( self->decode_buffer[i] );
2772 if ( self->audio_codec[i] )
2773 avcodec_close( self->audio_codec[i] );
2774 self->audio_codec[i] = NULL;
2776 if ( self->video_codec )
2777 avcodec_close( self->video_codec );
2778 self->video_codec = NULL;
2780 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2781 if ( self->dummy_context )
2782 avformat_close_input( &self->dummy_context );
2783 if ( self->seekable && self->audio_format )
2784 avformat_close_input( &self->audio_format );
2785 if ( self->video_format )
2786 avformat_close_input( &self->video_format );
2788 if ( self->dummy_context )
2789 av_close_input_file( self->dummy_context );
2790 if ( self->seekable && self->audio_format )
2791 av_close_input_file( self->audio_format );
2792 if ( self->video_format )
2793 av_close_input_file( self->video_format );
2795 pthread_mutex_unlock( &self->open_mutex );
2797 vdpau_producer_close( self );
2799 if ( self->image_cache )
2800 mlt_cache_close( self->image_cache );
2802 // Cleanup the mutexes
2803 if ( self->is_mutex_init )
2805 pthread_mutex_destroy( &self->audio_mutex );
2806 pthread_mutex_destroy( &self->video_mutex );
2807 pthread_mutex_destroy( &self->packets_mutex );
2808 pthread_mutex_destroy( &self->open_mutex );
2811 // Cleanup the packet queues
2813 if ( self->apackets )
2815 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2817 av_free_packet( pkt );
2820 mlt_deque_close( self->apackets );
2821 self->apackets = NULL;
2823 if ( self->vpackets )
2825 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2827 av_free_packet( pkt );
2830 mlt_deque_close( self->vpackets );
2831 self->vpackets = NULL;
2837 static void producer_close( mlt_producer parent )
2839 // Remove this instance from the cache
2840 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2843 parent->close = NULL;
2844 mlt_producer_close( parent );