2 * producer_avformat.c -- avformat producer
3 * Copyright (C) 2003-2009 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>
37 #if LIBAVCODEC_VERSION_MAJOR > 52
38 #include <libavutil/samplefmt.h>
39 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
40 const char *avcodec_get_sample_fmt_name(int sample_fmt);
43 # include <libavcodec/vdpau.h>
45 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
46 # include <libavutil/pixdesc.h>
49 // System header files
55 #if LIBAVUTIL_VERSION_INT < (50<<16)
56 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
57 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
60 #if LIBAVCODEC_VERSION_MAJOR > 52
61 #include <libavutil/opt.h>
62 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
63 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
64 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
66 #include <libavcodec/opt.h>
69 #define POSITION_INITIAL (-2)
70 #define POSITION_INVALID (-1)
72 #define MAX_AUDIO_STREAMS (10)
73 #define MAX_VDPAU_SURFACES (10)
75 void avformat_lock( );
76 void avformat_unlock( );
78 struct producer_avformat_s
81 AVFormatContext *dummy_context;
82 AVFormatContext *audio_format;
83 AVFormatContext *video_format;
84 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
85 AVCodecContext *video_codec;
87 ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
88 mlt_position audio_expected;
89 mlt_position video_expected;
99 int16_t *audio_buffer[ MAX_AUDIO_STREAMS ];
100 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
101 int16_t *decode_buffer[ MAX_AUDIO_STREAMS ];
102 int audio_used[ MAX_AUDIO_STREAMS ];
104 int audio_max_stream;
108 unsigned int invalid_pts_counter;
109 double resample_factor;
110 mlt_cache image_cache;
112 pthread_mutex_t video_mutex;
113 pthread_mutex_t audio_mutex;
118 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
129 typedef struct producer_avformat_s *producer_avformat;
131 // Forward references.
132 static int producer_open( producer_avformat self, mlt_profile profile, char *file );
133 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
134 static void producer_avformat_close( producer_avformat );
135 static void producer_close( mlt_producer parent );
136 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
137 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
138 static void apply_properties( void *obj, mlt_properties properties, int flags );
139 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
145 /** Constructor for libavformat.
148 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
152 // Report information about available demuxers and codecs as YAML Tiny
153 if ( file && strstr( file, "f-list" ) )
155 fprintf( stderr, "---\nformats:\n" );
156 AVInputFormat *format = NULL;
157 while ( ( format = av_iformat_next( format ) ) )
158 fprintf( stderr, " - %s\n", format->name );
159 fprintf( stderr, "...\n" );
162 if ( file && strstr( file, "acodec-list" ) )
164 fprintf( stderr, "---\naudio_codecs:\n" );
165 AVCodec *codec = NULL;
166 while ( ( codec = av_codec_next( codec ) ) )
167 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
168 fprintf( stderr, " - %s\n", codec->name );
169 fprintf( stderr, "...\n" );
172 if ( file && strstr( file, "vcodec-list" ) )
174 fprintf( stderr, "---\nvideo_codecs:\n" );
175 AVCodec *codec = NULL;
176 while ( ( codec = av_codec_next( codec ) ) )
177 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
178 fprintf( stderr, " - %s\n", codec->name );
179 fprintf( stderr, "...\n" );
183 // Check that we have a non-NULL argument
186 // Construct the producer
187 mlt_producer producer = calloc( 1, sizeof( struct mlt_producer_s ) );
188 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
191 if ( mlt_producer_init( producer, self ) == 0 )
193 self->parent = producer;
195 // Get the properties
196 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
198 // Set the resource property (required for all producers)
199 mlt_properties_set( properties, "resource", file );
201 // Register transport implementation with the producer
202 producer->close = (mlt_destructor) producer_close;
204 // Register our get_frame implementation
205 producer->get_frame = producer_get_frame;
207 if ( strcmp( service, "avformat-novalidate" ) )
210 if ( producer_open( self, profile, file ) != 0 )
213 mlt_producer_close( producer );
218 // Close the file to release resources for large playlists - reopen later as needed
220 if ( self->dummy_context )
221 av_close_input_file( self->dummy_context );
222 self->dummy_context = NULL;
223 if ( self->audio_format )
224 av_close_input_file( self->audio_format );
225 self->audio_format = NULL;
226 if ( self->video_format )
227 av_close_input_file( self->video_format );
228 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 );
236 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
238 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
244 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
246 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
254 /** Find the default streams.
257 static mlt_properties find_default_streams( mlt_properties meta_media, AVFormatContext *context, int *audio_index, int *video_index )
261 AVMetadataTag *tag = NULL;
263 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
265 // Allow for multiple audio and video streams in the file and select first of each (if available)
266 for( i = 0; i < context->nb_streams; i++ )
268 // Get the codec context
269 AVStream *stream = context->streams[ i ];
270 if ( ! stream ) continue;
271 AVCodecContext *codec_context = stream->codec;
272 if ( ! codec_context ) continue;
273 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
274 if ( ! codec ) continue;
276 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
278 // Determine the type and obtain the first index of each type
279 switch( codec_context->codec_type )
281 case CODEC_TYPE_VIDEO:
282 if ( *video_index < 0 )
284 mlt_properties_set( meta_media, key, "video" );
285 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
286 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
287 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
288 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
289 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
290 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
292 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
295 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
296 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
297 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
299 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
300 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
301 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
302 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
303 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
304 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
305 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
306 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
307 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
308 switch ( codec_context->colorspace )
310 case AVCOL_SPC_SMPTE240M:
311 mlt_properties_set_int( meta_media, key, 240 );
313 case AVCOL_SPC_BT470BG:
314 case AVCOL_SPC_SMPTE170M:
315 mlt_properties_set_int( meta_media, key, 601 );
317 case AVCOL_SPC_BT709:
318 mlt_properties_set_int( meta_media, key, 709 );
321 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
322 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
327 case CODEC_TYPE_AUDIO:
328 if ( *audio_index < 0 )
330 mlt_properties_set( meta_media, key, "audio" );
331 #if LIBAVCODEC_VERSION_MAJOR > 52
332 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
333 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
334 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
335 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
336 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
338 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
339 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
340 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
341 mlt_properties_set_int( meta_media, key, codec_context->channels );
346 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
347 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
348 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
349 mlt_properties_set( meta_media, key, codec->name );
350 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
351 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
352 mlt_properties_set( meta_media, key, codec->long_name );
354 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
355 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
356 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
357 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
358 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
359 // mlt_properties_set_int( meta_media, key, codec_context->profile );
360 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
361 // mlt_properties_set_int( meta_media, key, codec_context->level );
364 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
365 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
367 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
369 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
370 mlt_properties_set( meta_media, key, tag->value );
375 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
376 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
378 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
380 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
381 mlt_properties_set( meta_media, key, tag->value );
385 if ( context->title && strcmp( context->title, "" ) )
386 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
387 if ( context->author && strcmp( context->author, "" ) )
388 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
389 if ( context->copyright && strcmp( context->copyright, "" ) )
390 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
391 if ( context->comment )
392 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
393 if ( context->album )
394 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
396 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
397 if ( context->track )
398 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
404 static inline int dv_is_pal( AVPacket *pkt )
406 return pkt->data[3] & 0x80;
409 static int dv_is_wide( AVPacket *pkt )
411 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
413 for ( ; i < pkt->size; i += 5 /* packet size */ )
415 if ( pkt->data[ i ] == 0x61 )
417 uint8_t x = pkt->data[ i + 2 ] & 0x7;
418 return ( x == 2 ) || ( x == 7 );
424 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
426 double aspect_ratio = 1.0;
428 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
432 if ( dv_is_pal( pkt ) )
434 if ( dv_is_wide( pkt ) )
436 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
437 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
441 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
442 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
447 if ( dv_is_wide( pkt ) )
449 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
450 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
454 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
455 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
462 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
463 stream->sample_aspect_ratio;
465 codec_context->sample_aspect_ratio;
467 // Override FFmpeg's notion of DV aspect ratios, which are
468 // based upon a width of 704. Since we do not have a normaliser
469 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
470 // we just coerce the values to facilitate a passive behaviour through
471 // the rescale normaliser when using equivalent producers and consumers.
472 // = display_aspect / (width * height)
473 if ( ar.num == 10 && ar.den == 11 )
476 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
477 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
479 else if ( ar.num == 59 && ar.den == 54 )
482 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
483 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
485 else if ( ar.num == 40 && ar.den == 33 )
488 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
489 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
491 else if ( ar.num == 118 && ar.den == 81 )
494 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
495 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
501 AVRational codec_sar = codec_context->sample_aspect_ratio;
502 AVRational stream_sar =
503 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
504 stream->sample_aspect_ratio;
508 if ( codec_sar.num > 0 )
510 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
511 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
513 else if ( stream_sar.num > 0 )
515 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
516 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
520 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
521 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
524 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
525 aspect_ratio = av_q2d( ar );
526 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
534 static int producer_open( producer_avformat self, mlt_profile profile, char *file )
536 // Return an error code (0 == no error)
539 // Context for avformat
540 AVFormatContext *context = NULL;
542 // Get the properties
543 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
545 // We will treat everything with the producer fps
546 double fps = mlt_profile_fps( profile );
549 pthread_mutex_init( &self->audio_mutex, NULL );
550 pthread_mutex_init( &self->video_mutex, NULL );
551 pthread_mutex_lock( &self->audio_mutex );
552 pthread_mutex_lock( &self->video_mutex );
554 // If "MRL", then create AVInputFormat
555 AVInputFormat *format = NULL;
556 AVFormatParameters *params = NULL;
557 char *standard = NULL;
558 char *mrl = strchr( file, ':' );
560 // AV option (0 = both, 1 = video, 2 = audio)
563 // Only if there is not a protocol specification that avformat can handle
564 #if LIBAVFORMAT_VERSION_MAJOR > 52
565 if ( mrl && !avio_check( file, 0 ) )
567 if ( mrl && !url_exist( file ) )
570 // 'file' becomes format abbreviation
574 format = av_find_input_format( file );
576 // Eat the format designator
582 params = calloc( sizeof( AVFormatParameters ), 1 );
584 // These are required by video4linux (defaults)
586 params->height = 480;
587 params->time_base= (AVRational){1,25};
588 params->channels = 2;
589 params->sample_rate = 48000;
593 mrl = strchr( file, '?' );
597 char *name = strdup( ++mrl );
598 char *value = strchr( name, ':' );
603 char *t = strchr( value, '&' );
606 if ( !strcmp( name, "frame_rate" ) )
607 params->time_base.den = atoi( value );
608 else if ( !strcmp( name, "frame_rate_base" ) )
609 params->time_base.num = atoi( value );
610 else if ( !strcmp( name, "sample_rate" ) )
611 params->sample_rate = atoi( value );
612 else if ( !strcmp( name, "channel" ) )
613 params->channel = atoi( value );
614 else if ( !strcmp( name, "channels" ) )
615 params->channels = atoi( value );
616 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
617 else if ( !strcmp( name, "pix_fmt" ) )
618 params->pix_fmt = av_get_pix_fmt( value );
620 else if ( !strcmp( name, "width" ) )
621 params->width = atoi( value );
622 else if ( !strcmp( name, "height" ) )
623 params->height = atoi( value );
624 else if ( !strcmp( name, "standard" ) )
626 standard = strdup( value );
627 params->standard = standard;
629 else if ( !strcmp( name, "av" ) )
633 mrl = strchr( mrl, '&' );
637 // Now attempt to open the file
638 error = av_open_input_file( &context, file, format, 0, params ) < 0;
640 // Cleanup AVFormatParameters
644 // If successful, then try to get additional info
647 // Get the stream info
648 error = av_find_stream_info( context ) < 0;
650 // Continue if no error
653 // We will default to the first audio and video streams found
654 int audio_index = -1;
655 int video_index = -1;
657 // Find default audio and video streams
658 find_default_streams( properties, context, &audio_index, &video_index );
660 // Now set properties where we can (use default unknowns if required)
661 if ( context->duration != AV_NOPTS_VALUE )
663 // This isn't going to be accurate for all formats
664 // Workaround some clips whose estimated duration cause problems:
665 // http://www.kdenlive.org/mantis/view.php?id=2003
667 if ( mlt_properties_get( properties, "adjust_length" ) )
668 adjust = mlt_properties_get_int( properties, "adjust_length" );
669 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps + adjust );
670 if ( mlt_properties_get_position( properties, "force_length" ) > 0 )
671 frames = mlt_properties_get_position( properties, "force_length" );
672 mlt_properties_set_position( properties, "out", frames - 1 );
673 mlt_properties_set_position( properties, "length", frames );
676 if ( context->start_time != AV_NOPTS_VALUE )
677 self->start_time = context->start_time;
679 // Check if we're seekable
680 // avdevices are typically AVFMT_NOFILE and not seekable
681 self->seekable = !format || !( format->flags & AVFMT_NOFILE );
684 // protocols can indicate if they support seeking
685 #if LIBAVFORMAT_VERSION_MAJOR > 52
686 self->seekable = context->pb->seekable;
688 URLContext *uc = url_fileno( context->pb );
690 self->seekable = !uc->is_streamed;
693 if ( self->seekable )
695 self->seekable = av_seek_frame( context, -1, self->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
696 mlt_properties_set_int( properties, "seekable", self->seekable );
697 self->dummy_context = context;
698 av_open_input_file( &context, file, NULL, 0, NULL );
699 av_find_stream_info( context );
702 // Store selected audio and video indexes on properties
703 self->audio_index = audio_index;
704 self->video_index = video_index;
705 self->first_pts = -1;
706 self->last_position = POSITION_INITIAL;
708 // Fetch the width, height and aspect ratio
709 if ( video_index != -1 )
711 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
712 mlt_properties_set_int( properties, "width", codec_context->width );
713 mlt_properties_set_int( properties, "height", codec_context->height );
715 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
717 // Fetch the first frame of DV so we can read it directly
722 ret = av_read_frame( context, &pkt );
723 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
725 get_aspect_ratio( properties, context->streams[ video_index ], codec_context, &pkt );
732 get_aspect_ratio( properties, context->streams[ video_index ], codec_context, NULL );
735 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
736 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
738 sws_freeContext( context );
744 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
745 if ( av == 0 && audio_index != -1 && video_index != -1 )
747 // We'll use the open one as our video_format
748 self->video_format = context;
750 // And open again for our audio context
751 av_open_input_file( &context, file, NULL, 0, NULL );
752 av_find_stream_info( context );
755 self->audio_format = context;
757 else if ( av != 2 && video_index != -1 )
759 // We only have a video context
760 self->video_format = context;
762 else if ( audio_index != -1 )
764 // We only have an audio context
765 self->audio_format = context;
769 // Something has gone wrong
775 // Unlock the service
776 pthread_mutex_unlock( &self->audio_mutex );
777 pthread_mutex_unlock( &self->video_mutex );
782 void reopen_video( producer_avformat self, mlt_producer producer, mlt_properties properties )
784 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
785 pthread_mutex_lock( &self->audio_mutex );
787 if ( self->video_codec )
790 avcodec_close( self->video_codec );
793 self->video_codec = NULL;
794 if ( self->dummy_context )
795 av_close_input_file( self->dummy_context );
796 self->dummy_context = NULL;
797 if ( self->video_format )
798 av_close_input_file( self->video_format );
799 self->video_format = NULL;
801 int audio_index = self->audio_index;
802 int video_index = self->video_index;
804 mlt_events_block( properties, producer );
805 pthread_mutex_unlock( &self->audio_mutex );
806 pthread_mutex_unlock( &self->video_mutex );
807 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
808 mlt_properties_get( properties, "resource" ) );
809 pthread_mutex_lock( &self->video_mutex );
810 pthread_mutex_lock( &self->audio_mutex );
811 if ( self->dummy_context )
813 av_close_input_file( self->dummy_context );
814 self->dummy_context = NULL;
816 mlt_events_unblock( properties, producer );
817 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
818 #if LIBAVFORMAT_VERSION_MAJOR > 52
819 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
820 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
823 self->audio_index = audio_index;
824 if ( self->video_format && video_index > -1 )
826 self->video_index = video_index;
827 video_codec_init( self, video_index, properties );
830 pthread_mutex_unlock( &self->audio_mutex );
831 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
834 /** Convert a frame position to a time code.
837 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
839 return ( double )position / mlt_producer_get_fps( producer );
842 // Collect information about all audio streams
844 static void get_audio_streams_info( producer_avformat self )
846 // Fetch the audio format context
847 AVFormatContext *context = self->audio_format;
851 i < context->nb_streams;
854 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
856 AVCodecContext *codec_context = context->streams[i]->codec;
857 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
859 // If we don't have a codec and we can't initialise it, we can't do much more...
861 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
863 self->audio_streams++;
864 self->audio_max_stream = i;
865 self->total_channels += codec_context->channels;
866 if ( codec_context->channels > self->max_channel )
867 self->max_channel = codec_context->channels;
868 if ( codec_context->sample_rate > self->max_frequency )
869 self->max_frequency = codec_context->sample_rate;
870 avcodec_close( codec_context );
875 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
876 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
878 // Other audio-specific initializations
879 self->resample_factor = 1.0;
882 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
884 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
886 const int *new_coefficients;
888 int brightness, contrast, saturation;
890 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
891 &brightness, &contrast, &saturation ) != -1 )
893 // Don't change these from defaults unless explicitly told to.
894 if ( use_full_range >= 0 )
895 full_range = use_full_range;
896 switch ( colorspace )
902 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
905 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
908 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
911 new_coefficients = coefficients;
914 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
915 brightness, contrast, saturation );
920 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
921 mlt_image_format *format, int width, int height, int colorspace )
925 int flags = SWS_BILINEAR | SWS_ACCURATE_RND;
928 flags |= SWS_CPU_CAPS_MMX;
931 flags |= SWS_CPU_CAPS_MMX2;
934 if ( pix_fmt == PIX_FMT_RGB32 )
936 *format = mlt_image_rgb24a;
937 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
938 width, height, PIX_FMT_RGBA, flags, NULL, NULL, NULL);
940 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
941 set_luma_transfer( context, colorspace, full_range );
942 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
943 output.data, output.linesize);
944 sws_freeContext( context );
946 else if ( *format == mlt_image_yuv420p )
948 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
949 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
951 output.data[0] = buffer;
952 output.data[1] = buffer + width * height;
953 output.data[2] = buffer + ( 5 * width * height ) / 4;
954 output.linesize[0] = width;
955 output.linesize[1] = width >> 1;
956 output.linesize[2] = width >> 1;
957 set_luma_transfer( context, colorspace, full_range );
958 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
959 output.data, output.linesize);
960 sws_freeContext( context );
962 else if ( *format == mlt_image_rgb24 )
964 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
965 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
967 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
968 set_luma_transfer( context, colorspace, full_range );
969 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
970 output.data, output.linesize);
971 sws_freeContext( context );
973 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
975 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
976 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
978 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
979 set_luma_transfer( context, colorspace, full_range );
980 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
981 output.data, output.linesize);
982 sws_freeContext( context );
986 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
987 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
989 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
990 set_luma_transfer( context, colorspace, full_range );
991 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
992 output.data, output.linesize);
993 sws_freeContext( context );
996 if ( *format == mlt_image_yuv420p )
999 pict.data[0] = buffer;
1000 pict.data[1] = buffer + width * height;
1001 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1002 pict.linesize[0] = width;
1003 pict.linesize[1] = width >> 1;
1004 pict.linesize[2] = width >> 1;
1005 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1007 else if ( *format == mlt_image_rgb24 )
1010 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1011 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1013 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
1016 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1017 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1022 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1023 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1028 /** Allocate the image buffer and set it on the frame.
1031 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1035 if ( codec_context->width == 0 || codec_context->height == 0 )
1038 *width = codec_context->width;
1039 *height = codec_context->height;
1041 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
1042 size = *width * ( *height + 1 ) * 4;
1044 size = mlt_image_format_size( *format, *width, *height, NULL );
1046 // Construct the output image
1047 *buffer = mlt_pool_alloc( size );
1049 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1056 /** Get an image from a frame.
1059 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1062 producer_avformat self = mlt_frame_pop_service( frame );
1063 mlt_producer producer = self->parent;
1065 // Get the properties from the frame
1066 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1068 // Obtain the frame number of this frame
1069 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1071 // Get the producer properties
1072 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1074 pthread_mutex_lock( &self->video_mutex );
1076 // Fetch the video format context
1077 AVFormatContext *context = self->video_format;
1079 // Get the video stream
1080 AVStream *stream = context->streams[ self->video_index ];
1082 // Get codec context
1083 AVCodecContext *codec_context = stream->codec;
1085 // Get the image cache
1086 if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1087 self->image_cache = mlt_cache_init();
1088 if ( self->image_cache )
1090 mlt_cache_item item = mlt_cache_get( self->image_cache, (void*) position );
1091 uint8_t *original = mlt_cache_item_data( item, (int*) format );
1094 // Set the resolution
1095 *width = codec_context->width;
1096 *height = codec_context->height;
1098 // Workaround 1088 encodings missing cropping info.
1099 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1103 int size = mlt_image_format_size( *format, *width, *height, NULL );
1106 *buffer = mlt_pool_alloc( size );
1107 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1108 memcpy( *buffer, original, size );
1109 mlt_cache_item_close( item );
1114 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1115 mlt_frame_set_image( frame, *buffer, size, NULL );
1117 self->got_picture = 1;
1119 goto exit_get_image;
1128 // Special case pause handling flag
1131 // Special case ffwd handling
1134 // We may want to use the source fps if available
1135 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1136 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1137 double fps = mlt_producer_get_fps( producer );
1139 // This is the physical frame position in the source
1140 int req_position = ( int )( position / fps * source_fps + 0.5 );
1142 // Determines if we have to decode all frames in a sequence
1143 // Temporary hack to improve intra frame only
1144 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
1145 strcmp( codec_context->codec->name, "dvvideo" ) &&
1146 strcmp( codec_context->codec->name, "huffyuv" ) &&
1147 strcmp( codec_context->codec->name, "mjpeg" ) &&
1148 strcmp( codec_context->codec->name, "rawvideo" );
1150 int last_position = self->last_position;
1152 // Turn on usage of new seek API and PTS for seeking
1153 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1154 if ( mlt_properties_get( properties, "new_seek" ) )
1155 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1157 // Seek if necessary
1158 if ( position != self->video_expected || last_position < 0 )
1160 if ( self->av_frame && position + 1 == self->video_expected )
1162 // We're paused - use last image
1165 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
1167 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1168 ignore = ( int )( ( position - self->video_expected ) / fps * source_fps );
1169 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1171 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || last_position < 0 ) )
1173 if ( use_new_seek && last_position == POSITION_INITIAL )
1175 // find first key frame
1179 while ( ret >= 0 && toscan-- > 0 )
1181 ret = av_read_frame( context, &pkt );
1182 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
1184 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n", pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
1185 self->first_pts = pkt.pts;
1188 av_free_packet( &pkt );
1191 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1194 // Calculate the timestamp for the requested frame
1198 timestamp = ( req_position - 0.1 / source_fps ) /
1199 ( av_q2d( stream->time_base ) * source_fps );
1200 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %"PRId64" ", req_position, timestamp );
1201 if ( self->first_pts > 0 )
1202 timestamp += self->first_pts;
1203 else if ( context->start_time != AV_NOPTS_VALUE )
1204 timestamp += context->start_time;
1208 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
1209 if ( context->start_time != AV_NOPTS_VALUE )
1210 timestamp += context->start_time;
1213 timestamp -= AV_TIME_BASE;
1214 if ( timestamp < 0 )
1216 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %d\n",
1217 timestamp, position, self->video_expected, last_position );
1219 // Seek to the timestamp
1222 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1223 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1225 else if ( req_position > 0 || last_position <= 0 )
1227 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
1231 // Re-open video stream when rewinding to beginning from somewhere else.
1232 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1233 // not reliably seeking to the first frame across formats.
1234 reopen_video( self, producer, properties );
1235 context = self->video_format;
1236 stream = context->streams[ self->video_index ];
1237 codec_context = stream->codec;
1240 // Remove the cached info relating to the previous position
1241 self->current_position = POSITION_INVALID;
1242 self->last_position = POSITION_INVALID;
1243 av_freep( &self->av_frame );
1247 // flush any pictures still in decode buffer
1248 avcodec_flush_buffers( codec_context );
1253 // Duplicate the last image if necessary
1254 if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture && self->seekable
1256 || self->current_position == req_position
1257 || ( !use_new_seek && self->current_position > req_position ) ) )
1260 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1262 // Workaround 1088 encodings missing cropping info.
1263 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1266 if ( self->vdpau && self->vdpau->buffer )
1269 picture.data[0] = self->vdpau->buffer;
1270 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1271 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1272 picture.linesize[0] = codec_context->width;
1273 picture.linesize[1] = codec_context->width / 2;
1274 picture.linesize[2] = codec_context->width / 2;
1275 convert_image( (AVFrame*) &picture, *buffer,
1276 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1280 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1281 format, *width, *height, self->colorspace );
1284 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1289 int int_position = 0;
1290 int decode_errors = 0;
1291 int got_picture = 0;
1293 av_init_packet( &pkt );
1295 // Construct an AVFrame for YUV422 conversion
1296 if ( !self->av_frame )
1297 self->av_frame = avcodec_alloc_frame( );
1299 while( ret >= 0 && !got_picture )
1302 ret = av_read_frame( context, &pkt );
1304 // We only deal with video from the selected video_index
1305 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1307 // Determine time code of the packet
1310 int64_t pts = pkt.pts;
1311 if ( self->first_pts > 0 )
1312 pts -= self->first_pts;
1313 else if ( context->start_time != AV_NOPTS_VALUE )
1314 pts -= context->start_time;
1315 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1316 if ( pkt.pts == AV_NOPTS_VALUE )
1318 self->invalid_pts_counter++;
1319 if ( self->invalid_pts_counter > 20 )
1321 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1322 mlt_properties_set_int( properties, "new_seek", 0 );
1323 int_position = req_position;
1329 self->invalid_pts_counter = 0;
1331 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1332 pkt.pts, req_position, self->current_position, int_position );
1336 if ( self->seekable && pkt.dts != AV_NOPTS_VALUE )
1338 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1339 if ( context->start_time != AV_NOPTS_VALUE )
1340 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1341 last_position = self->last_position;
1342 if ( int_position == last_position )
1343 int_position = last_position + 1;
1347 int_position = req_position;
1349 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1350 pkt.dts, req_position, self->current_position, int_position );
1351 // Make a dumb assumption on streams that contain wild timestamps
1352 if ( abs( req_position - int_position ) > 999 )
1354 int_position = req_position;
1355 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1358 self->last_position = int_position;
1361 if ( must_decode || int_position >= req_position )
1364 if ( g_vdpau && self->vdpau )
1366 if ( g_vdpau->producer != self )
1368 vdpau_decoder_close();
1369 vdpau_decoder_init( self );
1372 self->vdpau->is_decoded = 0;
1375 codec_context->reordered_opaque = pkt.pts;
1376 if ( int_position >= req_position )
1377 codec_context->skip_loop_filter = AVDISCARD_NONE;
1378 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1379 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1381 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1383 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1386 if ( ++decode_errors <= 10 )
1399 // Determine time code of the packet
1400 int64_t pts = self->av_frame->reordered_opaque;
1401 if ( self->first_pts > 0 )
1402 pts -= self->first_pts;
1403 else if ( context->start_time != AV_NOPTS_VALUE )
1404 pts -= context->start_time;
1405 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1406 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, self->av_frame->key_frame );
1409 if ( int_position < req_position )
1414 else if ( int_position >= req_position )
1417 codec_context->skip_loop_filter = AVDISCARD_NONE;
1419 else if ( ignore -- )
1424 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1427 // Now handle the picture if we have one
1430 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1432 // Workaround 1088 encodings missing cropping info.
1433 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1438 if ( self->vdpau->is_decoded )
1440 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1442 uint32_t pitches[3];
1443 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1445 if ( !self->vdpau->buffer )
1446 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1447 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1448 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1449 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1450 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1451 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1452 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1454 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1455 if ( status == VDP_STATUS_OK )
1457 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1458 format, *width, *height, self->colorspace );
1462 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1463 image_size = self->vdpau->is_decoded = 0;
1468 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1469 image_size = got_picture = 0;
1474 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1475 format, *width, *height, self->colorspace );
1476 self->top_field_first |= self->av_frame->top_field_first;
1477 self->current_position = int_position;
1478 self->got_picture = 1;
1486 av_free_packet( &pkt );
1490 if ( self->got_picture && image_size > 0 && self->image_cache )
1492 // Copy buffer to image cache
1493 uint8_t *image = mlt_pool_alloc( image_size );
1494 memcpy( image, *buffer, image_size );
1495 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1497 // Try to duplicate last image if there was a decoding failure
1498 else if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1501 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1503 // Workaround 1088 encodings missing cropping info.
1504 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1507 if ( self->vdpau && self->vdpau->buffer )
1510 picture.data[0] = self->vdpau->buffer;
1511 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1512 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1513 picture.linesize[0] = codec_context->width;
1514 picture.linesize[1] = codec_context->width / 2;
1515 picture.linesize[2] = codec_context->width / 2;
1516 convert_image( (AVFrame*) &picture, *buffer,
1517 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1521 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1522 format, *width, *height, self->colorspace );
1523 self->got_picture = 1;
1526 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1529 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1530 self->video_expected = position + 1;
1534 pthread_mutex_unlock( &self->video_mutex );
1536 // Set the progressive flag
1537 if ( mlt_properties_get( properties, "force_progressive" ) )
1538 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1539 else if ( self->av_frame )
1540 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1542 // Set the field order property for this frame
1543 if ( mlt_properties_get( properties, "force_tff" ) )
1544 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1546 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1548 // Set immutable properties of the selected track's (or overridden) source attributes.
1549 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1550 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1551 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1552 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1554 return !self->got_picture;
1557 /** Process properties as AVOptions and apply to AV context obj
1560 static void apply_properties( void *obj, mlt_properties properties, int flags )
1563 int count = mlt_properties_count( properties );
1564 for ( i = 0; i < count; i++ )
1566 const char *opt_name = mlt_properties_get_name( properties, i );
1567 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1568 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1571 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1572 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1573 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1574 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1576 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1582 /** Initialize the video codec context.
1585 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1587 // Initialise the codec if necessary
1588 if ( !self->video_codec )
1590 // Get the video stream
1591 AVStream *stream = self->video_format->streams[ index ];
1593 // Get codec context
1594 AVCodecContext *codec_context = stream->codec;
1597 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1599 if ( codec_context->codec_id == CODEC_ID_H264 )
1601 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1603 if ( vdpau_init( self ) )
1605 self->video_codec = codec_context;
1606 if ( !vdpau_decoder_init( self ) )
1607 vdpau_decoder_close();
1611 codec = avcodec_find_decoder( codec_context->codec_id );
1615 // Initialise multi-threading
1616 int thread_count = mlt_properties_get_int( properties, "threads" );
1617 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1618 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1619 if ( thread_count > 1 )
1620 codec_context->thread_count = thread_count;
1622 // If we don't have a codec and we can't initialise it, we can't do much more...
1624 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1626 // Now store the codec with its destructor
1627 self->video_codec = codec_context;
1631 // Remember that we can't use this later
1632 self->video_index = -1;
1638 // Process properties as AVOptions
1639 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1640 #if LIBAVCODEC_VERSION_MAJOR > 52
1641 if ( codec->priv_class && codec_context->priv_data )
1642 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1645 // Reset some image properties
1646 mlt_properties_set_int( properties, "width", self->video_codec->width );
1647 mlt_properties_set_int( properties, "height", self->video_codec->height );
1648 // For DV, we'll just use the saved aspect ratio
1649 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1650 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1652 // Determine the fps first from the codec
1653 double source_fps = (double) self->video_codec->time_base.den /
1654 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1656 if ( mlt_properties_get( properties, "force_fps" ) )
1658 source_fps = mlt_properties_get_double( properties, "force_fps" );
1659 stream->time_base = av_d2q( source_fps, 1024 );
1660 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1661 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1665 // If the muxer reports a frame rate different than the codec
1666 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1667 double muxer_fps = av_q2d( stream->avg_frame_rate );
1668 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1669 muxer_fps = av_q2d( stream->r_frame_rate );
1671 double muxer_fps = av_q2d( stream->r_frame_rate );
1673 // Choose the lesser - the wrong tends to be off by some multiple of 10
1674 source_fps = FFMIN( source_fps, muxer_fps );
1675 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1677 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1678 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1680 else if ( muxer_fps > 0 )
1682 AVRational frame_rate = stream->r_frame_rate;
1683 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1684 // avg_frame_rate gives some approximate value that does not well match the media.
1685 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1686 // results in some very choppy output, but some value slightly different works
1688 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1689 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1690 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1692 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1693 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1697 source_fps = mlt_producer_get_fps( self->parent );
1698 AVRational frame_rate = av_d2q( source_fps, 255 );
1699 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1700 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1704 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1705 if ( source_fps > 0 )
1706 mlt_properties_set_double( properties, "source_fps", source_fps );
1708 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
1710 // Set the YUV colorspace from override or detect
1711 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1712 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1713 if ( ! self->colorspace )
1715 switch ( self->video_codec->colorspace )
1717 case AVCOL_SPC_SMPTE240M:
1718 self->colorspace = 240;
1720 case AVCOL_SPC_BT470BG:
1721 case AVCOL_SPC_SMPTE170M:
1722 self->colorspace = 601;
1724 case AVCOL_SPC_BT709:
1725 self->colorspace = 709;
1728 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1729 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1734 // Let apps get chosen colorspace
1735 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1737 return self->video_codec && self->video_index > -1;
1740 /** Set up video handling.
1743 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1746 mlt_producer producer = self->parent;
1748 // Get the properties
1749 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1751 // Fetch the video format context
1752 AVFormatContext *context = self->video_format;
1754 // Get the video_index
1755 int index = mlt_properties_get_int( properties, "video_index" );
1757 // Reopen the file if necessary
1758 if ( !context && index > -1 )
1760 mlt_events_block( properties, producer );
1761 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1762 mlt_properties_get( properties, "resource" ) );
1763 context = self->video_format;
1764 if ( self->dummy_context )
1766 av_close_input_file( self->dummy_context );
1767 self->dummy_context = NULL;
1769 mlt_events_unblock( properties, producer );
1770 if ( self->audio_format && !self->audio_streams )
1771 get_audio_streams_info( self );
1773 // Process properties as AVOptions
1776 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1777 #if LIBAVFORMAT_VERSION_MAJOR > 52
1778 if ( context->iformat && context->iformat->priv_class && context->priv_data )
1779 apply_properties( context->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
1784 // Exception handling for video_index
1785 if ( context && index >= (int) context->nb_streams )
1787 // Get the last video stream
1788 for ( index = context->nb_streams - 1;
1789 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1791 mlt_properties_set_int( properties, "video_index", index );
1793 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1795 // Invalidate the video stream
1797 mlt_properties_set_int( properties, "video_index", index );
1800 // Update the video properties if the index changed
1801 if ( index != self->video_index )
1803 // Reset the video properties if the index changed
1804 self->video_index = index;
1805 if ( self->video_codec )
1808 avcodec_close( self->video_codec );
1811 self->video_codec = NULL;
1814 // Get the frame properties
1815 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1818 if ( context && index > -1 && video_codec_init( self, index, properties ) )
1820 // Set the frame properties
1821 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1822 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1823 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1825 // Set the width and height
1826 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
1827 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
1828 // real_width and real_height are deprecated in favor of meta.media.width and .height
1829 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
1830 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
1831 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
1832 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
1833 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1834 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
1836 // Workaround 1088 encodings missing cropping info.
1837 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1839 mlt_properties_set_int( properties, "meta.media.height", 1080 );
1840 mlt_properties_set_int( frame_properties, "real_height", 1080 );
1843 // Add our image operation
1844 mlt_frame_push_service( frame, self );
1845 mlt_frame_push_get_image( frame, producer_get_image );
1849 // If something failed, use test card image
1850 mlt_properties_set_int( frame_properties, "test_image", 1 );
1854 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
1858 // Seek if necessary
1859 if ( position != self->audio_expected )
1861 if ( position + 1 == self->audio_expected )
1863 // We're paused - silence required
1866 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
1868 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1869 *ignore = position - self->audio_expected;
1871 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
1873 AVFormatContext *context = self->audio_format;
1874 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1875 if ( context->start_time != AV_NOPTS_VALUE )
1876 timestamp += context->start_time;
1877 if ( timestamp < 0 )
1880 // Set to the real timecode
1881 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1884 // Clear the usage in the audio buffer
1885 int i = MAX_AUDIO_STREAMS + 1;
1887 self->audio_used[i - 1] = 0;
1893 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
1895 // Fetch the audio_format
1896 AVFormatContext *context = self->audio_format;
1898 // Get the current stream index
1899 int index = pkt.stream_index;
1901 // Get codec context
1902 AVCodecContext *codec_context = self->audio_codec[ index ];
1904 // Obtain the resample context if it exists (not always needed)
1905 ReSampleContext *resample = self->audio_resample[ index ];
1907 // Obtain the audio buffers
1908 int16_t *audio_buffer = self->audio_buffer[ index ];
1909 int16_t *decode_buffer = self->decode_buffer[ index ];
1911 int audio_used = self->audio_used[ index ];
1912 uint8_t *ptr = pkt.data;
1916 while ( ptr && ret >= 0 && len > 0 )
1918 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1921 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1922 ret = avcodec_decode_audio3( codec_context, decode_buffer, &data_size, &pkt );
1923 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1924 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1926 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1930 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
1934 pkt.size = len -= ret;
1935 pkt.data = ptr += ret;
1937 // If decoded successfully
1938 if ( data_size > 0 )
1940 // Figure out how many samples will be needed after resampling
1941 #if LIBAVCODEC_VERSION_MAJOR > 52
1942 int convert_samples = data_size / codec_context->channels / ( av_get_bits_per_sample_fmt( codec_context->sample_fmt ) / 8 );
1944 int convert_samples = data_size / codec_context->channels / ( av_get_bits_per_sample_format( codec_context->sample_fmt ) / 8 );
1946 int samples_needed = self->resample_factor * convert_samples + 1;
1948 // Resize audio buffer to prevent overflow
1949 if ( audio_used * channels + samples_needed > self->audio_buffer_size[ index ] )
1951 self->audio_buffer_size[ index ] *= 2;
1952 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] * sizeof(int16_t) );
1956 // Copy to audio buffer while resampling
1957 int16_t *source = decode_buffer;
1958 int16_t *dest = &audio_buffer[ audio_used * channels ];
1959 audio_used += audio_resample( resample, dest, source, convert_samples );
1963 // Straight copy to audio buffer
1964 memcpy( &audio_buffer[ audio_used * codec_context->channels ], decode_buffer, data_size );
1965 audio_used += convert_samples;
1969 while ( *ignore && audio_used > samples )
1972 audio_used -= samples;
1973 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) ],
1974 audio_used * sizeof( int16_t ) );
1979 // If we're behind, ignore this packet
1982 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
1983 int req_position = ( int )( timecode * fps + 0.5 );
1984 int int_position = ( int )( current_pts * fps + 0.5 );
1985 if ( context->start_time != AV_NOPTS_VALUE )
1986 int_position -= ( int )( fps * context->start_time / AV_TIME_BASE + 0.5 );
1988 if ( self->seekable && *ignore == 0 )
1990 if ( int_position < req_position )
1991 // We are behind, so skip some
1993 else if ( int_position > req_position + 2 )
1994 // We are ahead, so seek backwards some more
1995 seek_audio( self, req_position, timecode - 1.0, ignore );
1999 self->audio_used[ index ] = audio_used;
2004 /** Get the audio from a frame.
2006 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2009 producer_avformat self = mlt_frame_pop_audio( frame );
2011 pthread_mutex_lock( &self->audio_mutex );
2013 // Obtain the frame number of this frame
2014 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
2016 // Calculate the real time code
2017 double real_timecode = producer_time_of_frame( self->parent, position );
2019 // Get the producer fps
2020 double fps = mlt_producer_get_fps( self->parent );
2022 // Number of frames to ignore (for ffwd)
2025 // Flag for paused (silence)
2026 int paused = seek_audio( self, position, real_timecode, &ignore );
2028 // Fetch the audio_format
2029 AVFormatContext *context = self->audio_format;
2031 // Determine the tracks to use
2032 int index = self->audio_index;
2033 int index_max = self->audio_index + 1;
2034 if ( self->audio_index == INT_MAX )
2037 index_max = context->nb_streams;
2038 *channels = self->total_channels;
2039 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2040 *frequency = FFMAX( self->max_frequency, *frequency );
2043 // Initialize the resamplers and buffers
2044 for ( ; index < index_max; index++ )
2046 // Get codec context
2047 AVCodecContext *codec_context = self->audio_codec[ index ];
2049 if ( codec_context && !self->audio_buffer[ index ] )
2051 // Check for resample and create if necessary
2052 if ( codec_context->channels <= 2 )
2054 // Determine by how much resampling will increase number of samples
2055 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2056 resample_factor *= (double) *frequency / codec_context->sample_rate;
2057 if ( resample_factor > self->resample_factor )
2058 self->resample_factor = resample_factor;
2060 // Create the resampler
2061 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2062 self->audio_resample[ index ] = av_audio_resample_init(
2063 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2064 codec_context->channels, *frequency, codec_context->sample_rate,
2065 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2067 self->audio_resample[ index ] = audio_resample_init(
2068 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2069 codec_context->channels, *frequency, codec_context->sample_rate );
2074 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2077 // Check for audio buffer and create if necessary
2078 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE;
2079 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] * sizeof( int16_t ) );
2081 // Check for decoder buffer and create if necessary
2082 self->decode_buffer[ index ] = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
2086 // Get the audio if required
2093 av_init_packet( &pkt );
2095 // If not resampling, give consumer more than requested.
2096 // It requested number samples based on requested frame rate.
2097 // Do not clean this up with a samples *= ...!
2098 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2099 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2101 while ( ret >= 0 && !got_audio )
2103 // Check if the buffer already contains the samples required
2104 if ( self->audio_index != INT_MAX && self->audio_used[ self->audio_index ] >= *samples && ignore == 0 )
2111 ret = av_read_frame( context, &pkt );
2113 // We only deal with audio from the selected audio index
2114 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( pkt.stream_index == self->audio_index ||
2115 ( self->audio_index == INT_MAX && context->streams[ pkt.stream_index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2117 int channels2 = self->audio_index == INT_MAX ? self->audio_codec[pkt.stream_index]->channels : *channels;
2118 ret = decode_audio( self, &ignore, pkt, channels2, *samples, real_timecode, fps );
2120 av_free_packet( &pkt );
2122 if ( self->audio_index == INT_MAX && ret >= 0 )
2124 // Determine if there is enough audio for all streams
2126 for ( index = 0; index < context->nb_streams; index++ )
2128 if ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples )
2134 // Set some additional return values
2135 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2137 *channels = self->audio_codec[ self->audio_index ]->channels;
2138 *frequency = self->audio_codec[ self->audio_index ]->sample_rate;
2141 // Allocate and set the frame's audio buffer
2142 int size = *samples * *channels * sizeof(int16_t);
2143 *buffer = mlt_pool_alloc( size );
2144 *format = mlt_audio_s16;
2145 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2147 // Interleave tracks if audio_index=all
2148 if ( self->audio_index == INT_MAX )
2150 int16_t *dest = *buffer;
2152 for ( i = 0; i < *samples; i++ )
2154 for ( index = 0; index < index_max; index++ )
2155 if ( self->audio_codec[ index ] )
2157 int current_channels = self->audio_codec[ index ]->channels;
2158 int16_t *src = self->audio_buffer[ index ] + i * current_channels;
2159 memcpy( dest, src, current_channels * sizeof(int16_t) );
2160 dest += current_channels;
2163 for ( index = 0; index < index_max; index++ )
2164 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2166 int current_channels = self->audio_codec[ index ]->channels;
2167 int16_t *src = self->audio_buffer[ index ] + *samples * current_channels;
2168 self->audio_used[index] -= *samples;
2169 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof(int16_t) );
2172 // Copy a single track to the output buffer
2175 index = self->audio_index;
2177 // Now handle the audio if we have enough
2178 if ( self->audio_used[ index ] > 0 )
2180 int16_t *src = self->audio_buffer[ index ];
2181 *samples = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2182 memcpy( *buffer, src, *samples * *channels * sizeof(int16_t) );
2183 self->audio_used[ index ] -= *samples;
2184 memmove( src, &src[ *samples * *channels ], self->audio_used[ index ] * *channels * sizeof(int16_t) );
2188 // Otherwise fill with silence
2189 memset( *buffer, 0, *samples * *channels * sizeof(int16_t) );
2195 // Get silence and don't touch the context
2196 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2199 // Regardless of speed (other than paused), we expect to get the next frame
2201 self->audio_expected = position + 1;
2203 pthread_mutex_unlock( &self->audio_mutex );
2208 /** Initialize the audio codec context.
2211 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2213 // Initialise the codec if necessary
2214 if ( !self->audio_codec[ index ] )
2216 // Get codec context
2217 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2220 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2222 // If we don't have a codec and we can't initialise it, we can't do much more...
2224 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2226 // Now store the codec with its destructor
2227 if ( self->audio_codec[ index ] )
2228 avcodec_close( self->audio_codec[ index ] );
2229 self->audio_codec[ index ] = codec_context;
2233 // Remember that we can't use self later
2234 self->audio_index = -1;
2238 // Process properties as AVOptions
2239 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2240 #if LIBAVCODEC_VERSION_MAJOR > 52
2241 if ( codec && codec->priv_class && codec_context->priv_data )
2242 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2245 return self->audio_codec[ index ] && self->audio_index > -1;
2248 /** Set up audio handling.
2251 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2254 mlt_producer producer = self->parent;
2256 // Get the properties
2257 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2259 // Fetch the audio format context
2260 AVFormatContext *context = self->audio_format;
2262 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2264 // Get the audio_index
2265 int index = mlt_properties_get_int( properties, "audio_index" );
2267 // Handle all audio tracks
2268 if ( self->audio_index > -1 &&
2269 mlt_properties_get( properties, "audio_index" ) &&
2270 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2273 // Reopen the file if necessary
2274 if ( !context && self->audio_index > -1 && index > -1 )
2276 mlt_events_block( properties, producer );
2277 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2278 mlt_properties_get( properties, "resource" ) );
2279 context = self->audio_format;
2280 if ( self->dummy_context )
2282 av_close_input_file( self->dummy_context );
2283 self->dummy_context = NULL;
2285 mlt_events_unblock( properties, producer );
2286 if ( self->audio_format )
2287 get_audio_streams_info( self );
2290 // Exception handling for audio_index
2291 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2293 for ( index = context->nb_streams - 1;
2294 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2296 mlt_properties_set_int( properties, "audio_index", index );
2298 if ( context && index > -1 && index < INT_MAX &&
2299 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2301 index = self->audio_index;
2302 mlt_properties_set_int( properties, "audio_index", index );
2305 // Update the audio properties if the index changed
2306 if ( context && index > -1 && index != self->audio_index )
2308 if ( self->audio_codec[ self->audio_index ] )
2311 avcodec_close( self->audio_codec[ self->audio_index ] );
2314 self->audio_codec[ self->audio_index ] = NULL;
2316 if ( self->audio_index != -1 )
2317 self->audio_index = index;
2322 if ( context && index == INT_MAX )
2324 mlt_properties_set_int( frame_properties, "frequency", self->max_frequency );
2325 mlt_properties_set_int( frame_properties, "channels", self->total_channels );
2326 for ( index = 0; index < context->nb_streams; index++ )
2328 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2329 audio_codec_init( self, index, properties );
2332 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2334 // Set the frame properties
2335 if ( index < INT_MAX )
2337 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2338 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2341 if ( context && index > -1 )
2343 // Add our audio operation
2344 mlt_frame_push_audio( frame, self );
2345 mlt_frame_push_audio( frame, producer_get_audio );
2349 /** Our get frame implementation.
2352 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2354 // Access the private data
2355 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2356 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2357 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2362 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2363 producer->child = self;
2364 self->parent = producer;
2365 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2366 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2369 // Create an empty frame
2370 *frame = mlt_frame_init( service);
2374 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2378 mlt_cache_item_close( cache_item );
2382 // Update timecode on the frame we're creating
2383 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2385 // Set the position of this producer
2386 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
2389 producer_set_up_video( self, *frame );
2392 producer_set_up_audio( self, *frame );
2394 // Calculate the next timecode
2395 mlt_producer_prepare_next( producer );
2400 static void producer_avformat_close( producer_avformat self )
2402 mlt_log_debug( NULL, "producer_avformat_close\n" );
2404 av_free( self->av_frame );
2407 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2409 if ( self->audio_resample[i] )
2410 audio_resample_close( self->audio_resample[i] );
2411 mlt_pool_release( self->audio_buffer[i] );
2412 av_free( self->decode_buffer[i] );
2413 if ( self->audio_codec[i] )
2414 avcodec_close( self->audio_codec[i] );
2416 if ( self->video_codec )
2417 avcodec_close( self->video_codec );
2418 if ( self->dummy_context )
2419 av_close_input_file( self->dummy_context );
2420 if ( self->audio_format )
2421 av_close_input_file( self->audio_format );
2422 if ( self->video_format )
2423 av_close_input_file( self->video_format );
2426 vdpau_producer_close( self );
2428 if ( self->image_cache )
2429 mlt_cache_close( self->image_cache );
2430 pthread_mutex_destroy( &self->audio_mutex );
2431 pthread_mutex_destroy( &self->video_mutex );
2435 static void producer_close( mlt_producer parent )
2438 parent->close = NULL;
2439 mlt_producer_close( parent );