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 uint8_t *audio_buffer[ MAX_AUDIO_STREAMS ];
100 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
101 uint8_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 list_components( char* file );
133 static int producer_open( producer_avformat self, mlt_profile profile, char *file );
134 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
135 static void producer_avformat_close( producer_avformat );
136 static void producer_close( mlt_producer parent );
137 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
138 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
139 static void apply_properties( void *obj, mlt_properties properties, int flags );
140 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
146 /** Constructor for libavformat.
149 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
151 if ( list_components( file ) )
154 mlt_producer producer = NULL;
156 // Check that we have a non-NULL argument
159 // Construct the producer
160 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
161 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
164 if ( mlt_producer_init( producer, self ) == 0 )
166 self->parent = producer;
168 // Get the properties
169 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
171 // Set the resource property (required for all producers)
172 mlt_properties_set( properties, "resource", file );
174 // Register transport implementation with the producer
175 producer->close = (mlt_destructor) producer_close;
177 // Register our get_frame implementation
178 producer->get_frame = producer_get_frame;
180 if ( strcmp( service, "avformat-novalidate" ) )
183 if ( producer_open( self, profile, file ) != 0 )
186 mlt_producer_close( producer );
191 // Close the file to release resources for large playlists - reopen later as needed
193 if ( self->dummy_context )
194 av_close_input_file( self->dummy_context );
195 self->dummy_context = NULL;
196 if ( self->audio_format )
197 av_close_input_file( self->audio_format );
198 self->audio_format = NULL;
199 if ( self->video_format )
200 av_close_input_file( self->video_format );
201 self->video_format = NULL;
204 // Default the user-selectable indices from the auto-detected indices
205 mlt_properties_set_int( properties, "audio_index", self->audio_index );
206 mlt_properties_set_int( properties, "video_index", self->video_index );
212 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
214 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
221 int list_components( char* file )
225 // Report information about available demuxers and codecs as YAML Tiny
226 if ( file && strstr( file, "f-list" ) )
228 fprintf( stderr, "---\nformats:\n" );
229 AVInputFormat *format = NULL;
230 while ( ( format = av_iformat_next( format ) ) )
231 fprintf( stderr, " - %s\n", format->name );
232 fprintf( stderr, "...\n" );
235 if ( file && strstr( file, "acodec-list" ) )
237 fprintf( stderr, "---\naudio_codecs:\n" );
238 AVCodec *codec = NULL;
239 while ( ( codec = av_codec_next( codec ) ) )
240 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
241 fprintf( stderr, " - %s\n", codec->name );
242 fprintf( stderr, "...\n" );
245 if ( file && strstr( file, "vcodec-list" ) )
247 fprintf( stderr, "---\nvideo_codecs:\n" );
248 AVCodec *codec = NULL;
249 while ( ( codec = av_codec_next( codec ) ) )
250 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
251 fprintf( stderr, " - %s\n", codec->name );
252 fprintf( stderr, "...\n" );
259 /** Find the default streams.
262 static mlt_properties find_default_streams( mlt_properties meta_media, AVFormatContext *context, int *audio_index, int *video_index )
266 AVMetadataTag *tag = NULL;
268 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
270 // Allow for multiple audio and video streams in the file and select first of each (if available)
271 for( i = 0; i < context->nb_streams; i++ )
273 // Get the codec context
274 AVStream *stream = context->streams[ i ];
275 if ( ! stream ) continue;
276 AVCodecContext *codec_context = stream->codec;
277 if ( ! codec_context ) continue;
278 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
279 if ( ! codec ) continue;
281 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
283 // Determine the type and obtain the first index of each type
284 switch( codec_context->codec_type )
286 case CODEC_TYPE_VIDEO:
287 if ( *video_index < 0 )
289 mlt_properties_set( meta_media, key, "video" );
290 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
291 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
292 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
293 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
294 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
295 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
297 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
300 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
301 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
302 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
304 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
305 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
306 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
307 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
308 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
309 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
310 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
311 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
312 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
313 switch ( codec_context->colorspace )
315 case AVCOL_SPC_SMPTE240M:
316 mlt_properties_set_int( meta_media, key, 240 );
318 case AVCOL_SPC_BT470BG:
319 case AVCOL_SPC_SMPTE170M:
320 mlt_properties_set_int( meta_media, key, 601 );
322 case AVCOL_SPC_BT709:
323 mlt_properties_set_int( meta_media, key, 709 );
326 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
327 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
332 case CODEC_TYPE_AUDIO:
333 if ( *audio_index < 0 )
335 mlt_properties_set( meta_media, key, "audio" );
336 #if LIBAVCODEC_VERSION_MAJOR > 52
337 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
338 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
339 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
340 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
341 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
343 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
344 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
345 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
346 mlt_properties_set_int( meta_media, key, codec_context->channels );
351 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
352 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
353 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
354 mlt_properties_set( meta_media, key, codec->name );
355 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
356 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
357 mlt_properties_set( meta_media, key, codec->long_name );
359 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
360 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
361 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
362 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
363 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
364 // mlt_properties_set_int( meta_media, key, codec_context->profile );
365 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
366 // mlt_properties_set_int( meta_media, key, codec_context->level );
369 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
370 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
372 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
374 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
375 mlt_properties_set( meta_media, key, tag->value );
380 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
381 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
383 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
385 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
386 mlt_properties_set( meta_media, key, tag->value );
390 if ( context->title && strcmp( context->title, "" ) )
391 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
392 if ( context->author && strcmp( context->author, "" ) )
393 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
394 if ( context->copyright && strcmp( context->copyright, "" ) )
395 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
396 if ( context->comment )
397 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
398 if ( context->album )
399 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
401 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
402 if ( context->track )
403 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
409 static inline int dv_is_pal( AVPacket *pkt )
411 return pkt->data[3] & 0x80;
414 static int dv_is_wide( AVPacket *pkt )
416 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
418 for ( ; i < pkt->size; i += 5 /* packet size */ )
420 if ( pkt->data[ i ] == 0x61 )
422 uint8_t x = pkt->data[ i + 2 ] & 0x7;
423 return ( x == 2 ) || ( x == 7 );
429 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
431 double aspect_ratio = 1.0;
433 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
437 if ( dv_is_pal( pkt ) )
439 if ( dv_is_wide( pkt ) )
441 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
442 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
446 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
447 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
452 if ( dv_is_wide( pkt ) )
454 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
455 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
459 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
460 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
467 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
468 stream->sample_aspect_ratio;
470 codec_context->sample_aspect_ratio;
472 // Override FFmpeg's notion of DV aspect ratios, which are
473 // based upon a width of 704. Since we do not have a normaliser
474 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
475 // we just coerce the values to facilitate a passive behaviour through
476 // the rescale normaliser when using equivalent producers and consumers.
477 // = display_aspect / (width * height)
478 if ( ar.num == 10 && ar.den == 11 )
481 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
482 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
484 else if ( ar.num == 59 && ar.den == 54 )
487 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
488 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
490 else if ( ar.num == 40 && ar.den == 33 )
493 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
494 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
496 else if ( ar.num == 118 && ar.den == 81 )
499 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
500 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
506 AVRational codec_sar = codec_context->sample_aspect_ratio;
507 AVRational stream_sar =
508 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
509 stream->sample_aspect_ratio;
513 if ( codec_sar.num > 0 )
515 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
516 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
518 else if ( stream_sar.num > 0 )
520 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
521 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
525 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
526 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
529 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
530 aspect_ratio = av_q2d( ar );
531 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
539 static int producer_open( producer_avformat self, mlt_profile profile, char *file )
541 // Return an error code (0 == no error)
544 // Context for avformat
545 AVFormatContext *context = NULL;
547 // Get the properties
548 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
550 // We will treat everything with the producer fps
551 double fps = mlt_profile_fps( profile );
554 pthread_mutex_init( &self->audio_mutex, NULL );
555 pthread_mutex_init( &self->video_mutex, NULL );
556 pthread_mutex_lock( &self->audio_mutex );
557 pthread_mutex_lock( &self->video_mutex );
559 // If "MRL", then create AVInputFormat
560 AVInputFormat *format = NULL;
561 AVFormatParameters *params = NULL;
562 char *standard = NULL;
563 char *mrl = strchr( file, ':' );
565 // AV option (0 = both, 1 = video, 2 = audio)
568 // Only if there is not a protocol specification that avformat can handle
569 #if LIBAVFORMAT_VERSION_MAJOR > 52
570 if ( mrl && avio_check( file, 0 ) < 0 )
572 if ( mrl && !url_exist( file ) )
575 // 'file' becomes format abbreviation
579 format = av_find_input_format( file );
581 // Eat the format designator
587 params = calloc( sizeof( AVFormatParameters ), 1 );
589 // These are required by video4linux (defaults)
591 params->height = 480;
592 params->time_base= (AVRational){1,25};
593 params->channels = 2;
594 params->sample_rate = 48000;
598 mrl = strchr( file, '?' );
602 char *name = strdup( ++mrl );
603 char *value = strchr( name, ':' );
608 char *t = strchr( value, '&' );
611 if ( !strcmp( name, "frame_rate" ) )
612 params->time_base.den = atoi( value );
613 else if ( !strcmp( name, "frame_rate_base" ) )
614 params->time_base.num = atoi( value );
615 else if ( !strcmp( name, "sample_rate" ) )
616 params->sample_rate = atoi( value );
617 else if ( !strcmp( name, "channel" ) )
618 params->channel = atoi( value );
619 else if ( !strcmp( name, "channels" ) )
620 params->channels = atoi( value );
621 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
622 else if ( !strcmp( name, "pix_fmt" ) )
623 params->pix_fmt = av_get_pix_fmt( value );
625 else if ( !strcmp( name, "width" ) )
626 params->width = atoi( value );
627 else if ( !strcmp( name, "height" ) )
628 params->height = atoi( value );
629 else if ( !strcmp( name, "standard" ) )
631 standard = strdup( value );
632 params->standard = standard;
634 else if ( !strcmp( name, "av" ) )
638 mrl = strchr( mrl, '&' );
642 // Now attempt to open the file
643 error = av_open_input_file( &context, file, format, 0, params ) < 0;
645 // Cleanup AVFormatParameters
649 // If successful, then try to get additional info
652 // Get the stream info
653 error = av_find_stream_info( context ) < 0;
655 // Continue if no error
658 // We will default to the first audio and video streams found
659 int audio_index = -1;
660 int video_index = -1;
662 // Find default audio and video streams
663 find_default_streams( properties, context, &audio_index, &video_index );
665 // Now set properties where we can (use default unknowns if required)
666 if ( context->duration != AV_NOPTS_VALUE )
668 // This isn't going to be accurate for all formats
669 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps );
670 mlt_properties_set_position( properties, "out", frames - 1 );
671 mlt_properties_set_position( properties, "length", frames );
674 if ( context->start_time != AV_NOPTS_VALUE )
675 self->start_time = context->start_time;
677 // Check if we're seekable
678 // avdevices are typically AVFMT_NOFILE and not seekable
679 self->seekable = !format || !( format->flags & AVFMT_NOFILE );
682 // protocols can indicate if they support seeking
683 #if LIBAVFORMAT_VERSION_MAJOR > 52
684 self->seekable = context->pb->seekable;
686 URLContext *uc = url_fileno( context->pb );
688 self->seekable = !uc->is_streamed;
691 if ( self->seekable )
693 self->seekable = av_seek_frame( context, -1, self->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
694 mlt_properties_set_int( properties, "seekable", self->seekable );
695 self->dummy_context = context;
696 av_open_input_file( &context, file, NULL, 0, NULL );
697 av_find_stream_info( context );
700 // Store selected audio and video indexes on properties
701 self->audio_index = audio_index;
702 self->video_index = video_index;
703 self->first_pts = -1;
704 self->last_position = POSITION_INITIAL;
706 // Fetch the width, height and aspect ratio
707 if ( video_index != -1 )
709 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
710 mlt_properties_set_int( properties, "width", codec_context->width );
711 mlt_properties_set_int( properties, "height", codec_context->height );
713 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
715 // Fetch the first frame of DV so we can read it directly
720 ret = av_read_frame( context, &pkt );
721 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
723 get_aspect_ratio( properties, context->streams[ video_index ], codec_context, &pkt );
730 get_aspect_ratio( properties, context->streams[ video_index ], codec_context, NULL );
733 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
734 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
736 sws_freeContext( context );
742 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
743 if ( av == 0 && audio_index != -1 && video_index != -1 )
745 // We'll use the open one as our video_format
746 self->video_format = context;
748 // And open again for our audio context
749 av_open_input_file( &context, file, NULL, 0, NULL );
750 av_find_stream_info( context );
753 self->audio_format = context;
755 else if ( av != 2 && video_index != -1 )
757 // We only have a video context
758 self->video_format = context;
760 else if ( audio_index != -1 )
762 // We only have an audio context
763 self->audio_format = context;
767 // Something has gone wrong
773 // Unlock the service
774 pthread_mutex_unlock( &self->audio_mutex );
775 pthread_mutex_unlock( &self->video_mutex );
780 void reopen_video( producer_avformat self, mlt_producer producer, mlt_properties properties )
782 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
783 pthread_mutex_lock( &self->audio_mutex );
785 if ( self->video_codec )
788 avcodec_close( self->video_codec );
791 self->video_codec = NULL;
792 if ( self->dummy_context )
793 av_close_input_file( self->dummy_context );
794 self->dummy_context = NULL;
795 if ( self->video_format )
796 av_close_input_file( self->video_format );
797 self->video_format = NULL;
799 int audio_index = self->audio_index;
800 int video_index = self->video_index;
802 mlt_events_block( properties, producer );
803 pthread_mutex_unlock( &self->audio_mutex );
804 pthread_mutex_unlock( &self->video_mutex );
805 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
806 mlt_properties_get( properties, "resource" ) );
807 pthread_mutex_lock( &self->video_mutex );
808 pthread_mutex_lock( &self->audio_mutex );
809 if ( self->dummy_context )
811 av_close_input_file( self->dummy_context );
812 self->dummy_context = NULL;
814 mlt_events_unblock( properties, producer );
815 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
816 #if LIBAVFORMAT_VERSION_MAJOR > 52
817 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
818 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
821 self->audio_index = audio_index;
822 if ( self->video_format && video_index > -1 )
824 self->video_index = video_index;
825 video_codec_init( self, video_index, properties );
828 pthread_mutex_unlock( &self->audio_mutex );
829 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
832 /** Convert a frame position to a time code.
835 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
837 return ( double )position / mlt_producer_get_fps( producer );
840 // Collect information about all audio streams
842 static void get_audio_streams_info( producer_avformat self )
844 // Fetch the audio format context
845 AVFormatContext *context = self->audio_format;
849 i < context->nb_streams;
852 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
854 AVCodecContext *codec_context = context->streams[i]->codec;
855 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
857 // If we don't have a codec and we can't initialise it, we can't do much more...
859 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
861 self->audio_streams++;
862 self->audio_max_stream = i;
863 self->total_channels += codec_context->channels;
864 if ( codec_context->channels > self->max_channel )
865 self->max_channel = codec_context->channels;
866 if ( codec_context->sample_rate > self->max_frequency )
867 self->max_frequency = codec_context->sample_rate;
868 avcodec_close( codec_context );
873 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
874 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
876 // Other audio-specific initializations
877 self->resample_factor = 1.0;
880 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
882 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
884 const int *new_coefficients;
886 int brightness, contrast, saturation;
888 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
889 &brightness, &contrast, &saturation ) != -1 )
891 // Don't change these from defaults unless explicitly told to.
892 if ( use_full_range >= 0 )
893 full_range = use_full_range;
894 switch ( colorspace )
900 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
903 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
906 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
909 new_coefficients = coefficients;
912 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
913 brightness, contrast, saturation );
918 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
919 mlt_image_format *format, int width, int height, int colorspace )
923 int flags = SWS_BILINEAR | SWS_ACCURATE_RND;
926 flags |= SWS_CPU_CAPS_MMX;
929 flags |= SWS_CPU_CAPS_MMX2;
932 if ( pix_fmt == PIX_FMT_RGB32 )
934 *format = mlt_image_rgb24a;
935 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
936 width, height, PIX_FMT_RGBA, flags, NULL, NULL, NULL);
938 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
939 set_luma_transfer( context, colorspace, full_range );
940 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
941 output.data, output.linesize);
942 sws_freeContext( context );
944 else if ( *format == mlt_image_yuv420p )
946 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
947 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
949 output.data[0] = buffer;
950 output.data[1] = buffer + width * height;
951 output.data[2] = buffer + ( 5 * width * height ) / 4;
952 output.linesize[0] = width;
953 output.linesize[1] = width >> 1;
954 output.linesize[2] = width >> 1;
955 set_luma_transfer( context, colorspace, full_range );
956 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
957 output.data, output.linesize);
958 sws_freeContext( context );
960 else if ( *format == mlt_image_rgb24 )
962 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
963 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
965 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
966 set_luma_transfer( context, colorspace, full_range );
967 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
968 output.data, output.linesize);
969 sws_freeContext( context );
971 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
973 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
974 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
976 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
977 set_luma_transfer( context, colorspace, full_range );
978 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
979 output.data, output.linesize);
980 sws_freeContext( context );
984 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
985 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
987 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
988 set_luma_transfer( context, colorspace, full_range );
989 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
990 output.data, output.linesize);
991 sws_freeContext( context );
994 if ( *format == mlt_image_yuv420p )
997 pict.data[0] = buffer;
998 pict.data[1] = buffer + width * height;
999 pict.data[2] = buffer + ( 5 * width * height ) / 4;
1000 pict.linesize[0] = width;
1001 pict.linesize[1] = width >> 1;
1002 pict.linesize[2] = width >> 1;
1003 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1005 else if ( *format == mlt_image_rgb24 )
1008 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1009 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1011 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
1014 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1015 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1020 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1021 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1026 /** Allocate the image buffer and set it on the frame.
1029 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1033 if ( codec_context->width == 0 || codec_context->height == 0 )
1036 *width = codec_context->width;
1037 *height = codec_context->height;
1039 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
1040 size = *width * ( *height + 1 ) * 4;
1042 size = mlt_image_format_size( *format, *width, *height, NULL );
1044 // Construct the output image
1045 *buffer = mlt_pool_alloc( size );
1047 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1054 /** Get an image from a frame.
1057 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1060 producer_avformat self = mlt_frame_pop_service( frame );
1061 mlt_producer producer = self->parent;
1063 // Get the properties from the frame
1064 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1066 // Obtain the frame number of this frame
1067 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1069 // Get the producer properties
1070 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1072 pthread_mutex_lock( &self->video_mutex );
1074 // Fetch the video format context
1075 AVFormatContext *context = self->video_format;
1077 // Get the video stream
1078 AVStream *stream = context->streams[ self->video_index ];
1080 // Get codec context
1081 AVCodecContext *codec_context = stream->codec;
1083 // Get the image cache
1084 if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1085 self->image_cache = mlt_cache_init();
1086 if ( self->image_cache )
1088 mlt_cache_item item = mlt_cache_get( self->image_cache, (void*) position );
1089 uint8_t *original = mlt_cache_item_data( item, (int*) format );
1092 // Set the resolution
1093 *width = codec_context->width;
1094 *height = codec_context->height;
1096 // Workaround 1088 encodings missing cropping info.
1097 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1101 int size = mlt_image_format_size( *format, *width, *height, NULL );
1104 *buffer = mlt_pool_alloc( size );
1105 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1106 memcpy( *buffer, original, size );
1107 mlt_cache_item_close( item );
1112 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1113 mlt_frame_set_image( frame, *buffer, size, NULL );
1115 self->got_picture = 1;
1117 goto exit_get_image;
1126 // Special case pause handling flag
1129 // Special case ffwd handling
1132 // We may want to use the source fps if available
1133 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1134 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1135 double fps = mlt_producer_get_fps( producer );
1137 // This is the physical frame position in the source
1138 int req_position = ( int )( position / fps * source_fps + 0.5 );
1140 // Determines if we have to decode all frames in a sequence
1141 // Temporary hack to improve intra frame only
1142 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
1143 strcmp( codec_context->codec->name, "dvvideo" ) &&
1144 strcmp( codec_context->codec->name, "huffyuv" ) &&
1145 strcmp( codec_context->codec->name, "mjpeg" ) &&
1146 strcmp( codec_context->codec->name, "rawvideo" );
1148 int last_position = self->last_position;
1150 // Turn on usage of new seek API and PTS for seeking
1151 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1152 if ( mlt_properties_get( properties, "new_seek" ) )
1153 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1155 // Seek if necessary
1156 if ( position != self->video_expected || last_position < 0 )
1158 if ( self->av_frame && position + 1 == self->video_expected )
1160 // We're paused - use last image
1163 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
1165 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1166 ignore = ( int )( ( position - self->video_expected ) / fps * source_fps );
1167 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1169 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || last_position < 0 ) )
1171 if ( use_new_seek && last_position == POSITION_INITIAL )
1173 // find first key frame
1177 while ( ret >= 0 && toscan-- > 0 )
1179 ret = av_read_frame( context, &pkt );
1180 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
1182 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) );
1183 self->first_pts = pkt.pts;
1186 av_free_packet( &pkt );
1189 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1192 // Calculate the timestamp for the requested frame
1196 timestamp = ( req_position - 0.1 / source_fps ) /
1197 ( av_q2d( stream->time_base ) * source_fps );
1198 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %"PRId64" ", req_position, timestamp );
1199 if ( self->first_pts > 0 )
1200 timestamp += self->first_pts;
1201 else if ( context->start_time != AV_NOPTS_VALUE )
1202 timestamp += context->start_time;
1206 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
1207 if ( context->start_time != AV_NOPTS_VALUE )
1208 timestamp += context->start_time;
1211 timestamp -= AV_TIME_BASE;
1212 if ( timestamp < 0 )
1214 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %d\n",
1215 timestamp, position, self->video_expected, last_position );
1217 // Seek to the timestamp
1220 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1221 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1223 else if ( req_position > 0 || last_position <= 0 )
1225 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
1229 // Re-open video stream when rewinding to beginning from somewhere else.
1230 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1231 // not reliably seeking to the first frame across formats.
1232 reopen_video( self, producer, properties );
1233 context = self->video_format;
1234 stream = context->streams[ self->video_index ];
1235 codec_context = stream->codec;
1238 // Remove the cached info relating to the previous position
1239 self->current_position = POSITION_INVALID;
1240 self->last_position = POSITION_INVALID;
1241 av_freep( &self->av_frame );
1245 // flush any pictures still in decode buffer
1246 avcodec_flush_buffers( codec_context );
1251 // Duplicate the last image if necessary
1252 if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture && self->seekable
1254 || self->current_position == req_position
1255 || ( !use_new_seek && self->current_position > req_position ) ) )
1258 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1260 // Workaround 1088 encodings missing cropping info.
1261 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1264 if ( self->vdpau && self->vdpau->buffer )
1267 picture.data[0] = self->vdpau->buffer;
1268 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1269 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1270 picture.linesize[0] = codec_context->width;
1271 picture.linesize[1] = codec_context->width / 2;
1272 picture.linesize[2] = codec_context->width / 2;
1273 convert_image( (AVFrame*) &picture, *buffer,
1274 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1278 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1279 format, *width, *height, self->colorspace );
1282 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1287 int int_position = 0;
1288 int decode_errors = 0;
1289 int got_picture = 0;
1291 av_init_packet( &pkt );
1293 // Construct an AVFrame for YUV422 conversion
1294 if ( !self->av_frame )
1295 self->av_frame = avcodec_alloc_frame( );
1297 while( ret >= 0 && !got_picture )
1300 ret = av_read_frame( context, &pkt );
1302 // We only deal with video from the selected video_index
1303 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1305 // Determine time code of the packet
1308 int64_t pts = pkt.pts;
1309 if ( self->first_pts > 0 )
1310 pts -= self->first_pts;
1311 else if ( context->start_time != AV_NOPTS_VALUE )
1312 pts -= context->start_time;
1313 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1314 if ( pkt.pts == AV_NOPTS_VALUE )
1316 self->invalid_pts_counter++;
1317 if ( self->invalid_pts_counter > 20 )
1319 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1320 mlt_properties_set_int( properties, "new_seek", 0 );
1321 int_position = req_position;
1327 self->invalid_pts_counter = 0;
1329 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1330 pkt.pts, req_position, self->current_position, int_position );
1334 if ( self->seekable && pkt.dts != AV_NOPTS_VALUE )
1336 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1337 if ( context->start_time != AV_NOPTS_VALUE )
1338 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1339 last_position = self->last_position;
1340 if ( int_position == last_position )
1341 int_position = last_position + 1;
1345 int_position = req_position;
1347 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1348 pkt.dts, req_position, self->current_position, int_position );
1349 // Make a dumb assumption on streams that contain wild timestamps
1350 if ( abs( req_position - int_position ) > 999 )
1352 int_position = req_position;
1353 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1356 self->last_position = int_position;
1359 if ( must_decode || int_position >= req_position )
1362 if ( g_vdpau && self->vdpau )
1364 if ( g_vdpau->producer != self )
1366 vdpau_decoder_close();
1367 vdpau_decoder_init( self );
1370 self->vdpau->is_decoded = 0;
1373 codec_context->reordered_opaque = pkt.pts;
1374 if ( int_position >= req_position )
1375 codec_context->skip_loop_filter = AVDISCARD_NONE;
1376 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1377 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1379 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1381 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1384 if ( ++decode_errors <= 10 )
1397 // Determine time code of the packet
1398 int64_t pts = self->av_frame->reordered_opaque;
1399 if ( self->first_pts > 0 )
1400 pts -= self->first_pts;
1401 else if ( context->start_time != AV_NOPTS_VALUE )
1402 pts -= context->start_time;
1403 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1404 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, self->av_frame->key_frame );
1407 if ( int_position < req_position )
1412 else if ( int_position >= req_position )
1415 codec_context->skip_loop_filter = AVDISCARD_NONE;
1417 else if ( ignore -- )
1422 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1425 // Now handle the picture if we have one
1428 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1430 // Workaround 1088 encodings missing cropping info.
1431 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1436 if ( self->vdpau->is_decoded )
1438 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1440 uint32_t pitches[3];
1441 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1443 if ( !self->vdpau->buffer )
1444 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1445 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1446 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1447 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1448 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1449 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1450 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1452 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1453 if ( status == VDP_STATUS_OK )
1455 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1456 format, *width, *height, self->colorspace );
1460 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1461 image_size = self->vdpau->is_decoded = 0;
1466 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1467 image_size = got_picture = 0;
1472 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1473 format, *width, *height, self->colorspace );
1474 self->top_field_first |= self->av_frame->top_field_first;
1475 self->current_position = int_position;
1476 self->got_picture = 1;
1484 av_free_packet( &pkt );
1488 if ( self->got_picture && image_size > 0 && self->image_cache )
1490 // Copy buffer to image cache
1491 uint8_t *image = mlt_pool_alloc( image_size );
1492 memcpy( image, *buffer, image_size );
1493 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1495 // Try to duplicate last image if there was a decoding failure
1496 else if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1499 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1501 // Workaround 1088 encodings missing cropping info.
1502 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1505 if ( self->vdpau && self->vdpau->buffer )
1508 picture.data[0] = self->vdpau->buffer;
1509 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1510 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1511 picture.linesize[0] = codec_context->width;
1512 picture.linesize[1] = codec_context->width / 2;
1513 picture.linesize[2] = codec_context->width / 2;
1514 convert_image( (AVFrame*) &picture, *buffer,
1515 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1519 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1520 format, *width, *height, self->colorspace );
1521 self->got_picture = 1;
1524 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1527 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1528 self->video_expected = position + 1;
1532 pthread_mutex_unlock( &self->video_mutex );
1534 // Set the progressive flag
1535 if ( mlt_properties_get( properties, "force_progressive" ) )
1536 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1537 else if ( self->av_frame )
1538 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1540 // Set the field order property for this frame
1541 if ( mlt_properties_get( properties, "force_tff" ) )
1542 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1544 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1546 // Set immutable properties of the selected track's (or overridden) source attributes.
1547 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1548 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1549 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1550 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1552 return !self->got_picture;
1555 /** Process properties as AVOptions and apply to AV context obj
1558 static void apply_properties( void *obj, mlt_properties properties, int flags )
1561 int count = mlt_properties_count( properties );
1562 for ( i = 0; i < count; i++ )
1564 const char *opt_name = mlt_properties_get_name( properties, i );
1565 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1566 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1569 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1570 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1571 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1572 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1574 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1580 /** Initialize the video codec context.
1583 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1585 // Initialise the codec if necessary
1586 if ( !self->video_codec )
1588 // Get the video stream
1589 AVStream *stream = self->video_format->streams[ index ];
1591 // Get codec context
1592 AVCodecContext *codec_context = stream->codec;
1595 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1597 if ( codec_context->codec_id == CODEC_ID_H264 )
1599 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1601 if ( vdpau_init( self ) )
1603 self->video_codec = codec_context;
1604 if ( !vdpau_decoder_init( self ) )
1605 vdpau_decoder_close();
1609 codec = avcodec_find_decoder( codec_context->codec_id );
1613 // Initialise multi-threading
1614 int thread_count = mlt_properties_get_int( properties, "threads" );
1615 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1616 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1617 if ( thread_count > 1 )
1618 codec_context->thread_count = thread_count;
1620 // If we don't have a codec and we can't initialise it, we can't do much more...
1622 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1624 // Now store the codec with its destructor
1625 self->video_codec = codec_context;
1629 // Remember that we can't use this later
1630 self->video_index = -1;
1636 // Process properties as AVOptions
1637 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1638 #if LIBAVCODEC_VERSION_MAJOR > 52
1639 if ( codec->priv_class && codec_context->priv_data )
1640 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1643 // Reset some image properties
1644 mlt_properties_set_int( properties, "width", self->video_codec->width );
1645 mlt_properties_set_int( properties, "height", self->video_codec->height );
1646 // For DV, we'll just use the saved aspect ratio
1647 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1648 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1650 // Determine the fps first from the codec
1651 double source_fps = (double) self->video_codec->time_base.den /
1652 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1654 if ( mlt_properties_get( properties, "force_fps" ) )
1656 source_fps = mlt_properties_get_double( properties, "force_fps" );
1657 stream->time_base = av_d2q( source_fps, 1024 );
1658 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1659 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1663 // If the muxer reports a frame rate different than the codec
1664 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1665 double muxer_fps = av_q2d( stream->avg_frame_rate );
1666 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1667 muxer_fps = av_q2d( stream->r_frame_rate );
1669 double muxer_fps = av_q2d( stream->r_frame_rate );
1671 // Choose the lesser - the wrong tends to be off by some multiple of 10
1672 source_fps = FFMIN( source_fps, muxer_fps );
1673 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1675 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1676 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1678 else if ( muxer_fps > 0 )
1680 AVRational frame_rate = stream->r_frame_rate;
1681 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1682 // avg_frame_rate gives some approximate value that does not well match the media.
1683 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1684 // results in some very choppy output, but some value slightly different works
1686 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1687 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1688 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1690 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1691 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1695 source_fps = mlt_producer_get_fps( self->parent );
1696 AVRational frame_rate = av_d2q( source_fps, 255 );
1697 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1698 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1702 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1703 if ( source_fps > 0 )
1704 mlt_properties_set_double( properties, "source_fps", source_fps );
1706 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
1708 // Set the YUV colorspace from override or detect
1709 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1710 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1711 if ( ! self->colorspace )
1713 switch ( self->video_codec->colorspace )
1715 case AVCOL_SPC_SMPTE240M:
1716 self->colorspace = 240;
1718 case AVCOL_SPC_BT470BG:
1719 case AVCOL_SPC_SMPTE170M:
1720 self->colorspace = 601;
1722 case AVCOL_SPC_BT709:
1723 self->colorspace = 709;
1726 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1727 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1732 // Let apps get chosen colorspace
1733 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1735 return self->video_codec && self->video_index > -1;
1738 /** Set up video handling.
1741 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1744 mlt_producer producer = self->parent;
1746 // Get the properties
1747 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1749 // Fetch the video format context
1750 AVFormatContext *context = self->video_format;
1752 // Get the video_index
1753 int index = mlt_properties_get_int( properties, "video_index" );
1755 // Reopen the file if necessary
1756 if ( !context && index > -1 )
1758 mlt_events_block( properties, producer );
1759 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1760 mlt_properties_get( properties, "resource" ) );
1761 context = self->video_format;
1762 if ( self->dummy_context )
1764 av_close_input_file( self->dummy_context );
1765 self->dummy_context = NULL;
1767 mlt_events_unblock( properties, producer );
1768 if ( self->audio_format && !self->audio_streams )
1769 get_audio_streams_info( self );
1771 // Process properties as AVOptions
1774 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1775 #if LIBAVFORMAT_VERSION_MAJOR > 52
1776 if ( context->iformat && context->iformat->priv_class && context->priv_data )
1777 apply_properties( context->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
1782 // Exception handling for video_index
1783 if ( context && index >= (int) context->nb_streams )
1785 // Get the last video stream
1786 for ( index = context->nb_streams - 1;
1787 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1789 mlt_properties_set_int( properties, "video_index", index );
1791 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1793 // Invalidate the video stream
1795 mlt_properties_set_int( properties, "video_index", index );
1798 // Update the video properties if the index changed
1799 if ( index != self->video_index )
1801 // Reset the video properties if the index changed
1802 self->video_index = index;
1803 if ( self->video_codec )
1806 avcodec_close( self->video_codec );
1809 self->video_codec = NULL;
1812 // Get the frame properties
1813 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1816 if ( context && index > -1 && video_codec_init( self, index, properties ) )
1818 // Set the frame properties
1819 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1820 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1821 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1823 // Set the width and height
1824 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
1825 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
1826 // real_width and real_height are deprecated in favor of meta.media.width and .height
1827 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
1828 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
1829 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
1830 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
1831 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1832 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
1834 // Workaround 1088 encodings missing cropping info.
1835 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1837 mlt_properties_set_int( properties, "meta.media.height", 1080 );
1838 mlt_properties_set_int( frame_properties, "real_height", 1080 );
1841 // Add our image operation
1842 mlt_frame_push_service( frame, self );
1843 mlt_frame_push_get_image( frame, producer_get_image );
1847 // If something failed, use test card image
1848 mlt_properties_set_int( frame_properties, "test_image", 1 );
1852 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
1856 // Seek if necessary
1857 if ( position != self->audio_expected )
1859 if ( position + 1 == self->audio_expected )
1861 // We're paused - silence required
1864 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
1866 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1867 *ignore = position - self->audio_expected;
1869 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
1871 AVFormatContext *context = self->audio_format;
1872 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1873 if ( context->start_time != AV_NOPTS_VALUE )
1874 timestamp += context->start_time;
1875 if ( timestamp < 0 )
1878 // Set to the real timecode
1879 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1882 // Clear the usage in the audio buffer
1883 int i = MAX_AUDIO_STREAMS + 1;
1885 self->audio_used[i - 1] = 0;
1891 static int sample_bytes( AVCodecContext *context )
1893 #if LIBAVCODEC_VERSION_MAJOR > 52
1894 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
1896 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
1900 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
1902 // Fetch the audio_format
1903 AVFormatContext *context = self->audio_format;
1905 // Get the current stream index
1906 int index = pkt.stream_index;
1908 // Get codec context
1909 AVCodecContext *codec_context = self->audio_codec[ index ];
1911 // Obtain the resample context if it exists (not always needed)
1912 ReSampleContext *resample = self->audio_resample[ index ];
1914 // Obtain the audio buffers
1915 uint8_t *audio_buffer = self->audio_buffer[ index ];
1916 uint8_t *decode_buffer = self->decode_buffer[ index ];
1918 int audio_used = self->audio_used[ index ];
1919 uint8_t *ptr = pkt.data;
1923 while ( ptr && ret >= 0 && len > 0 )
1925 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
1926 int data_size = self->audio_buffer_size[ index ];
1929 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1930 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
1931 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1932 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1934 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1938 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
1942 pkt.size = len -= ret;
1943 pkt.data = ptr += ret;
1945 // If decoded successfully
1946 if ( data_size > 0 )
1948 // Figure out how many samples will be needed after resampling
1949 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
1950 int samples_needed = self->resample_factor * convert_samples;
1952 // Resize audio buffer to prevent overflow
1953 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
1955 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
1956 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
1960 // Copy to audio buffer while resampling
1961 uint8_t *source = decode_buffer;
1962 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
1963 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
1967 // Straight copy to audio buffer
1968 memcpy( &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ], decode_buffer, data_size );
1969 audio_used += convert_samples;
1973 while ( *ignore && audio_used > samples )
1976 audio_used -= samples;
1977 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
1978 audio_used * sizeof_sample );
1983 // If we're behind, ignore this packet
1986 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
1987 int req_position = ( int )( timecode * fps + 0.5 );
1988 int int_position = ( int )( current_pts * fps + 0.5 );
1989 if ( context->start_time != AV_NOPTS_VALUE )
1990 int_position -= ( int )( fps * context->start_time / AV_TIME_BASE + 0.5 );
1992 if ( self->seekable && *ignore == 0 )
1994 if ( int_position < req_position )
1995 // We are behind, so skip some
1997 else if ( int_position > req_position + 2 )
1998 // We are ahead, so seek backwards some more
1999 seek_audio( self, req_position, timecode - 1.0, ignore );
2003 self->audio_used[ index ] = audio_used;
2008 /** Get the audio from a frame.
2010 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2013 producer_avformat self = mlt_frame_pop_audio( frame );
2015 pthread_mutex_lock( &self->audio_mutex );
2017 // Obtain the frame number of this frame
2018 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
2020 // Calculate the real time code
2021 double real_timecode = producer_time_of_frame( self->parent, position );
2023 // Get the producer fps
2024 double fps = mlt_producer_get_fps( self->parent );
2026 // Number of frames to ignore (for ffwd)
2029 // Flag for paused (silence)
2030 int paused = seek_audio( self, position, real_timecode, &ignore );
2032 // Fetch the audio_format
2033 AVFormatContext *context = self->audio_format;
2035 int sizeof_sample = sizeof( int16_t );
2037 // Determine the tracks to use
2038 int index = self->audio_index;
2039 int index_max = self->audio_index + 1;
2040 if ( self->audio_index == INT_MAX )
2043 index_max = context->nb_streams;
2044 *channels = self->total_channels;
2045 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2046 *frequency = FFMAX( self->max_frequency, *frequency );
2049 // Initialize the resamplers and buffers
2050 for ( ; index < index_max; index++ )
2052 // Get codec context
2053 AVCodecContext *codec_context = self->audio_codec[ index ];
2055 if ( codec_context && !self->audio_buffer[ index ] )
2057 // Check for resample and create if necessary
2058 if ( codec_context->channels <= 2 )
2060 // Determine by how much resampling will increase number of samples
2061 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2062 resample_factor *= (double) *frequency / codec_context->sample_rate;
2063 if ( resample_factor > self->resample_factor )
2064 self->resample_factor = resample_factor;
2066 // Create the resampler
2067 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2068 self->audio_resample[ index ] = av_audio_resample_init(
2069 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2070 codec_context->channels, *frequency, codec_context->sample_rate,
2071 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2073 self->audio_resample[ index ] = audio_resample_init(
2074 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2075 codec_context->channels, *frequency, codec_context->sample_rate );
2080 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2081 sizeof_sample = sample_bytes( codec_context );
2084 // Check for audio buffer and create if necessary
2085 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2086 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2088 // Check for decoder buffer and create if necessary
2089 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2093 // Get the audio if required
2100 av_init_packet( &pkt );
2102 // If not resampling, give consumer more than requested.
2103 // It requested number samples based on requested frame rate.
2104 // Do not clean this up with a samples *= ...!
2105 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2106 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2108 while ( ret >= 0 && !got_audio )
2110 // Check if the buffer already contains the samples required
2111 if ( self->audio_index != INT_MAX && self->audio_used[ self->audio_index ] >= *samples && ignore == 0 )
2118 ret = av_read_frame( context, &pkt );
2120 // We only deal with audio from the selected audio index
2121 index = pkt.stream_index;
2122 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2123 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2125 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2126 self->audio_codec[index]->channels : *channels;
2127 ret = decode_audio( self, &ignore, pkt, channels2, *samples, real_timecode, fps );
2129 av_free_packet( &pkt );
2131 if ( self->audio_index == INT_MAX && ret >= 0 )
2133 // Determine if there is enough audio for all streams
2135 for ( index = 0; index < context->nb_streams; index++ )
2137 if ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples )
2143 // Set some additional return values
2144 *format = mlt_audio_s16;
2145 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2147 index = self->audio_index;
2148 *channels = self->audio_codec[ index ]->channels;
2149 *frequency = self->audio_codec[ index ]->sample_rate;
2150 *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2151 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2153 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2155 else if ( self->audio_index == INT_MAX )
2157 // This only works if all audio tracks have the same sample format.
2158 for ( index = 0; index < index_max; index++ )
2159 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2161 *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2162 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2164 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2169 // Allocate and set the frame's audio buffer
2170 int size = mlt_audio_format_size( *format, *samples, *channels );
2171 *buffer = mlt_pool_alloc( size );
2172 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2174 // Interleave tracks if audio_index=all
2175 if ( self->audio_index == INT_MAX )
2177 uint8_t *dest = *buffer;
2179 for ( i = 0; i < *samples; i++ )
2181 for ( index = 0; index < index_max; index++ )
2182 if ( self->audio_codec[ index ] )
2184 int current_channels = self->audio_codec[ index ]->channels;
2185 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2186 memcpy( dest, src, current_channels * sizeof_sample );
2187 dest += current_channels * sizeof_sample;
2190 for ( index = 0; index < index_max; index++ )
2191 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2193 int current_channels = self->audio_codec[ index ]->channels;
2194 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2195 self->audio_used[index] -= *samples;
2196 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2199 // Copy a single track to the output buffer
2202 index = self->audio_index;
2204 // Now handle the audio if we have enough
2205 if ( self->audio_used[ index ] > 0 )
2207 uint8_t *src = self->audio_buffer[ index ];
2208 // copy samples from audio_buffer
2209 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2210 memcpy( *buffer, src, size * *channels * sizeof_sample );
2211 // supply the remaining requested samples as silence
2212 if ( *samples > self->audio_used[ index ] )
2213 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2214 // reposition the samples within audio_buffer
2215 self->audio_used[ index ] -= size;
2216 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2220 // Otherwise fill with silence
2221 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2227 // Get silence and don't touch the context
2228 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2231 // Regardless of speed (other than paused), we expect to get the next frame
2233 self->audio_expected = position + 1;
2235 pthread_mutex_unlock( &self->audio_mutex );
2240 /** Initialize the audio codec context.
2243 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2245 // Initialise the codec if necessary
2246 if ( !self->audio_codec[ index ] )
2248 // Get codec context
2249 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2252 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2254 // If we don't have a codec and we can't initialise it, we can't do much more...
2256 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2258 // Now store the codec with its destructor
2259 if ( self->audio_codec[ index ] )
2260 avcodec_close( self->audio_codec[ index ] );
2261 self->audio_codec[ index ] = codec_context;
2265 // Remember that we can't use self later
2266 self->audio_index = -1;
2270 // Process properties as AVOptions
2271 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2272 #if LIBAVCODEC_VERSION_MAJOR > 52
2273 if ( codec && codec->priv_class && codec_context->priv_data )
2274 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2277 return self->audio_codec[ index ] && self->audio_index > -1;
2280 /** Set up audio handling.
2283 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2286 mlt_producer producer = self->parent;
2288 // Get the properties
2289 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2291 // Fetch the audio format context
2292 AVFormatContext *context = self->audio_format;
2294 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2296 // Get the audio_index
2297 int index = mlt_properties_get_int( properties, "audio_index" );
2299 // Handle all audio tracks
2300 if ( self->audio_index > -1 &&
2301 mlt_properties_get( properties, "audio_index" ) &&
2302 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2305 // Reopen the file if necessary
2306 if ( !context && self->audio_index > -1 && index > -1 )
2308 mlt_events_block( properties, producer );
2309 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2310 mlt_properties_get( properties, "resource" ) );
2311 context = self->audio_format;
2312 if ( self->dummy_context )
2314 av_close_input_file( self->dummy_context );
2315 self->dummy_context = NULL;
2317 mlt_events_unblock( properties, producer );
2318 if ( self->audio_format )
2319 get_audio_streams_info( self );
2322 // Exception handling for audio_index
2323 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2325 for ( index = context->nb_streams - 1;
2326 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2328 mlt_properties_set_int( properties, "audio_index", index );
2330 if ( context && index > -1 && index < INT_MAX &&
2331 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2333 index = self->audio_index;
2334 mlt_properties_set_int( properties, "audio_index", index );
2337 // Update the audio properties if the index changed
2338 if ( context && index > -1 && index != self->audio_index )
2340 if ( self->audio_codec[ self->audio_index ] )
2343 avcodec_close( self->audio_codec[ self->audio_index ] );
2346 self->audio_codec[ self->audio_index ] = NULL;
2348 if ( self->audio_index != -1 )
2349 self->audio_index = index;
2354 if ( context && index == INT_MAX )
2356 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2357 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2358 for ( index = 0; index < context->nb_streams; index++ )
2360 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2361 audio_codec_init( self, index, properties );
2364 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2366 // Set the frame properties
2367 if ( index < INT_MAX )
2369 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2370 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2373 if ( context && index > -1 )
2375 // Add our audio operation
2376 mlt_frame_push_audio( frame, self );
2377 mlt_frame_push_audio( frame, producer_get_audio );
2381 /** Our get frame implementation.
2384 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2386 // Access the private data
2387 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2388 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2389 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2394 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2395 producer->child = self;
2396 self->parent = producer;
2397 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2398 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2401 // Create an empty frame
2402 *frame = mlt_frame_init( service);
2406 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2410 mlt_cache_item_close( cache_item );
2414 // Update timecode on the frame we're creating
2415 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2417 // Set the position of this producer
2418 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
2421 producer_set_up_video( self, *frame );
2424 producer_set_up_audio( self, *frame );
2426 // Calculate the next timecode
2427 mlt_producer_prepare_next( producer );
2432 static void producer_avformat_close( producer_avformat self )
2434 mlt_log_debug( NULL, "producer_avformat_close\n" );
2436 av_free( self->av_frame );
2439 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2441 if ( self->audio_resample[i] )
2442 audio_resample_close( self->audio_resample[i] );
2443 mlt_pool_release( self->audio_buffer[i] );
2444 av_free( self->decode_buffer[i] );
2445 if ( self->audio_codec[i] )
2446 avcodec_close( self->audio_codec[i] );
2448 if ( self->video_codec )
2449 avcodec_close( self->video_codec );
2450 if ( self->dummy_context )
2451 av_close_input_file( self->dummy_context );
2452 if ( self->audio_format )
2453 av_close_input_file( self->audio_format );
2454 if ( self->video_format )
2455 av_close_input_file( self->video_format );
2458 vdpau_producer_close( self );
2460 if ( self->image_cache )
2461 mlt_cache_close( self->image_cache );
2462 pthread_mutex_destroy( &self->audio_mutex );
2463 pthread_mutex_destroy( &self->video_mutex );
2467 static void producer_close( mlt_producer parent )
2469 // Remove this instance from the cache
2470 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2473 parent->close = NULL;
2474 mlt_producer_close( parent );