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 *buffer = 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 );
1104 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1105 mlt_frame_set_image( frame, *buffer, size, NULL );
1106 // self->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1107 self->got_picture = 1;
1109 goto exit_get_image;
1118 // Special case pause handling flag
1121 // Special case ffwd handling
1124 // We may want to use the source fps if available
1125 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1126 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1127 double fps = mlt_producer_get_fps( producer );
1129 // This is the physical frame position in the source
1130 int req_position = ( int )( position / fps * source_fps + 0.5 );
1132 // Determines if we have to decode all frames in a sequence
1133 // Temporary hack to improve intra frame only
1134 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
1135 strcmp( codec_context->codec->name, "dvvideo" ) &&
1136 strcmp( codec_context->codec->name, "huffyuv" ) &&
1137 strcmp( codec_context->codec->name, "mjpeg" ) &&
1138 strcmp( codec_context->codec->name, "rawvideo" );
1140 int last_position = self->last_position;
1142 // Turn on usage of new seek API and PTS for seeking
1143 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1144 if ( mlt_properties_get( properties, "new_seek" ) )
1145 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1147 // Seek if necessary
1148 if ( position != self->video_expected || last_position < 0 )
1150 if ( self->av_frame && position + 1 == self->video_expected )
1152 // We're paused - use last image
1155 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
1157 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1158 ignore = ( int )( ( position - self->video_expected ) / fps * source_fps );
1159 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1161 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || last_position < 0 ) )
1163 if ( use_new_seek && last_position == POSITION_INITIAL )
1165 // find first key frame
1169 while ( ret >= 0 && toscan-- > 0 )
1171 ret = av_read_frame( context, &pkt );
1172 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
1174 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) );
1175 self->first_pts = pkt.pts;
1178 av_free_packet( &pkt );
1181 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1184 // Calculate the timestamp for the requested frame
1188 timestamp = ( req_position - 0.1 / source_fps ) /
1189 ( av_q2d( stream->time_base ) * source_fps );
1190 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %"PRId64" ", req_position, timestamp );
1191 if ( self->first_pts > 0 )
1192 timestamp += self->first_pts;
1193 else if ( context->start_time != AV_NOPTS_VALUE )
1194 timestamp += context->start_time;
1198 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
1199 if ( context->start_time != AV_NOPTS_VALUE )
1200 timestamp += context->start_time;
1203 timestamp -= AV_TIME_BASE;
1204 if ( timestamp < 0 )
1206 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %d\n",
1207 timestamp, position, self->video_expected, last_position );
1209 // Seek to the timestamp
1212 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1213 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1215 else if ( req_position > 0 || last_position <= 0 )
1217 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
1221 // Re-open video stream when rewinding to beginning from somewhere else.
1222 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1223 // not reliably seeking to the first frame across formats.
1224 reopen_video( self, producer, properties );
1225 context = self->video_format;
1226 stream = context->streams[ self->video_index ];
1227 codec_context = stream->codec;
1230 // Remove the cached info relating to the previous position
1231 self->current_position = POSITION_INVALID;
1232 self->last_position = POSITION_INVALID;
1233 av_freep( &self->av_frame );
1237 // flush any pictures still in decode buffer
1238 avcodec_flush_buffers( codec_context );
1243 // Duplicate the last image if necessary
1244 if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture && self->seekable
1246 || self->current_position == req_position
1247 || ( !use_new_seek && self->current_position > req_position ) ) )
1250 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1252 // Workaround 1088 encodings missing cropping info.
1253 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1256 if ( self->vdpau && self->vdpau->buffer )
1259 picture.data[0] = self->vdpau->buffer;
1260 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1261 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1262 picture.linesize[0] = codec_context->width;
1263 picture.linesize[1] = codec_context->width / 2;
1264 picture.linesize[2] = codec_context->width / 2;
1265 convert_image( (AVFrame*) &picture, *buffer,
1266 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1270 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1271 format, *width, *height, self->colorspace );
1274 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1279 int int_position = 0;
1280 int decode_errors = 0;
1281 int got_picture = 0;
1283 av_init_packet( &pkt );
1285 // Construct an AVFrame for YUV422 conversion
1286 if ( !self->av_frame )
1287 self->av_frame = avcodec_alloc_frame( );
1289 while( ret >= 0 && !got_picture )
1292 ret = av_read_frame( context, &pkt );
1294 // We only deal with video from the selected video_index
1295 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1297 // Determine time code of the packet
1300 int64_t pts = pkt.pts;
1301 if ( self->first_pts > 0 )
1302 pts -= self->first_pts;
1303 else if ( context->start_time != AV_NOPTS_VALUE )
1304 pts -= context->start_time;
1305 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1306 if ( pkt.pts == AV_NOPTS_VALUE )
1308 self->invalid_pts_counter++;
1309 if ( self->invalid_pts_counter > 20 )
1311 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1312 mlt_properties_set_int( properties, "new_seek", 0 );
1313 int_position = req_position;
1319 self->invalid_pts_counter = 0;
1321 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1322 pkt.pts, req_position, self->current_position, int_position );
1326 if ( self->seekable && pkt.dts != AV_NOPTS_VALUE )
1328 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1329 if ( context->start_time != AV_NOPTS_VALUE )
1330 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1331 last_position = self->last_position;
1332 if ( int_position == last_position )
1333 int_position = last_position + 1;
1337 int_position = req_position;
1339 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1340 pkt.dts, req_position, self->current_position, int_position );
1341 // Make a dumb assumption on streams that contain wild timestamps
1342 if ( abs( req_position - int_position ) > 999 )
1344 int_position = req_position;
1345 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1348 self->last_position = int_position;
1351 if ( must_decode || int_position >= req_position )
1354 if ( g_vdpau && self->vdpau )
1356 if ( g_vdpau->producer != self )
1358 vdpau_decoder_close();
1359 vdpau_decoder_init( self );
1362 self->vdpau->is_decoded = 0;
1365 codec_context->reordered_opaque = pkt.pts;
1366 if ( int_position >= req_position )
1367 codec_context->skip_loop_filter = AVDISCARD_NONE;
1368 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1369 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1371 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1373 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1376 if ( ++decode_errors <= 10 )
1389 // Determine time code of the packet
1390 int64_t pts = self->av_frame->reordered_opaque;
1391 if ( self->first_pts > 0 )
1392 pts -= self->first_pts;
1393 else if ( context->start_time != AV_NOPTS_VALUE )
1394 pts -= context->start_time;
1395 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1396 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, self->av_frame->key_frame );
1399 if ( int_position < req_position )
1404 else if ( int_position >= req_position )
1407 codec_context->skip_loop_filter = AVDISCARD_NONE;
1409 else if ( ignore -- )
1414 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1417 // Now handle the picture if we have one
1420 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1422 // Workaround 1088 encodings missing cropping info.
1423 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1428 if ( self->vdpau->is_decoded )
1430 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1432 uint32_t pitches[3];
1433 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1435 if ( !self->vdpau->buffer )
1436 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1437 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1438 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1439 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1440 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1441 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1442 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1444 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1445 if ( status == VDP_STATUS_OK )
1447 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1448 format, *width, *height, self->colorspace );
1452 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1453 image_size = self->vdpau->is_decoded = 0;
1458 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1459 image_size = got_picture = 0;
1464 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1465 format, *width, *height, self->colorspace );
1466 self->top_field_first |= self->av_frame->top_field_first;
1467 self->current_position = int_position;
1468 self->got_picture = 1;
1476 av_free_packet( &pkt );
1480 if ( self->got_picture && image_size > 0 && self->image_cache )
1482 // Copy buffer to image cache
1483 uint8_t *image = mlt_pool_alloc( image_size );
1484 memcpy( image, *buffer, image_size );
1485 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1487 // Try to duplicate last image if there was a decoding failure
1488 else if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1491 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1493 // Workaround 1088 encodings missing cropping info.
1494 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1497 if ( self->vdpau && self->vdpau->buffer )
1500 picture.data[0] = self->vdpau->buffer;
1501 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1502 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1503 picture.linesize[0] = codec_context->width;
1504 picture.linesize[1] = codec_context->width / 2;
1505 picture.linesize[2] = codec_context->width / 2;
1506 convert_image( (AVFrame*) &picture, *buffer,
1507 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1511 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1512 format, *width, *height, self->colorspace );
1513 self->got_picture = 1;
1516 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1519 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1520 self->video_expected = position + 1;
1524 pthread_mutex_unlock( &self->video_mutex );
1526 // Set the progressive flag
1527 if ( mlt_properties_get( properties, "force_progressive" ) )
1528 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1529 else if ( self->av_frame )
1530 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1532 // Set the field order property for this frame
1533 if ( mlt_properties_get( properties, "force_tff" ) )
1534 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1536 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1538 // Set immutable properties of the selected track's (or overridden) source attributes.
1539 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1540 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1541 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1542 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1544 return !self->got_picture;
1547 /** Process properties as AVOptions and apply to AV context obj
1550 static void apply_properties( void *obj, mlt_properties properties, int flags )
1553 int count = mlt_properties_count( properties );
1554 for ( i = 0; i < count; i++ )
1556 const char *opt_name = mlt_properties_get_name( properties, i );
1557 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1558 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1561 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1562 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1563 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1564 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1566 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1572 /** Initialize the video codec context.
1575 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1577 // Initialise the codec if necessary
1578 if ( !self->video_codec )
1580 // Get the video stream
1581 AVStream *stream = self->video_format->streams[ index ];
1583 // Get codec context
1584 AVCodecContext *codec_context = stream->codec;
1587 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1589 if ( codec_context->codec_id == CODEC_ID_H264 )
1591 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1593 if ( vdpau_init( self ) )
1595 self->video_codec = codec_context;
1596 if ( !vdpau_decoder_init( self ) )
1597 vdpau_decoder_close();
1601 codec = avcodec_find_decoder( codec_context->codec_id );
1605 // Initialise multi-threading
1606 int thread_count = mlt_properties_get_int( properties, "threads" );
1607 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1608 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1609 if ( thread_count > 1 )
1610 codec_context->thread_count = thread_count;
1612 // If we don't have a codec and we can't initialise it, we can't do much more...
1614 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1616 // Now store the codec with its destructor
1617 self->video_codec = codec_context;
1621 // Remember that we can't use this later
1622 self->video_index = -1;
1628 // Process properties as AVOptions
1629 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1630 #if LIBAVCODEC_VERSION_MAJOR > 52
1631 if ( codec->priv_class && codec_context->priv_data )
1632 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1635 // Reset some image properties
1636 mlt_properties_set_int( properties, "width", self->video_codec->width );
1637 mlt_properties_set_int( properties, "height", self->video_codec->height );
1638 // For DV, we'll just use the saved aspect ratio
1639 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1640 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1642 // Determine the fps first from the codec
1643 double source_fps = (double) self->video_codec->time_base.den /
1644 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1646 if ( mlt_properties_get( properties, "force_fps" ) )
1648 source_fps = mlt_properties_get_double( properties, "force_fps" );
1649 stream->time_base = av_d2q( source_fps, 1024 );
1650 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1651 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1655 // If the muxer reports a frame rate different than the codec
1656 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1657 double muxer_fps = av_q2d( stream->avg_frame_rate );
1658 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1659 muxer_fps = av_q2d( stream->r_frame_rate );
1661 double muxer_fps = av_q2d( stream->r_frame_rate );
1663 // Choose the lesser - the wrong tends to be off by some multiple of 10
1664 source_fps = FFMIN( source_fps, muxer_fps );
1665 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1667 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1668 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1670 else if ( muxer_fps > 0 )
1672 AVRational frame_rate = stream->r_frame_rate;
1673 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1674 // avg_frame_rate gives some approximate value that does not well match the media.
1675 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1676 // results in some very choppy output, but some value slightly different works
1678 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1679 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1680 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1682 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1683 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1687 source_fps = mlt_producer_get_fps( self->parent );
1688 AVRational frame_rate = av_d2q( source_fps, 255 );
1689 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1690 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1694 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1695 if ( source_fps > 0 )
1696 mlt_properties_set_double( properties, "source_fps", source_fps );
1698 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
1700 // Set the YUV colorspace from override or detect
1701 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1702 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1703 if ( ! self->colorspace )
1705 switch ( self->video_codec->colorspace )
1707 case AVCOL_SPC_SMPTE240M:
1708 self->colorspace = 240;
1710 case AVCOL_SPC_BT470BG:
1711 case AVCOL_SPC_SMPTE170M:
1712 self->colorspace = 601;
1714 case AVCOL_SPC_BT709:
1715 self->colorspace = 709;
1718 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1719 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1724 // Let apps get chosen colorspace
1725 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1727 return self->video_codec && self->video_index > -1;
1730 /** Set up video handling.
1733 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1736 mlt_producer producer = self->parent;
1738 // Get the properties
1739 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1741 // Fetch the video format context
1742 AVFormatContext *context = self->video_format;
1744 // Get the video_index
1745 int index = mlt_properties_get_int( properties, "video_index" );
1747 // Reopen the file if necessary
1748 if ( !context && index > -1 )
1750 mlt_events_block( properties, producer );
1751 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1752 mlt_properties_get( properties, "resource" ) );
1753 context = self->video_format;
1754 if ( self->dummy_context )
1756 av_close_input_file( self->dummy_context );
1757 self->dummy_context = NULL;
1759 mlt_events_unblock( properties, producer );
1760 if ( self->audio_format && !self->audio_streams )
1761 get_audio_streams_info( self );
1763 // Process properties as AVOptions
1766 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1767 #if LIBAVFORMAT_VERSION_MAJOR > 52
1768 if ( context->iformat && context->iformat->priv_class && context->priv_data )
1769 apply_properties( context->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
1774 // Exception handling for video_index
1775 if ( context && index >= (int) context->nb_streams )
1777 // Get the last video stream
1778 for ( index = context->nb_streams - 1;
1779 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1781 mlt_properties_set_int( properties, "video_index", index );
1783 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1785 // Invalidate the video stream
1787 mlt_properties_set_int( properties, "video_index", index );
1790 // Update the video properties if the index changed
1791 if ( index != self->video_index )
1793 // Reset the video properties if the index changed
1794 self->video_index = index;
1795 if ( self->video_codec )
1798 avcodec_close( self->video_codec );
1801 self->video_codec = NULL;
1804 // Get the frame properties
1805 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1808 if ( context && index > -1 && video_codec_init( self, index, properties ) )
1810 // Set the frame properties
1811 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1812 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1813 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1815 // Set the width and height
1816 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
1817 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
1818 // real_width and real_height are deprecated in favor of meta.media.width and .height
1819 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
1820 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
1821 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
1822 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
1823 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1824 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
1826 // Workaround 1088 encodings missing cropping info.
1827 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1829 mlt_properties_set_int( properties, "meta.media.height", 1080 );
1830 mlt_properties_set_int( frame_properties, "real_height", 1080 );
1833 // Add our image operation
1834 mlt_frame_push_service( frame, self );
1835 mlt_frame_push_get_image( frame, producer_get_image );
1839 // If something failed, use test card image
1840 mlt_properties_set_int( frame_properties, "test_image", 1 );
1844 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
1848 // Seek if necessary
1849 if ( position != self->audio_expected )
1851 if ( position + 1 == self->audio_expected )
1853 // We're paused - silence required
1856 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
1858 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1859 *ignore = position - self->audio_expected;
1861 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
1863 AVFormatContext *context = self->audio_format;
1864 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1865 if ( context->start_time != AV_NOPTS_VALUE )
1866 timestamp += context->start_time;
1867 if ( timestamp < 0 )
1870 // Set to the real timecode
1871 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1874 // Clear the usage in the audio buffer
1875 int i = MAX_AUDIO_STREAMS + 1;
1877 self->audio_used[i - 1] = 0;
1883 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
1885 // Fetch the audio_format
1886 AVFormatContext *context = self->audio_format;
1888 // Get the current stream index
1889 int index = pkt.stream_index;
1891 // Get codec context
1892 AVCodecContext *codec_context = self->audio_codec[ index ];
1894 // Obtain the resample context if it exists (not always needed)
1895 ReSampleContext *resample = self->audio_resample[ index ];
1897 // Obtain the audio buffers
1898 int16_t *audio_buffer = self->audio_buffer[ index ];
1899 int16_t *decode_buffer = self->decode_buffer[ index ];
1901 int audio_used = self->audio_used[ index ];
1902 uint8_t *ptr = pkt.data;
1906 while ( ptr && ret >= 0 && len > 0 )
1908 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1911 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1912 ret = avcodec_decode_audio3( codec_context, decode_buffer, &data_size, &pkt );
1913 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1914 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1916 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1920 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
1924 pkt.size = len -= ret;
1925 pkt.data = ptr += ret;
1927 // If decoded successfully
1928 if ( data_size > 0 )
1930 // Figure out how many samples will be needed after resampling
1931 #if LIBAVCODEC_VERSION_MAJOR > 52
1932 int convert_samples = data_size / codec_context->channels / ( av_get_bits_per_sample_fmt( codec_context->sample_fmt ) / 8 );
1934 int convert_samples = data_size / codec_context->channels / ( av_get_bits_per_sample_format( codec_context->sample_fmt ) / 8 );
1936 int samples_needed = self->resample_factor * convert_samples + 1;
1938 // Resize audio buffer to prevent overflow
1939 if ( audio_used * channels + samples_needed > self->audio_buffer_size[ index ] )
1941 self->audio_buffer_size[ index ] *= 2;
1942 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] * sizeof(int16_t) );
1946 // Copy to audio buffer while resampling
1947 int16_t *source = decode_buffer;
1948 int16_t *dest = &audio_buffer[ audio_used * channels ];
1949 audio_used += audio_resample( resample, dest, source, convert_samples );
1953 // Straight copy to audio buffer
1954 memcpy( &audio_buffer[ audio_used * codec_context->channels ], decode_buffer, data_size );
1955 audio_used += convert_samples;
1959 while ( *ignore && audio_used > samples )
1962 audio_used -= samples;
1963 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) ],
1964 audio_used * sizeof( int16_t ) );
1969 // If we're behind, ignore this packet
1972 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
1973 int req_position = ( int )( timecode * fps + 0.5 );
1974 int int_position = ( int )( current_pts * fps + 0.5 );
1975 if ( context->start_time != AV_NOPTS_VALUE )
1976 int_position -= ( int )( fps * context->start_time / AV_TIME_BASE + 0.5 );
1978 if ( self->seekable && *ignore == 0 )
1980 if ( int_position < req_position )
1981 // We are behind, so skip some
1983 else if ( int_position > req_position + 2 )
1984 // We are ahead, so seek backwards some more
1985 seek_audio( self, req_position, timecode - 1.0, ignore );
1989 self->audio_used[ index ] = audio_used;
1994 /** Get the audio from a frame.
1996 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1999 producer_avformat self = mlt_frame_pop_audio( frame );
2001 pthread_mutex_lock( &self->audio_mutex );
2003 // Obtain the frame number of this frame
2004 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
2006 // Calculate the real time code
2007 double real_timecode = producer_time_of_frame( self->parent, position );
2009 // Get the producer fps
2010 double fps = mlt_producer_get_fps( self->parent );
2012 // Number of frames to ignore (for ffwd)
2015 // Flag for paused (silence)
2016 int paused = seek_audio( self, position, real_timecode, &ignore );
2018 // Fetch the audio_format
2019 AVFormatContext *context = self->audio_format;
2021 // Determine the tracks to use
2022 int index = self->audio_index;
2023 int index_max = self->audio_index + 1;
2024 if ( self->audio_index == INT_MAX )
2027 index_max = context->nb_streams;
2028 *channels = self->total_channels;
2029 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2030 *frequency = FFMAX( self->max_frequency, *frequency );
2033 // Initialize the resamplers and buffers
2034 for ( ; index < index_max; index++ )
2036 // Get codec context
2037 AVCodecContext *codec_context = self->audio_codec[ index ];
2039 if ( codec_context && !self->audio_buffer[ index ] )
2041 // Check for resample and create if necessary
2042 if ( codec_context->channels <= 2 )
2044 // Determine by how much resampling will increase number of samples
2045 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2046 resample_factor *= (double) *frequency / codec_context->sample_rate;
2047 if ( resample_factor > self->resample_factor )
2048 self->resample_factor = resample_factor;
2050 // Create the resampler
2051 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2052 self->audio_resample[ index ] = av_audio_resample_init(
2053 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2054 codec_context->channels, *frequency, codec_context->sample_rate,
2055 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2057 self->audio_resample[ index ] = audio_resample_init(
2058 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2059 codec_context->channels, *frequency, codec_context->sample_rate );
2064 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2067 // Check for audio buffer and create if necessary
2068 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE;
2069 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] * sizeof( int16_t ) );
2071 // Check for decoder buffer and create if necessary
2072 self->decode_buffer[ index ] = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
2076 // Get the audio if required
2083 av_init_packet( &pkt );
2085 // If not resampling, give consumer more than requested.
2086 // It requested number samples based on requested frame rate.
2087 // Do not clean this up with a samples *= ...!
2088 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2089 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2091 while ( ret >= 0 && !got_audio )
2093 // Check if the buffer already contains the samples required
2094 if ( self->audio_index != INT_MAX && self->audio_used[ self->audio_index ] >= *samples && ignore == 0 )
2101 ret = av_read_frame( context, &pkt );
2103 // We only deal with audio from the selected audio index
2104 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( pkt.stream_index == self->audio_index ||
2105 ( self->audio_index == INT_MAX && context->streams[ pkt.stream_index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2107 int channels2 = self->audio_index == INT_MAX ? self->audio_codec[pkt.stream_index]->channels : *channels;
2108 ret = decode_audio( self, &ignore, pkt, channels2, *samples, real_timecode, fps );
2110 av_free_packet( &pkt );
2112 if ( self->audio_index == INT_MAX && ret >= 0 )
2114 // Determine if there is enough audio for all streams
2116 for ( index = 0; index < context->nb_streams; index++ )
2118 if ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples )
2124 // Set some additional return values
2125 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2127 *channels = self->audio_codec[ self->audio_index ]->channels;
2128 *frequency = self->audio_codec[ self->audio_index ]->sample_rate;
2131 // Allocate and set the frame's audio buffer
2132 int size = *samples * *channels * sizeof(int16_t);
2133 *buffer = mlt_pool_alloc( size );
2134 *format = mlt_audio_s16;
2135 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2137 // Interleave tracks if audio_index=all
2138 if ( self->audio_index == INT_MAX )
2140 int16_t *dest = *buffer;
2142 for ( i = 0; i < *samples; i++ )
2144 for ( index = 0; index < index_max; index++ )
2145 if ( self->audio_codec[ index ] )
2147 int current_channels = self->audio_codec[ index ]->channels;
2148 int16_t *src = self->audio_buffer[ index ] + i * current_channels;
2149 memcpy( dest, src, current_channels * sizeof(int16_t) );
2150 dest += current_channels;
2153 for ( index = 0; index < index_max; index++ )
2154 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2156 int current_channels = self->audio_codec[ index ]->channels;
2157 int16_t *src = self->audio_buffer[ index ] + *samples * current_channels;
2158 self->audio_used[index] -= *samples;
2159 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof(int16_t) );
2162 // Copy a single track to the output buffer
2165 index = self->audio_index;
2167 // Now handle the audio if we have enough
2168 if ( self->audio_used[ index ] > 0 )
2170 int16_t *src = self->audio_buffer[ index ];
2171 *samples = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2172 memcpy( *buffer, src, *samples * *channels * sizeof(int16_t) );
2173 self->audio_used[ index ] -= *samples;
2174 memmove( src, &src[ *samples * *channels ], self->audio_used[ index ] * *channels * sizeof(int16_t) );
2178 // Otherwise fill with silence
2179 memset( *buffer, 0, *samples * *channels * sizeof(int16_t) );
2185 // Get silence and don't touch the context
2186 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2189 // Regardless of speed (other than paused), we expect to get the next frame
2191 self->audio_expected = position + 1;
2193 pthread_mutex_unlock( &self->audio_mutex );
2198 /** Initialize the audio codec context.
2201 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2203 // Initialise the codec if necessary
2204 if ( !self->audio_codec[ index ] )
2206 // Get codec context
2207 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2210 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2212 // If we don't have a codec and we can't initialise it, we can't do much more...
2214 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2216 // Now store the codec with its destructor
2217 if ( self->audio_codec[ index ] )
2218 avcodec_close( self->audio_codec[ index ] );
2219 self->audio_codec[ index ] = codec_context;
2223 // Remember that we can't use self later
2224 self->audio_index = -1;
2228 // Process properties as AVOptions
2229 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2230 #if LIBAVCODEC_VERSION_MAJOR > 52
2231 if ( codec && codec->priv_class && codec_context->priv_data )
2232 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2235 return self->audio_codec[ index ] && self->audio_index > -1;
2238 /** Set up audio handling.
2241 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2244 mlt_producer producer = self->parent;
2246 // Get the properties
2247 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2249 // Fetch the audio format context
2250 AVFormatContext *context = self->audio_format;
2252 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2254 // Get the audio_index
2255 int index = mlt_properties_get_int( properties, "audio_index" );
2257 // Handle all audio tracks
2258 if ( self->audio_index > -1 &&
2259 mlt_properties_get( properties, "audio_index" ) &&
2260 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2263 // Reopen the file if necessary
2264 if ( !context && self->audio_index > -1 && index > -1 )
2266 mlt_events_block( properties, producer );
2267 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2268 mlt_properties_get( properties, "resource" ) );
2269 context = self->audio_format;
2270 if ( self->dummy_context )
2272 av_close_input_file( self->dummy_context );
2273 self->dummy_context = NULL;
2275 mlt_events_unblock( properties, producer );
2276 if ( self->audio_format )
2277 get_audio_streams_info( self );
2280 // Exception handling for audio_index
2281 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2283 for ( index = context->nb_streams - 1;
2284 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2286 mlt_properties_set_int( properties, "audio_index", index );
2288 if ( context && index > -1 && index < INT_MAX &&
2289 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2291 index = self->audio_index;
2292 mlt_properties_set_int( properties, "audio_index", index );
2295 // Update the audio properties if the index changed
2296 if ( context && index > -1 && index != self->audio_index )
2298 if ( self->audio_codec[ self->audio_index ] )
2301 avcodec_close( self->audio_codec[ self->audio_index ] );
2304 self->audio_codec[ self->audio_index ] = NULL;
2306 if ( self->audio_index != -1 )
2307 self->audio_index = index;
2312 if ( context && index == INT_MAX )
2314 mlt_properties_set_int( frame_properties, "frequency", self->max_frequency );
2315 mlt_properties_set_int( frame_properties, "channels", self->total_channels );
2316 for ( index = 0; index < context->nb_streams; index++ )
2318 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2319 audio_codec_init( self, index, properties );
2322 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2324 // Set the frame properties
2325 if ( index < INT_MAX )
2327 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2328 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2331 if ( context && index > -1 )
2333 // Add our audio operation
2334 mlt_frame_push_audio( frame, self );
2335 mlt_frame_push_audio( frame, producer_get_audio );
2339 /** Our get frame implementation.
2342 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2344 // Access the private data
2345 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2346 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2347 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2352 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2353 producer->child = self;
2354 self->parent = producer;
2355 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2356 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2359 // Create an empty frame
2360 *frame = mlt_frame_init( service);
2364 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2368 mlt_cache_item_close( cache_item );
2372 // Update timecode on the frame we're creating
2373 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2375 // Set the position of this producer
2376 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
2379 producer_set_up_video( self, *frame );
2382 producer_set_up_audio( self, *frame );
2384 // Calculate the next timecode
2385 mlt_producer_prepare_next( producer );
2390 static void producer_avformat_close( producer_avformat self )
2392 mlt_log_debug( NULL, "producer_avformat_close\n" );
2394 av_free( self->av_frame );
2397 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2399 if ( self->audio_resample[i] )
2400 audio_resample_close( self->audio_resample[i] );
2401 mlt_pool_release( self->audio_buffer[i] );
2402 av_free( self->decode_buffer[i] );
2403 if ( self->audio_codec[i] )
2404 avcodec_close( self->audio_codec[i] );
2406 if ( self->video_codec )
2407 avcodec_close( self->video_codec );
2408 if ( self->dummy_context )
2409 av_close_input_file( self->dummy_context );
2410 if ( self->audio_format )
2411 av_close_input_file( self->audio_format );
2412 if ( self->video_format )
2413 av_close_input_file( self->video_format );
2416 vdpau_producer_close( self );
2418 if ( self->image_cache )
2419 mlt_cache_close( self->image_cache );
2420 pthread_mutex_destroy( &self->audio_mutex );
2421 pthread_mutex_destroy( &self->video_mutex );
2425 static void producer_close( mlt_producer parent )
2428 parent->close = NULL;
2429 mlt_producer_close( parent );