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;
129 AVRational video_time_base;
134 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
148 typedef struct producer_avformat_s *producer_avformat;
150 // Forward references.
151 static int list_components( char* file );
152 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock );
153 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
154 static void producer_avformat_close( producer_avformat );
155 static void producer_close( mlt_producer parent );
156 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
157 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
158 static void apply_properties( void *obj, mlt_properties properties, int flags );
159 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
160 static void get_audio_streams_info( producer_avformat self );
161 static mlt_audio_format pick_audio_format( int sample_fmt );
167 /** Constructor for libavformat.
170 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
172 if ( list_components( file ) )
175 mlt_producer producer = NULL;
177 // Check that we have a non-NULL argument
180 // Construct the producer
181 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
182 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
185 if ( mlt_producer_init( producer, self ) == 0 )
187 self->parent = producer;
189 // Get the properties
190 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
192 // Set the resource property (required for all producers)
193 mlt_properties_set( properties, "resource", file );
195 // Register transport implementation with the producer
196 producer->close = (mlt_destructor) producer_close;
198 // Register our get_frame implementation
199 producer->get_frame = producer_get_frame;
201 if ( strcmp( service, "avformat-novalidate" ) )
204 if ( producer_open( self, profile, file, 1 ) != 0 )
207 mlt_producer_close( producer );
209 producer_avformat_close( self );
211 else if ( self->seekable )
213 // Close the file to release resources for large playlists - reopen later as needed
214 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
215 if ( self->audio_format )
216 avformat_close_input( &self->audio_format );
217 if ( self->video_format )
218 avformat_close_input( &self->video_format );
220 if ( self->audio_format )
221 av_close_input_file( self->audio_format );
222 if ( self->video_format )
223 av_close_input_file( self->video_format );
225 self->audio_format = NULL;
226 self->video_format = NULL;
231 // Default the user-selectable indices from the auto-detected indices
232 mlt_properties_set_int( properties, "audio_index", self->audio_index );
233 mlt_properties_set_int( properties, "video_index", self->video_index );
235 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
237 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
244 int list_components( char* file )
248 // Report information about available demuxers and codecs as YAML Tiny
249 if ( file && strstr( file, "f-list" ) )
251 fprintf( stderr, "---\nformats:\n" );
252 AVInputFormat *format = NULL;
253 while ( ( format = av_iformat_next( format ) ) )
254 fprintf( stderr, " - %s\n", format->name );
255 fprintf( stderr, "...\n" );
258 if ( file && strstr( file, "acodec-list" ) )
260 fprintf( stderr, "---\naudio_codecs:\n" );
261 AVCodec *codec = NULL;
262 while ( ( codec = av_codec_next( codec ) ) )
263 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
264 fprintf( stderr, " - %s\n", codec->name );
265 fprintf( stderr, "...\n" );
268 if ( file && strstr( file, "vcodec-list" ) )
270 fprintf( stderr, "---\nvideo_codecs:\n" );
271 AVCodec *codec = NULL;
272 while ( ( codec = av_codec_next( codec ) ) )
273 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
274 fprintf( stderr, " - %s\n", codec->name );
275 fprintf( stderr, "...\n" );
282 static int first_video_index( producer_avformat self )
284 AVFormatContext *context = self->video_format? self->video_format : self->audio_format;
285 int i = -1; // not found
288 for ( i = 0; i < context->nb_streams; i++ ) {
289 if ( context->streams[i]->codec &&
290 context->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
293 if ( i == context->nb_streams )
299 /** Find the default streams.
302 static mlt_properties find_default_streams( producer_avformat self )
306 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
307 AVDictionaryEntry *tag = NULL;
309 AVMetadataTag *tag = NULL;
311 AVFormatContext *context = self->video_format;
312 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
314 // Default to the first audio and video streams found
315 self->audio_index = -1;
316 self->video_index = -1;
318 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
320 // Allow for multiple audio and video streams in the file and select first of each (if available)
321 for( i = 0; i < context->nb_streams; i++ )
323 // Get the codec context
324 AVStream *stream = context->streams[ i ];
325 if ( ! stream ) continue;
326 AVCodecContext *codec_context = stream->codec;
327 if ( ! codec_context ) continue;
328 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
329 if ( ! codec ) continue;
331 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
333 // Determine the type and obtain the first index of each type
334 switch( codec_context->codec_type )
336 case CODEC_TYPE_VIDEO:
337 // Use first video stream
338 if ( self->video_index < 0 )
339 self->video_index = i;
340 mlt_properties_set( meta_media, key, "video" );
341 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
342 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
343 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
344 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
345 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
346 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
348 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
351 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
352 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
353 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
355 snprintf( key, sizeof(key), "meta.media.%d.codec.width", i );
356 mlt_properties_set_int( meta_media, key, codec_context->width );
357 snprintf( key, sizeof(key), "meta.media.%d.codec.height", i );
358 mlt_properties_set_int( meta_media, key, codec_context->height );
359 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
360 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
361 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
362 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
363 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(3<<8)+0)
364 mlt_properties_set( meta_media, key, av_get_pix_fmt_name( codec_context->pix_fmt ) );
366 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
368 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
369 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
370 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
371 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
372 switch ( codec_context->colorspace )
374 case AVCOL_SPC_SMPTE240M:
375 mlt_properties_set_int( meta_media, key, 240 );
377 case AVCOL_SPC_BT470BG:
378 case AVCOL_SPC_SMPTE170M:
379 mlt_properties_set_int( meta_media, key, 601 );
381 case AVCOL_SPC_BT709:
382 mlt_properties_set_int( meta_media, key, 709 );
385 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
386 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
391 case CODEC_TYPE_AUDIO:
392 if ( !codec_context->channels )
394 // Use first audio stream
395 if ( self->audio_index < 0 && pick_audio_format( codec_context->sample_fmt ) != mlt_audio_none )
396 self->audio_index = i;
398 mlt_properties_set( meta_media, key, "audio" );
399 #if LIBAVUTIL_VERSION_INT >= ((50<<16)+(38<<8)+0)
400 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
401 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
402 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
403 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
404 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
406 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
407 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
408 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
409 mlt_properties_set_int( meta_media, key, codec_context->channels );
414 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
415 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
416 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
417 mlt_properties_set( meta_media, key, codec->name );
418 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
419 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
420 mlt_properties_set( meta_media, key, codec->long_name );
422 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
423 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
424 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
425 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
426 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
427 // mlt_properties_set_int( meta_media, key, codec_context->profile );
428 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
429 // mlt_properties_set_int( meta_media, key, codec_context->level );
432 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
433 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
434 while ( ( tag = av_dict_get( stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
436 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
439 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
441 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
442 mlt_properties_set( meta_media, key, tag->value );
447 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
448 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
449 while ( ( tag = av_dict_get( context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
451 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
454 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
456 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
457 mlt_properties_set( meta_media, key, tag->value );
461 if ( context->title && strcmp( context->title, "" ) )
462 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
463 if ( context->author && strcmp( context->author, "" ) )
464 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
465 if ( context->copyright && strcmp( context->copyright, "" ) )
466 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
467 if ( context->comment )
468 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
469 if ( context->album )
470 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
472 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
473 if ( context->track )
474 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
480 static inline int dv_is_pal( AVPacket *pkt )
482 return pkt->data[3] & 0x80;
485 static int dv_is_wide( AVPacket *pkt )
487 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
489 for ( ; i < pkt->size; i += 5 /* packet size */ )
491 if ( pkt->data[ i ] == 0x61 )
493 uint8_t x = pkt->data[ i + 2 ] & 0x7;
494 return ( x == 2 ) || ( x == 7 );
500 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
502 double aspect_ratio = 1.0;
504 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
508 if ( dv_is_pal( pkt ) )
510 if ( dv_is_wide( pkt ) )
512 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
513 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
517 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
518 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
523 if ( dv_is_wide( pkt ) )
525 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
526 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
530 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
531 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
538 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
539 stream->sample_aspect_ratio;
541 codec_context->sample_aspect_ratio;
543 // Override FFmpeg's notion of DV aspect ratios, which are
544 // based upon a width of 704. Since we do not have a normaliser
545 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
546 // we just coerce the values to facilitate a passive behaviour through
547 // the rescale normaliser when using equivalent producers and consumers.
548 // = display_aspect / (width * height)
549 if ( ar.num == 10 && ar.den == 11 )
552 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
553 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
555 else if ( ar.num == 59 && ar.den == 54 )
558 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
559 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
561 else if ( ar.num == 40 && ar.den == 33 )
564 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
565 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
567 else if ( ar.num == 118 && ar.den == 81 )
570 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
571 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
577 AVRational codec_sar = codec_context->sample_aspect_ratio;
578 AVRational stream_sar =
579 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
580 stream->sample_aspect_ratio;
584 if ( codec_sar.num > 0 )
586 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
587 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
589 else if ( stream_sar.num > 0 )
591 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
592 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
596 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
597 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
600 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
601 aspect_ratio = av_q2d( ar );
602 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
607 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
608 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVDictionary **params )
610 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
613 if ( !URL ) return NULL;
616 char *protocol = strdup( URL );
617 char *url = strchr( protocol, ':' );
619 // Only if there is not a protocol specification that avformat can handle
620 #if LIBAVFORMAT_VERSION_MAJOR >= 53
621 if ( url && avio_check( URL, 0 ) < 0 )
623 if ( url && !url_exist( URL ) )
626 // Truncate protocol string
628 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
631 *format = av_find_input_format( protocol );
633 // Eat the format designator
638 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
639 // support for legacy width and height parameters
643 // These are required by video4linux2 (defaults)
644 params->width = profile->width;
645 params->height = profile->height;
646 if ( !strstr( URL, "&frame_rate" ) )
647 params->time_base = (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
648 params->channels = 2;
649 params->sample_rate = 48000;
653 url = strchr( url, '?' );
657 char *name = strdup( ++url );
658 char *value = strchr( name, '=' );
660 // Also accept : as delimiter for backwards compatibility.
661 value = strchr( name, ':' );
666 char *t = strchr( value, '&' );
669 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
670 // translate old parameters to new av_dict names
671 if ( !strcmp( name, "frame_rate" ) )
672 av_dict_set( params, "framerate", value, 0 );
673 else if ( !strcmp( name, "pix_fmt" ) )
674 av_dict_set( params, "pixel_format", value, 0 );
675 else if ( !strcmp( name, "width" ) )
676 width = strdup( value );
677 else if ( !strcmp( name, "height" ) )
678 height = strdup( value );
680 // generic demux/device option support
681 av_dict_set( params, name, value, 0 );
683 if ( !strcmp( name, "frame_rate" ) )
684 params->time_base.den = atoi( value );
685 else if ( !strcmp( name, "frame_rate_base" ) )
686 params->time_base.num = atoi( value );
687 else if ( !strcmp( name, "sample_rate" ) )
688 params->sample_rate = atoi( value );
689 else if ( !strcmp( name, "channel" ) )
690 params->channel = atoi( value );
691 else if ( !strcmp( name, "channels" ) )
692 params->channels = atoi( value );
693 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
694 else if ( !strcmp( name, "pix_fmt" ) )
695 params->pix_fmt = av_get_pix_fmt( value );
697 else if ( !strcmp( name, "width" ) )
698 params->width = atoi( value );
699 else if ( !strcmp( name, "height" ) )
700 params->height = atoi( value );
701 else if ( !strcmp( name, "standard" ) )
702 params->standard = strdup( value );
706 url = strchr( url, '&' );
708 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
709 // continued support for legacy width and height parameters
710 if ( width && height )
712 char *s = malloc( strlen( width ) + strlen( height ) + 2 );
716 av_dict_set( params, "video_size", s, 0 );
719 if ( width ) free( width );
720 if ( height ) free ( height );
723 result = strdup( result );
727 result = strdup( URL );
733 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
737 // Get the properties
738 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
740 AVFormatContext *format = self->video_format;
742 // We will treat everything with the producer fps.
743 // TODO: make this more flexible.
744 double fps = mlt_profile_fps( profile );
747 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
749 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
750 // when producer_open is called after initial call when restoring or reseting the producer.
751 if ( format->duration != AV_NOPTS_VALUE )
753 // This isn't going to be accurate for all formats
754 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
755 mlt_properties_set_position( properties, "out", frames - 1 );
756 mlt_properties_set_position( properties, "length", frames );
757 mlt_properties_set_int( properties, "_length_computed", 1 );
761 // Set live sources to run forever
762 mlt_properties_set_position( properties, "length", INT_MAX );
763 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
764 mlt_properties_set( properties, "eof", "loop" );
765 mlt_properties_set_int( properties, "_length_computed", 1 );
769 // Check if we're seekable
770 // avdevices are typically AVFMT_NOFILE and not seekable
771 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
774 // protocols can indicate if they support seeking
775 #if LIBAVFORMAT_VERSION_MAJOR >= 53
776 self->seekable = format->pb->seekable;
778 URLContext *uc = url_fileno( format->pb );
780 self->seekable = !uc->is_streamed;
783 if ( self->seekable )
785 // Do a more rigourous test of seekable on a disposable context
786 self->seekable = av_seek_frame( format, -1, format->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
787 mlt_properties_set_int( properties, "seekable", self->seekable );
788 self->dummy_context = format;
789 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
790 self->video_format = NULL;
791 avformat_open_input( &self->video_format, filename, NULL, NULL );
792 avformat_find_stream_info( self->video_format, NULL );
794 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
795 av_find_stream_info( self->video_format );
797 format = self->video_format;
800 // Fetch the width, height and aspect ratio
801 if ( self->video_index != -1 )
803 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
804 mlt_properties_set_int( properties, "width", codec_context->width );
805 mlt_properties_set_int( properties, "height", codec_context->height );
807 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
809 // Fetch the first frame of DV so we can read it directly
814 ret = av_read_frame( format, &pkt );
815 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
817 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, &pkt );
818 av_free_packet(&pkt);
822 av_free_packet(&pkt);
827 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context, NULL );
831 // Verify that we can convert this to YUV 4:2:2
832 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
833 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
834 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
836 sws_freeContext( context );
847 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
849 // Return an error code (0 == no error)
851 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
856 if ( !self->is_mutex_init )
858 pthread_mutex_init( &self->audio_mutex, NULL );
859 pthread_mutex_init( &self->video_mutex, NULL );
860 pthread_mutex_init( &self->packets_mutex, NULL );
861 pthread_mutex_init( &self->open_mutex, NULL );
862 self->is_mutex_init = 1;
864 pthread_mutex_lock( &self->audio_mutex );
865 pthread_mutex_lock( &self->video_mutex );
867 mlt_events_block( properties, self->parent );
870 AVInputFormat *format = NULL;
871 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
872 AVDictionary *params = NULL;
874 AVFormatParameters params;
875 memset( ¶ms, 0, sizeof(params) );
877 char *filename = parse_url( profile, URL, &format, ¶ms );
879 // Now attempt to open the file or device with filename
880 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
881 error = avformat_open_input( &self->video_format, filename, format, ¶ms ) < 0;
883 // If the URL is a network stream URL, then we probably need to open with full URL
884 error = avformat_open_input( &self->video_format, URL, format, ¶ms ) < 0;
886 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
888 // If the URL is a network stream URL, then we probably need to open with full URL
889 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
892 // Set MLT properties onto video AVFormatContext
893 if ( !error && self->video_format )
895 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
896 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
897 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
898 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
902 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
903 av_dict_free( ¶ms );
905 // Cleanup AVFormatParameters
906 if ( params.standard )
907 free( (void*) params.standard );
910 // If successful, then try to get additional info
911 if ( !error && self->video_format )
913 // Get the stream info
914 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
915 error = avformat_find_stream_info( self->video_format, NULL ) < 0;
917 error = av_find_stream_info( self->video_format ) < 0;
920 // Continue if no error
921 if ( !error && self->video_format )
923 // Find default audio and video streams
924 find_default_streams( self );
925 error = get_basic_info( self, profile, filename );
927 // Initialize position info
928 self->first_pts = AV_NOPTS_VALUE;
929 self->last_position = POSITION_INITIAL;
931 if ( !self->audio_format )
933 // We're going to cheat here - for seekable A/V files, we will have separate contexts
934 // to support independent seeking of audio from video.
935 // TODO: Is this really necessary?
936 if ( self->audio_index != -1 && self->video_index != -1 )
938 if ( self->seekable )
940 // And open again for our audio context
941 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
942 avformat_open_input( &self->audio_format, filename, NULL, NULL );
943 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
944 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
945 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
946 avformat_find_stream_info( self->audio_format, NULL );
948 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
949 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
950 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
951 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
952 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
954 av_find_stream_info( self->audio_format );
959 self->audio_format = self->video_format;
962 else if ( self->audio_index != -1 )
964 // We only have an audio context
965 self->audio_format = self->video_format;
966 self->video_format = NULL;
968 else if ( self->video_index == -1 )
970 // Something has gone wrong
973 if ( self->audio_format && !self->audio_streams )
974 get_audio_streams_info( self );
982 self->apackets = mlt_deque_init();
983 self->vpackets = mlt_deque_init();
986 if ( self->dummy_context )
988 pthread_mutex_lock( &self->open_mutex );
989 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
990 avformat_close_input( &self->dummy_context );
992 av_close_input_file( self->dummy_context );
994 self->dummy_context = NULL;
995 pthread_mutex_unlock( &self->open_mutex );
998 // Unlock the service
1001 pthread_mutex_unlock( &self->audio_mutex );
1002 pthread_mutex_unlock( &self->video_mutex );
1004 mlt_events_unblock( properties, self->parent );
1009 static void reopen_video( producer_avformat self, mlt_producer producer )
1011 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1012 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1013 pthread_mutex_lock( &self->audio_mutex );
1014 pthread_mutex_lock( &self->open_mutex );
1016 if ( self->video_codec )
1017 avcodec_close( self->video_codec );
1018 self->video_codec = NULL;
1019 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
1020 if ( self->dummy_context )
1021 avformat_close_input( &self->dummy_context );
1022 if ( self->video_format )
1023 avformat_close_input( &self->video_format );
1025 if ( self->dummy_context )
1026 av_close_input_file( self->dummy_context );
1027 if ( self->video_format )
1028 av_close_input_file( self->video_format );
1030 self->dummy_context = NULL;
1031 self->video_format = NULL;
1032 pthread_mutex_unlock( &self->open_mutex );
1034 int audio_index = self->audio_index;
1035 int video_index = self->video_index;
1037 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1038 mlt_properties_get( properties, "resource" ), 0 );
1040 self->audio_index = audio_index;
1041 if ( self->video_format && video_index > -1 )
1043 self->video_index = video_index;
1044 video_codec_init( self, video_index, properties );
1047 pthread_mutex_unlock( &self->audio_mutex );
1048 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1051 static int64_t best_pts( producer_avformat self, int64_t pts, int64_t dts )
1053 self->invalid_pts_counter += pts == AV_NOPTS_VALUE;
1054 self->invalid_dts_counter += dts == AV_NOPTS_VALUE;
1055 if ( ( self->invalid_pts_counter <= self->invalid_dts_counter
1056 || dts == AV_NOPTS_VALUE ) && pts != AV_NOPTS_VALUE )
1062 static void find_first_pts( producer_avformat self, int video_index )
1065 AVFormatContext *context = self->video_format? self->video_format : self->audio_format;
1070 while ( ret >= 0 && toscan-- > 0 )
1072 ret = av_read_frame( context, &pkt );
1073 if ( ret >= 0 && pkt.stream_index == video_index && ( pkt.flags & PKT_FLAG_KEY ) )
1075 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
1076 "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n",
1077 pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
1078 self->first_pts = best_pts( self, pkt.pts, pkt.dts );
1079 if ( self->first_pts != AV_NOPTS_VALUE )
1082 av_free_packet( &pkt );
1084 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1087 static int seek_video( producer_avformat self, mlt_position position,
1088 int64_t req_position, int preseek )
1090 mlt_producer producer = self->parent;
1093 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
1095 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1097 // Fetch the video format context
1098 AVFormatContext *context = self->video_format;
1100 // Get the video stream
1101 AVStream *stream = context->streams[ self->video_index ];
1103 // Get codec context
1104 AVCodecContext *codec_context = stream->codec;
1106 // We may want to use the source fps if available
1107 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1108 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1110 if ( self->last_position == POSITION_INITIAL )
1111 find_first_pts( self, self->video_index );
1113 if ( self->av_frame && position + 1 == self->video_expected )
1115 // We're paused - use last image
1118 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
1120 // Calculate the timestamp for the requested frame
1121 int64_t timestamp = req_position / ( av_q2d( self->video_time_base ) * source_fps );
1122 if ( req_position <= 0 )
1124 else if ( self->first_pts != AV_NOPTS_VALUE )
1125 timestamp += self->first_pts;
1126 else if ( context->start_time != AV_NOPTS_VALUE )
1127 timestamp += context->start_time;
1128 if ( preseek && av_q2d( self->video_time_base ) != 0 )
1129 timestamp -= 2 / av_q2d( self->video_time_base );
1130 if ( timestamp < 0 )
1132 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
1133 timestamp, position, self->video_expected, self->last_position );
1135 // Seek to the timestamp
1136 // NOTE: reopen_video is disabled at this time because it is causing trouble with A/V sync.
1137 if ( 1 || req_position > 0 || self->last_position <= 0 )
1139 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1140 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1142 // flush any pictures still in decode buffer
1143 avcodec_flush_buffers( codec_context );
1147 // Re-open video stream when rewinding to beginning from somewhere else.
1148 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1149 // not reliably seeking to the first frame across formats.
1150 reopen_video( self, producer );
1153 // Remove the cached info relating to the previous position
1154 self->current_position = POSITION_INVALID;
1155 self->last_position = POSITION_INVALID;
1156 av_freep( &self->av_frame );
1162 /** Convert a frame position to a time code.
1165 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
1167 return ( double )position / mlt_producer_get_fps( producer );
1170 // Collect information about all audio streams
1172 static void get_audio_streams_info( producer_avformat self )
1174 // Fetch the audio format context
1175 AVFormatContext *context = self->audio_format;
1179 i < context->nb_streams;
1182 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1184 AVCodecContext *codec_context = context->streams[i]->codec;
1185 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1187 // If we don't have a codec and we can't initialise it, we can't do much more...
1188 pthread_mutex_lock( &self->open_mutex );
1189 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1190 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1192 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1195 self->audio_streams++;
1196 self->audio_max_stream = i;
1197 self->total_channels += codec_context->channels;
1198 if ( codec_context->channels > self->max_channel )
1199 self->max_channel = codec_context->channels;
1200 if ( codec_context->sample_rate > self->max_frequency )
1201 self->max_frequency = codec_context->sample_rate;
1202 avcodec_close( codec_context );
1204 pthread_mutex_unlock( &self->open_mutex );
1207 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1208 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1210 // Other audio-specific initializations
1211 self->resample_factor = 1.0;
1214 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1216 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
1218 const int *new_coefficients;
1220 int brightness, contrast, saturation;
1222 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1223 &brightness, &contrast, &saturation ) != -1 )
1225 // Don't change these from defaults unless explicitly told to.
1226 if ( use_full_range >= 0 )
1227 full_range = use_full_range;
1228 switch ( colorspace )
1234 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1237 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1240 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1243 new_coefficients = coefficients;
1246 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1247 brightness, contrast, saturation );
1252 static mlt_image_format pick_pix_format( enum PixelFormat pix_fmt )
1260 return mlt_image_rgb24a;
1261 case PIX_FMT_YUV420P:
1262 case PIX_FMT_YUVJ420P:
1263 case PIX_FMT_YUVA420P:
1264 return mlt_image_yuv420p;
1268 case PIX_FMT_MONOWHITE:
1269 case PIX_FMT_MONOBLACK:
1272 return mlt_image_rgb24;
1274 return mlt_image_yuv422;
1278 static mlt_audio_format pick_audio_format( int sample_fmt )
1280 switch ( sample_fmt )
1283 case AV_SAMPLE_FMT_U8:
1284 return mlt_audio_u8;
1285 case AV_SAMPLE_FMT_S16:
1286 return mlt_audio_s16;
1287 case AV_SAMPLE_FMT_S32:
1288 return mlt_audio_s32le;
1289 case AV_SAMPLE_FMT_FLT:
1290 return mlt_audio_f32le;
1291 // planar - this producer converts planar to interleaved
1292 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1293 case AV_SAMPLE_FMT_U8P:
1294 return mlt_audio_u8;
1295 case AV_SAMPLE_FMT_S16P:
1296 return mlt_audio_s16;
1297 case AV_SAMPLE_FMT_S32P:
1298 return mlt_audio_s32le;
1299 case AV_SAMPLE_FMT_FLTP:
1300 return mlt_audio_f32le;
1303 return mlt_audio_none;
1307 static void convert_image( producer_avformat self, AVFrame *frame, uint8_t *buffer, int pix_fmt,
1308 mlt_image_format *format, int width, int height, uint8_t **alpha )
1311 int flags = SWS_BICUBIC | SWS_ACCURATE_RND;
1314 flags |= SWS_CPU_CAPS_MMX;
1317 flags |= SWS_CPU_CAPS_MMX2;
1320 // extract alpha from planar formats
1321 if ( ( pix_fmt == PIX_FMT_YUVA420P
1322 #if defined(FFUDIV) && LIBAVUTIL_VERSION_INT >= ((51<<16)+(35<<8)+101)
1323 || pix_fmt == PIX_FMT_YUVA444P
1326 *format != mlt_image_rgb24a && *format != mlt_image_opengl &&
1327 frame->data[3] && frame->linesize[3] )
1332 dst = *alpha = mlt_pool_alloc( width * height );
1333 src = frame->data[3];
1335 for ( i = 0; i < height; dst += width, src += frame->linesize[3], i++ )
1336 memcpy( dst, src, FFMIN( width, frame->linesize[3] ) );
1339 if ( *format == mlt_image_yuv420p )
1341 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1342 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1344 output.data[0] = buffer;
1345 output.data[1] = buffer + width * height;
1346 output.data[2] = buffer + ( 5 * width * height ) / 4;
1347 output.linesize[0] = width;
1348 output.linesize[1] = width >> 1;
1349 output.linesize[2] = width >> 1;
1350 set_luma_transfer( context, self->colorspace, -1 );
1351 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1352 output.data, output.linesize);
1353 sws_freeContext( context );
1355 else if ( *format == mlt_image_rgb24 )
1357 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1358 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1360 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1361 set_luma_transfer( context, self->colorspace, self->full_luma );
1362 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1363 output.data, output.linesize);
1364 sws_freeContext( context );
1366 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1368 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1369 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1371 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1372 set_luma_transfer( context, self->colorspace, self->full_luma );
1373 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1374 output.data, output.linesize);
1375 sws_freeContext( context );
1379 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1380 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1382 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1383 set_luma_transfer( context, self->colorspace, -1 );
1384 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1385 output.data, output.linesize);
1386 sws_freeContext( context );
1389 if ( *format == mlt_image_yuv420p )
1392 pict.data[0] = buffer;
1393 pict.data[1] = buffer + width * height;
1394 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1395 pict.linesize[0] = width;
1396 pict.linesize[1] = width >> 1;
1397 pict.linesize[2] = width >> 1;
1398 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1400 else if ( *format == mlt_image_rgb24 )
1403 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1404 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1406 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1409 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1410 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1415 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1416 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1421 /** Allocate the image buffer and set it on the frame.
1424 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1428 if ( codec_context->width == 0 || codec_context->height == 0 )
1431 if ( *format == mlt_image_glsl )
1432 *format = pick_pix_format( codec_context->pix_fmt );
1434 *width = codec_context->width;
1435 *height = codec_context->height;
1436 size = mlt_image_format_size( *format, *width, *height, NULL );
1437 *buffer = mlt_pool_alloc( size );
1439 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1446 /** Get an image from a frame.
1449 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1452 producer_avformat self = mlt_frame_pop_service( frame );
1453 mlt_producer producer = self->parent;
1455 // Get the properties from the frame
1456 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1458 // Obtain the frame number of this frame
1459 mlt_position position = mlt_frame_original_position( frame );
1461 // Get the producer properties
1462 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1464 pthread_mutex_lock( &self->video_mutex );
1466 // Fetch the video format context
1467 AVFormatContext *context = self->video_format;
1469 // Get the video stream
1470 AVStream *stream = context->streams[ self->video_index ];
1472 // Get codec context
1473 AVCodecContext *codec_context = stream->codec;
1475 uint8_t *alpha = NULL;
1476 int got_picture = 0;
1479 // Get the image cache
1480 if ( ! self->image_cache )
1482 // if cache size supplied by environment variable
1483 int cache_supplied = getenv( "MLT_AVFORMAT_CACHE" ) != NULL;
1484 int cache_size = cache_supplied? atoi( getenv( "MLT_AVFORMAT_CACHE" ) ) : 0;
1486 // cache size supplied via property
1487 if ( mlt_properties_get( properties, "cache" ) )
1490 cache_size = mlt_properties_get_int( properties, "cache" );
1492 if ( mlt_properties_get_int( properties, "noimagecache" ) )
1494 // create cache if not disabled
1495 if ( !cache_supplied || cache_size > 0 )
1496 self->image_cache = mlt_cache_init();
1497 // set cache size if supplied
1498 if ( self->image_cache && cache_supplied )
1499 mlt_cache_set_size( self->image_cache, cache_size );
1501 if ( self->image_cache )
1503 mlt_frame original = mlt_cache_get_frame( self->image_cache, position );
1506 mlt_properties orig_props = MLT_FRAME_PROPERTIES( original );
1509 *buffer = mlt_properties_get_data( orig_props, "alpha", &size );
1511 mlt_frame_set_alpha( frame, *buffer, size, NULL );
1512 *buffer = mlt_properties_get_data( orig_props, "image", &size );
1513 mlt_frame_set_image( frame, *buffer, size, NULL );
1514 mlt_properties_set_data( frame_properties, "avformat.image_cache", original, 0, (mlt_destructor) mlt_frame_close, NULL );
1515 *format = mlt_properties_get_int( orig_props, "format" );
1517 // Set the resolution
1518 *width = codec_context->width;
1519 *height = codec_context->height;
1521 // Workaround 1088 encodings missing cropping info.
1522 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1526 goto exit_get_image;
1531 // We may want to use the source fps if available
1532 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1533 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1535 // This is the physical frame position in the source
1536 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1538 // Determines if we have to decode all frames in a sequence
1539 // Temporary hack to improve intra frame only
1540 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1541 strcmp( codec_context->codec->name, "dnxhd" ) &&
1542 strcmp( codec_context->codec->name, "dvvideo" ) &&
1543 strcmp( codec_context->codec->name, "huffyuv" ) &&
1544 strcmp( codec_context->codec->name, "mjpeg" ) &&
1545 strcmp( codec_context->codec->name, "rawvideo" ) );
1547 double delay = mlt_properties_get_double( properties, "video_delay" );
1549 // Seek if necessary
1550 const char *interp = mlt_properties_get( frame_properties, "rescale.interp" );
1551 int preseek = must_decode
1552 #if defined(FFUDIV) && LIBAVFORMAT_VERSION_INT >= ((53<<16)+(24<<8)+2)
1553 && ( interp && strcmp( interp, "nearest" ) )
1555 && codec_context->has_b_frames;
1556 int paused = seek_video( self, position, req_position, preseek );
1558 // Seek might have reopened the file
1559 context = self->video_format;
1560 stream = context->streams[ self->video_index ];
1561 codec_context = stream->codec;
1562 if ( *format == mlt_image_none ||
1563 codec_context->pix_fmt == PIX_FMT_ARGB ||
1564 codec_context->pix_fmt == PIX_FMT_RGBA ||
1565 codec_context->pix_fmt == PIX_FMT_ABGR ||
1566 codec_context->pix_fmt == PIX_FMT_BGRA )
1567 *format = pick_pix_format( codec_context->pix_fmt );
1569 // Duplicate the last image if necessary
1570 if ( self->av_frame && self->av_frame->linesize[0]
1571 && ( paused || self->current_position >= req_position ) )
1574 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1576 // Workaround 1088 encodings missing cropping info.
1577 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1580 if ( self->vdpau && self->vdpau->buffer )
1583 picture.data[0] = self->vdpau->buffer;
1584 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1585 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1586 picture.linesize[0] = codec_context->width;
1587 picture.linesize[1] = codec_context->width / 2;
1588 picture.linesize[2] = codec_context->width / 2;
1589 convert_image( self, (AVFrame*) &picture, *buffer,
1590 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1594 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1595 format, *width, *height, &alpha );
1602 int64_t int_position = 0;
1603 int decode_errors = 0;
1605 // Construct an AVFrame for YUV422 conversion
1606 if ( !self->av_frame )
1607 self->av_frame = avcodec_alloc_frame( );
1609 while( ret >= 0 && !got_picture )
1612 if ( self->pkt.stream_index == self->video_index )
1613 av_free_packet( &self->pkt );
1614 av_init_packet( &self->pkt );
1615 pthread_mutex_lock( &self->packets_mutex );
1616 if ( mlt_deque_count( self->vpackets ) )
1618 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1624 ret = av_read_frame( context, &self->pkt );
1625 if ( ret >= 0 && !self->seekable && self->pkt.stream_index == self->audio_index )
1627 if ( !av_dup_packet( &self->pkt ) )
1629 AVPacket *tmp = malloc( sizeof(AVPacket) );
1631 mlt_deque_push_back( self->apackets, tmp );
1635 pthread_mutex_unlock( &self->packets_mutex );
1637 // We only deal with video from the selected video_index
1638 if ( ret >= 0 && self->pkt.stream_index == self->video_index && self->pkt.size > 0 )
1640 int64_t pts = best_pts( self, self->pkt.pts, self->pkt.dts );
1641 if ( pts != AV_NOPTS_VALUE )
1643 if ( !self->seekable && self->first_pts == AV_NOPTS_VALUE )
1644 self->first_pts = pts;
1645 if ( self->first_pts != AV_NOPTS_VALUE )
1646 pts -= self->first_pts;
1647 else if ( context->start_time != AV_NOPTS_VALUE )
1648 pts -= context->start_time;
1649 int_position = ( int64_t )( ( av_q2d( self->video_time_base ) * pts + delay ) * source_fps + 0.5 );
1650 if ( int_position == self->last_position )
1651 int_position = self->last_position + 1;
1653 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1654 "V pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1655 self->pkt.pts, self->pkt.dts, req_position, self->current_position, int_position );
1657 // Make a dumb assumption on streams that contain wild timestamps
1658 if ( abs( req_position - int_position ) > 999 )
1660 int_position = req_position;
1661 mlt_log_warning( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!\n" );
1663 self->last_position = int_position;
1666 if ( must_decode || int_position >= req_position )
1671 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1673 vdpau_decoder_init( self );
1675 self->vdpau->is_decoded = 0;
1678 codec_context->reordered_opaque = int_position;
1679 if ( int_position >= req_position )
1680 codec_context->skip_loop_filter = AVDISCARD_NONE;
1681 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1682 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &self->pkt );
1684 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, self->pkt.data, self->pkt.size );
1686 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1689 if ( ++decode_errors <= 10 )
1700 // Get position of reordered frame
1701 int_position = self->av_frame->reordered_opaque;
1702 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(106<<8)+0))
1703 pts = best_pts( self, self->av_frame->pkt_pts, self->av_frame->pkt_dts );
1704 if ( pts != AV_NOPTS_VALUE )
1706 if ( self->first_pts != AV_NOPTS_VALUE )
1707 pts -= self->first_pts;
1708 else if ( context->start_time != AV_NOPTS_VALUE )
1709 pts -= context->start_time;
1710 int_position = ( int64_t )( ( av_q2d( self->video_time_base ) * pts + delay ) * source_fps + 0.5 );
1714 if ( int_position < req_position )
1716 else if ( int_position >= req_position )
1717 codec_context->skip_loop_filter = AVDISCARD_NONE;
1719 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, self->pkt.flags & PKT_FLAG_KEY );
1722 // Now handle the picture if we have one
1725 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1727 // Workaround 1088 encodings missing cropping info.
1728 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1733 if ( self->vdpau->is_decoded )
1735 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1737 uint32_t pitches[3];
1738 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1740 if ( !self->vdpau->buffer )
1741 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1742 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1743 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1744 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1745 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1746 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1747 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1749 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1750 if ( status == VDP_STATUS_OK )
1752 convert_image( self, self->av_frame, *buffer, PIX_FMT_YUV420P,
1753 format, *width, *height, &alpha );
1757 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1758 image_size = self->vdpau->is_decoded = 0;
1763 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1764 image_size = got_picture = 0;
1769 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1770 format, *width, *height, &alpha );
1771 self->top_field_first |= self->av_frame->top_field_first;
1772 self->current_position = int_position;
1780 // Free packet data if not video and not live audio packet
1781 if ( self->pkt.stream_index != self->video_index &&
1782 !( !self->seekable && self->pkt.stream_index == self->audio_index ) )
1783 av_free_packet( &self->pkt );
1789 mlt_frame_set_alpha( frame, alpha, (*width) * (*height), mlt_pool_release );
1791 if ( image_size > 0 && self->image_cache )
1793 mlt_properties_set_int( frame_properties, "format", *format );
1794 mlt_cache_put_frame( self->image_cache, frame );
1797 // Try to duplicate last image if there was a decoding failure
1798 // TODO: with multithread decoding a partial frame decoding resulting
1799 // in failure also resets av_frame making test below fail.
1800 if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1803 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1805 // Workaround 1088 encodings missing cropping info.
1806 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1809 if ( self->vdpau && self->vdpau->buffer )
1812 picture.data[0] = self->vdpau->buffer;
1813 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1814 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1815 picture.linesize[0] = codec_context->width;
1816 picture.linesize[1] = codec_context->width / 2;
1817 picture.linesize[2] = codec_context->width / 2;
1818 convert_image( self, (AVFrame*) &picture, *buffer,
1819 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1823 convert_image( self, self->av_frame, *buffer, codec_context->pix_fmt,
1824 format, *width, *height, &alpha );
1829 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1830 self->video_expected = position + 1;
1834 pthread_mutex_unlock( &self->video_mutex );
1836 // Set the progressive flag
1837 if ( mlt_properties_get( properties, "force_progressive" ) )
1838 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1839 else if ( self->av_frame )
1840 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1842 // Set the field order property for this frame
1843 if ( mlt_properties_get( properties, "force_tff" ) )
1844 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1846 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1848 // Set immutable properties of the selected track's (or overridden) source attributes.
1849 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1850 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1851 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1852 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1854 // If we already have RGB, then the full range processing either happened already
1855 // or does not apply (RGB source).
1856 if ( *format == mlt_image_rgb24 || *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1857 mlt_properties_set( frame_properties, "force_full_luma", NULL );
1859 return !got_picture;
1862 /** Process properties as AVOptions and apply to AV context obj
1865 static void apply_properties( void *obj, mlt_properties properties, int flags )
1868 int count = mlt_properties_count( properties );
1869 for ( i = 0; i < count; i++ )
1871 const char *opt_name = mlt_properties_get_name( properties, i );
1872 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
1873 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1875 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1877 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1880 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1881 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1882 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1883 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1884 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1885 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1887 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1893 /** Initialize the video codec context.
1896 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1898 // Initialise the codec if necessary
1899 if ( !self->video_codec )
1901 // Get the video stream
1902 AVStream *stream = self->video_format->streams[ index ];
1904 // Get codec context
1905 AVCodecContext *codec_context = stream->codec;
1908 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1910 if ( codec_context->codec_id == CODEC_ID_H264 )
1912 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1914 if ( vdpau_init( self ) )
1916 self->video_codec = codec_context;
1917 if ( !vdpau_decoder_init( self ) )
1922 codec = avcodec_find_decoder( codec_context->codec_id );
1926 // Initialise multi-threading
1927 int thread_count = mlt_properties_get_int( properties, "threads" );
1928 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1929 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1930 if ( thread_count > 1 )
1931 codec_context->thread_count = thread_count;
1933 // If we don't have a codec and we can't initialise it, we can't do much more...
1934 pthread_mutex_lock( &self->open_mutex );
1935 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1936 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1938 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1941 // Now store the codec with its destructor
1942 self->video_codec = codec_context;
1946 // Remember that we can't use this later
1947 self->video_index = -1;
1948 pthread_mutex_unlock( &self->open_mutex );
1951 pthread_mutex_unlock( &self->open_mutex );
1953 // Process properties as AVOptions
1954 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1955 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1956 if ( codec->priv_class && codec_context->priv_data )
1957 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1960 // Reset some image properties
1961 if ( self->video_codec )
1963 mlt_properties_set_int( properties, "width", self->video_codec->width );
1964 mlt_properties_set_int( properties, "height", self->video_codec->height );
1966 // For DV, we'll just use the saved aspect ratio
1967 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1968 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1970 // Determine the fps first from the codec
1971 double source_fps = (double) self->video_codec->time_base.den /
1972 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1975 // If the muxer reports a frame rate different than the codec
1976 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1977 double muxer_fps = av_q2d( stream->avg_frame_rate );
1978 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1979 muxer_fps = av_q2d( stream->r_frame_rate );
1981 double muxer_fps = av_q2d( stream->r_frame_rate );
1983 // Choose the lesser - the wrong tends to be off by some multiple of 10
1984 source_fps = FFMIN( source_fps, muxer_fps );
1985 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1987 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1988 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1990 else if ( muxer_fps > 0 )
1992 AVRational frame_rate = stream->r_frame_rate;
1993 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1994 // avg_frame_rate gives some approximate value that does not well match the media.
1995 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1996 // results in some very choppy output, but some value slightly different works
1998 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1999 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
2000 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
2002 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
2003 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
2007 source_fps = mlt_producer_get_fps( self->parent );
2008 AVRational frame_rate = av_d2q( source_fps, 255 );
2009 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
2010 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
2013 self->video_time_base = stream->time_base;
2014 if ( mlt_properties_get( properties, "force_fps" ) )
2016 double source_fps = mlt_properties_get_double( properties, "force_fps" );
2017 AVRational fps = av_d2q( source_fps, 1024 );
2018 self->video_time_base.num *= mlt_properties_get_int( properties, "meta.media.frame_rate_num" ) * fps.den;
2019 self->video_time_base.den *= mlt_properties_get_int( properties, "meta.media.frame_rate_den" ) * fps.num;
2020 mlt_properties_set_int( properties, "meta.media.frame_rate_num", fps.num );
2021 mlt_properties_set_int( properties, "meta.media.frame_rate_den", fps.den );
2024 // Set the YUV colorspace from override or detect
2025 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
2026 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
2027 if ( ! self->colorspace )
2029 switch ( self->video_codec->colorspace )
2031 case AVCOL_SPC_SMPTE240M:
2032 self->colorspace = 240;
2034 case AVCOL_SPC_BT470BG:
2035 case AVCOL_SPC_SMPTE170M:
2036 self->colorspace = 601;
2038 case AVCOL_SPC_BT709:
2039 self->colorspace = 709;
2042 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
2043 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
2048 // Let apps get chosen colorspace
2049 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
2051 self->full_luma = -1;
2052 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(72<<8)+2)
2053 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent), "color_range %d\n", codec_context->color_range );
2054 if ( codec_context->color_range == AVCOL_RANGE_JPEG )
2055 self->full_luma = 1;
2057 if ( mlt_properties_get( properties, "set.force_full_luma" ) )
2058 self->full_luma = mlt_properties_get_int( properties, "set.force_full_luma" );
2060 return self->video_codec && self->video_index > -1;
2063 /** Set up video handling.
2066 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
2069 mlt_producer producer = self->parent;
2071 // Get the properties
2072 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2074 // Fetch the video format context
2075 AVFormatContext *context = self->video_format;
2077 // Get the video_index
2078 int index = mlt_properties_get_int( properties, "video_index" );
2080 // Reopen the file if necessary
2081 if ( !context && index > -1 )
2083 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2084 mlt_properties_get( properties, "resource" ), 1 );
2085 context = self->video_format;
2088 // Exception handling for video_index
2089 if ( context && index >= (int) context->nb_streams )
2091 // Get the last video stream
2092 for ( index = context->nb_streams - 1;
2093 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
2095 mlt_properties_set_int( properties, "video_index", index );
2097 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
2099 // Invalidate the video stream
2101 mlt_properties_set_int( properties, "video_index", index );
2104 // Update the video properties if the index changed
2105 if ( index != self->video_index )
2107 // Reset the video properties if the index changed
2108 self->video_index = index;
2109 pthread_mutex_lock( &self->open_mutex );
2110 if ( self->video_codec )
2111 avcodec_close( self->video_codec );
2112 self->video_codec = NULL;
2113 pthread_mutex_unlock( &self->open_mutex );
2116 // Get the frame properties
2117 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2120 if ( context && index > -1 && video_codec_init( self, index, properties ) )
2122 // Set the frame properties
2123 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
2124 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
2125 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
2127 // Set the width and height
2128 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
2129 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
2130 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
2131 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
2132 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
2133 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
2135 // Workaround 1088 encodings missing cropping info.
2136 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
2138 mlt_properties_set_int( properties, "meta.media.height", 1080 );
2141 // Add our image operation
2142 mlt_frame_push_service( frame, self );
2143 mlt_frame_push_get_image( frame, producer_get_image );
2147 // If something failed, use test card image
2148 mlt_properties_set_int( frame_properties, "test_image", 1 );
2152 static int seek_audio( producer_avformat self, mlt_position position, double timecode )
2156 // Seek if necessary
2157 if ( self->seekable && ( position != self->audio_expected || self->last_position < 0 ) )
2159 if ( self->last_position == POSITION_INITIAL )
2161 int video_index = self->video_index;
2162 if ( video_index == -1 )
2163 video_index = first_video_index( self );
2164 if ( video_index >= 0 )
2165 find_first_pts( self, video_index );
2168 if ( position + 1 == self->audio_expected )
2170 // We're paused - silence required
2173 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
2175 AVFormatContext *context = self->audio_format;
2176 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
2177 if ( context->start_time != AV_NOPTS_VALUE )
2178 timestamp += context->start_time;
2179 if ( timestamp < 0 )
2182 // Set to the real timecode
2183 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
2186 // Clear the usage in the audio buffer
2187 int i = MAX_AUDIO_STREAMS + 1;
2189 self->audio_used[i - 1] = 0;
2195 static int sample_bytes( AVCodecContext *context )
2197 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2198 return av_get_bytes_per_sample( context->sample_fmt );
2199 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2200 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2202 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2206 static void planar_to_interleaved( uint8_t *dest, uint8_t *src, int samples, int channels, int bytes_per_sample )
2209 for ( s = 0; s < samples; s++ )
2211 for ( c = 0; c < channels; c++ )
2213 memcpy( dest, src + ( c * samples + s ) * bytes_per_sample, bytes_per_sample );
2214 dest += bytes_per_sample;
2219 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2221 // Fetch the audio_format
2222 AVFormatContext *context = self->audio_format;
2224 // Get the current stream index
2225 int index = pkt.stream_index;
2227 // Get codec context
2228 AVCodecContext *codec_context = self->audio_codec[ index ];
2230 // Obtain the resample context if it exists (not always needed)
2231 ReSampleContext *resample = self->audio_resample[ index ];
2233 // Obtain the audio buffers
2234 uint8_t *audio_buffer = self->audio_buffer[ index ];
2235 uint8_t *decode_buffer = self->decode_buffer[ index ];
2237 int audio_used = self->audio_used[ index ];
2238 uint8_t *ptr = pkt.data;
2242 while ( ptr && ret >= 0 && len > 0 )
2244 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
2245 int data_size = self->audio_buffer_size[ index ];
2248 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
2249 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2250 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
2251 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
2253 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
2257 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2261 pkt.size = len -= ret;
2262 pkt.data = ptr += ret;
2264 // If decoded successfully
2265 if ( data_size > 0 )
2267 // Figure out how many samples will be needed after resampling
2268 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2269 int samples_needed = self->resample_factor * convert_samples;
2271 // Resize audio buffer to prevent overflow
2272 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2274 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
2275 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2279 // Copy to audio buffer while resampling
2280 uint8_t *source = decode_buffer;
2281 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
2282 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
2286 uint8_t *source = decode_buffer;
2287 uint8_t *dest = &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ];
2288 switch ( codec_context->sample_fmt )
2290 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2291 case AV_SAMPLE_FMT_U8P:
2292 case AV_SAMPLE_FMT_S16P:
2293 case AV_SAMPLE_FMT_S32P:
2294 case AV_SAMPLE_FMT_FLTP:
2295 planar_to_interleaved( dest, source, convert_samples, codec_context->channels, sizeof_sample );
2299 // Straight copy to audio buffer
2300 memcpy( dest, decode_buffer, data_size );
2302 audio_used += convert_samples;
2306 while ( *ignore && audio_used )
2309 audio_used -= audio_used > samples ? samples : audio_used;
2310 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
2311 audio_used * sizeof_sample );
2316 // If we're behind, ignore this packet
2317 // Skip this on non-seekable, audio-only inputs.
2318 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2320 int64_t pts = pkt.pts;
2321 if ( self->first_pts != AV_NOPTS_VALUE )
2322 pts -= self->first_pts;
2323 else if ( context->start_time != AV_NOPTS_VALUE )
2324 pts -= context->start_time;
2325 double timebase = av_q2d( context->streams[ index ]->time_base );
2326 int64_t int_position = ( int64_t )( timebase * pts * fps + 0.5 );
2327 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2329 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
2330 "A pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
2331 pkt.pts, pkt.dts, req_position, self->current_position, int_position );
2333 if ( int_position > 0 )
2335 if ( int_position < req_position )
2336 // We are behind, so skip some
2337 *ignore = req_position - int_position;
2338 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2339 // We are ahead, so seek backwards some more
2340 seek_audio( self, req_position, timecode - 1.0 );
2342 // Cancel the find_first_pts() in seek_audio()
2343 if ( self->video_index == -1 && self->last_position == POSITION_INITIAL )
2344 self->last_position = int_position;
2347 self->audio_used[ index ] = audio_used;
2352 /** Get the audio from a frame.
2354 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2357 producer_avformat self = mlt_frame_pop_audio( frame );
2359 pthread_mutex_lock( &self->audio_mutex );
2361 // Obtain the frame number of this frame
2362 mlt_position position = mlt_frame_original_position( frame );
2364 // Calculate the real time code
2365 double real_timecode = producer_time_of_frame( self->parent, position );
2367 // Get the producer fps
2368 double fps = mlt_producer_get_fps( self->parent );
2370 // Number of frames to ignore (for ffwd)
2371 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2373 // Flag for paused (silence)
2374 int paused = seek_audio( self, position, real_timecode );
2376 // Initialize ignore for all streams from the seek return value
2377 int i = MAX_AUDIO_STREAMS;
2379 ignore[i] = ignore[0];
2381 // Fetch the audio_format
2382 AVFormatContext *context = self->audio_format;
2384 int sizeof_sample = sizeof( int16_t );
2386 // Determine the tracks to use
2387 int index = self->audio_index;
2388 int index_max = self->audio_index + 1;
2389 if ( self->audio_index == INT_MAX )
2392 index_max = FFMIN( MAX_AUDIO_STREAMS, context->nb_streams );
2393 *channels = self->total_channels;
2394 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2395 *frequency = FFMAX( self->max_frequency, *frequency );
2398 // Initialize the resamplers and buffers
2399 for ( ; index < index_max && index < MAX_AUDIO_STREAMS; index++ )
2401 // Get codec context
2402 AVCodecContext *codec_context = self->audio_codec[ index ];
2404 if ( codec_context && !self->audio_buffer[ index ] )
2406 #if LIBAVCODEC_VERSION_INT < ((54<<16)+(26<<8)+0)
2407 // Check for resample and create if necessary
2408 if ( codec_context->channels <= 2 )
2410 // Determine by how much resampling will increase number of samples
2411 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2412 resample_factor *= (double) *frequency / codec_context->sample_rate;
2413 if ( resample_factor > self->resample_factor )
2414 self->resample_factor = resample_factor;
2416 // Create the resampler
2417 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2418 self->audio_resample[ index ] = av_audio_resample_init(
2419 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2420 codec_context->channels, *frequency, codec_context->sample_rate,
2421 AV_SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2423 self->audio_resample[ index ] = audio_resample_init(
2424 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2425 codec_context->channels, *frequency, codec_context->sample_rate );
2431 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2432 sizeof_sample = sample_bytes( codec_context );
2435 // Check for audio buffer and create if necessary
2436 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2437 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2439 // Check for decoder buffer and create if necessary
2440 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2444 // Get the audio if required
2445 if ( !paused && *frequency > 0 )
2451 av_init_packet( &pkt );
2453 // If not resampling, give consumer more than requested.
2454 // It requested number samples based on requested frame rate.
2455 // Do not clean this up with a samples *= ...!
2456 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2457 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2459 while ( ret >= 0 && !got_audio )
2461 // Check if the buffer already contains the samples required
2462 if ( self->audio_index != INT_MAX &&
2463 self->audio_used[ self->audio_index ] >= *samples &&
2464 ignore[ self->audio_index ] == 0 )
2469 else if ( self->audio_index == INT_MAX )
2471 // Check if there is enough audio for all streams
2473 for ( index = 0; got_audio && index < index_max; index++ )
2474 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2481 pthread_mutex_lock( &self->packets_mutex );
2482 if ( mlt_deque_count( self->apackets ) )
2484 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2490 ret = av_read_frame( context, &pkt );
2491 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2493 if ( !av_dup_packet( &pkt ) )
2495 AVPacket *tmp = malloc( sizeof(AVPacket) );
2497 mlt_deque_push_back( self->vpackets, tmp );
2501 pthread_mutex_unlock( &self->packets_mutex );
2503 // We only deal with audio from the selected audio index
2504 index = pkt.stream_index;
2505 if ( index < MAX_AUDIO_STREAMS && ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2506 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2508 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2509 self->audio_codec[index]->channels : *channels;
2510 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2513 if ( self->seekable || index != self->video_index )
2514 av_free_packet( &pkt );
2518 // Set some additional return values
2519 *format = mlt_audio_s16;
2520 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2522 index = self->audio_index;
2523 *channels = self->audio_codec[ index ]->channels;
2524 *frequency = self->audio_codec[ index ]->sample_rate;
2525 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2526 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2528 else if ( self->audio_index == INT_MAX )
2530 for ( index = 0; index < index_max; index++ )
2531 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2533 // XXX: This only works if all audio tracks have the same sample format.
2534 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2535 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2540 // Allocate and set the frame's audio buffer
2541 int size = mlt_audio_format_size( *format, *samples, *channels );
2542 *buffer = mlt_pool_alloc( size );
2543 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2545 // Interleave tracks if audio_index=all
2546 if ( self->audio_index == INT_MAX )
2548 uint8_t *dest = *buffer;
2550 for ( i = 0; i < *samples; i++ )
2552 for ( index = 0; index < index_max; index++ )
2553 if ( self->audio_codec[ index ] )
2555 int current_channels = self->audio_codec[ index ]->channels;
2556 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2557 memcpy( dest, src, current_channels * sizeof_sample );
2558 dest += current_channels * sizeof_sample;
2561 for ( index = 0; index < index_max; index++ )
2562 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2564 int current_channels = self->audio_codec[ index ]->channels;
2565 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2566 self->audio_used[index] -= *samples;
2567 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2570 // Copy a single track to the output buffer
2573 index = self->audio_index;
2575 // Now handle the audio if we have enough
2576 if ( self->audio_used[ index ] > 0 )
2578 uint8_t *src = self->audio_buffer[ index ];
2579 // copy samples from audio_buffer
2580 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2581 memcpy( *buffer, src, size * *channels * sizeof_sample );
2582 // supply the remaining requested samples as silence
2583 if ( *samples > self->audio_used[ index ] )
2584 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2585 // reposition the samples within audio_buffer
2586 self->audio_used[ index ] -= size;
2587 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2591 // Otherwise fill with silence
2592 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2598 // Get silence and don't touch the context
2599 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2602 // Regardless of speed (other than paused), we expect to get the next frame
2604 self->audio_expected = position + 1;
2606 pthread_mutex_unlock( &self->audio_mutex );
2611 /** Initialize the audio codec context.
2614 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2616 // Initialise the codec if necessary
2617 if ( !self->audio_codec[ index ] )
2619 // Get codec context
2620 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2623 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2625 // If we don't have a codec and we can't initialise it, we can't do much more...
2626 pthread_mutex_lock( &self->open_mutex );
2627 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2628 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2630 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2633 // Now store the codec with its destructor
2634 if ( self->audio_codec[ index ] )
2635 avcodec_close( self->audio_codec[ index ] );
2636 self->audio_codec[ index ] = codec_context;
2640 // Remember that we can't use self later
2641 self->audio_index = -1;
2643 pthread_mutex_unlock( &self->open_mutex );
2645 // Process properties as AVOptions
2646 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2647 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
2648 if ( codec && codec->priv_class && codec_context->priv_data )
2649 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2652 return self->audio_codec[ index ] && self->audio_index > -1;
2655 /** Set up audio handling.
2658 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2661 mlt_producer producer = self->parent;
2663 // Get the properties
2664 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2666 // Fetch the audio format context
2667 AVFormatContext *context = self->audio_format;
2669 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2671 // Get the audio_index
2672 int index = mlt_properties_get_int( properties, "audio_index" );
2674 // Handle all audio tracks
2675 if ( self->audio_index > -1 &&
2676 mlt_properties_get( properties, "audio_index" ) &&
2677 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2680 // Reopen the file if necessary
2681 if ( !context && self->audio_index > -1 && index > -1 )
2683 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2684 mlt_properties_get( properties, "resource" ), 1 );
2685 context = self->audio_format;
2688 // Exception handling for audio_index
2689 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2691 for ( index = context->nb_streams - 1;
2692 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2694 mlt_properties_set_int( properties, "audio_index", index );
2696 if ( context && index > -1 && index < INT_MAX &&
2697 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2699 index = self->audio_index;
2700 mlt_properties_set_int( properties, "audio_index", index );
2702 if ( context && index > -1 && index < INT_MAX &&
2703 pick_audio_format( context->streams[ index ]->codec->sample_fmt ) == mlt_audio_none )
2708 // Update the audio properties if the index changed
2709 if ( context && index > -1 && index != self->audio_index )
2711 pthread_mutex_lock( &self->open_mutex );
2712 if ( self->audio_codec[ self->audio_index ] )
2713 avcodec_close( self->audio_codec[ self->audio_index ] );
2714 self->audio_codec[ self->audio_index ] = NULL;
2715 pthread_mutex_unlock( &self->open_mutex );
2717 if ( self->audio_index != -1 )
2718 self->audio_index = index;
2723 if ( context && index == INT_MAX )
2725 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2726 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2727 for ( index = 0; index < context->nb_streams; index++ )
2729 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2730 audio_codec_init( self, index, properties );
2733 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2735 // Set the frame properties
2736 if ( index < MAX_AUDIO_STREAMS )
2738 mlt_properties_set_int( frame_properties, "audio_frequency", self->audio_codec[ index ]->sample_rate );
2739 mlt_properties_set_int( frame_properties, "audio_channels", self->audio_codec[ index ]->channels );
2742 if ( context && index > -1 )
2744 // Add our audio operation
2745 mlt_frame_push_audio( frame, self );
2746 mlt_frame_push_audio( frame, producer_get_audio );
2750 /** Our get frame implementation.
2753 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2755 // Access the private data
2756 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2757 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2758 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2763 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2764 producer->child = self;
2765 self->parent = producer;
2766 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2767 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2770 // Create an empty frame
2771 *frame = mlt_frame_init( service);
2775 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2779 mlt_cache_item_close( cache_item );
2783 // Update timecode on the frame we're creating
2784 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2787 producer_set_up_video( self, *frame );
2790 producer_set_up_audio( self, *frame );
2792 // Set the position of this producer
2793 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2794 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "original_position", position );
2796 // Calculate the next timecode
2797 mlt_producer_prepare_next( producer );
2802 static void producer_avformat_close( producer_avformat self )
2804 mlt_log_debug( NULL, "producer_avformat_close\n" );
2806 // Cleanup av contexts
2807 av_free_packet( &self->pkt );
2808 av_free( self->av_frame );
2809 pthread_mutex_lock( &self->open_mutex );
2811 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2813 if ( self->audio_resample[i] )
2814 audio_resample_close( self->audio_resample[i] );
2815 mlt_pool_release( self->audio_buffer[i] );
2816 av_free( self->decode_buffer[i] );
2817 if ( self->audio_codec[i] )
2818 avcodec_close( self->audio_codec[i] );
2819 self->audio_codec[i] = NULL;
2821 if ( self->video_codec )
2822 avcodec_close( self->video_codec );
2823 self->video_codec = NULL;
2825 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2826 if ( self->dummy_context )
2827 avformat_close_input( &self->dummy_context );
2828 if ( self->seekable && self->audio_format )
2829 avformat_close_input( &self->audio_format );
2830 if ( self->video_format )
2831 avformat_close_input( &self->video_format );
2833 if ( self->dummy_context )
2834 av_close_input_file( self->dummy_context );
2835 if ( self->seekable && self->audio_format )
2836 av_close_input_file( self->audio_format );
2837 if ( self->video_format )
2838 av_close_input_file( self->video_format );
2840 pthread_mutex_unlock( &self->open_mutex );
2842 vdpau_producer_close( self );
2844 if ( self->image_cache )
2845 mlt_cache_close( self->image_cache );
2847 // Cleanup the mutexes
2848 if ( self->is_mutex_init )
2850 pthread_mutex_destroy( &self->audio_mutex );
2851 pthread_mutex_destroy( &self->video_mutex );
2852 pthread_mutex_destroy( &self->packets_mutex );
2853 pthread_mutex_destroy( &self->open_mutex );
2856 // Cleanup the packet queues
2858 if ( self->apackets )
2860 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2862 av_free_packet( pkt );
2865 mlt_deque_close( self->apackets );
2866 self->apackets = NULL;
2868 if ( self->vpackets )
2870 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2872 av_free_packet( pkt );
2875 mlt_deque_close( self->vpackets );
2876 self->vpackets = NULL;
2882 static void producer_close( mlt_producer parent )
2884 // Remove this instance from the cache
2885 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2888 parent->close = NULL;
2889 mlt_producer_close( parent );