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 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 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps );
665 mlt_properties_set_position( properties, "out", frames - 1 );
666 mlt_properties_set_position( properties, "length", frames );
669 if ( context->start_time != AV_NOPTS_VALUE )
670 self->start_time = context->start_time;
672 // Check if we're seekable
673 // avdevices are typically AVFMT_NOFILE and not seekable
674 self->seekable = !format || !( format->flags & AVFMT_NOFILE );
677 // protocols can indicate if they support seeking
678 #if LIBAVFORMAT_VERSION_MAJOR > 52
679 self->seekable = context->pb->seekable;
681 URLContext *uc = url_fileno( context->pb );
683 self->seekable = !uc->is_streamed;
686 if ( self->seekable )
688 self->seekable = av_seek_frame( context, -1, self->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
689 mlt_properties_set_int( properties, "seekable", self->seekable );
690 self->dummy_context = context;
691 av_open_input_file( &context, file, NULL, 0, NULL );
692 av_find_stream_info( context );
695 // Store selected audio and video indexes on properties
696 self->audio_index = audio_index;
697 self->video_index = video_index;
698 self->first_pts = -1;
699 self->last_position = POSITION_INITIAL;
701 // Fetch the width, height and aspect ratio
702 if ( video_index != -1 )
704 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
705 mlt_properties_set_int( properties, "width", codec_context->width );
706 mlt_properties_set_int( properties, "height", codec_context->height );
708 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
710 // Fetch the first frame of DV so we can read it directly
715 ret = av_read_frame( context, &pkt );
716 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
718 get_aspect_ratio( properties, context->streams[ video_index ], codec_context, &pkt );
725 get_aspect_ratio( properties, context->streams[ video_index ], codec_context, NULL );
728 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
729 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
731 sws_freeContext( context );
737 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
738 if ( av == 0 && audio_index != -1 && video_index != -1 )
740 // We'll use the open one as our video_format
741 self->video_format = context;
743 // And open again for our audio context
744 av_open_input_file( &context, file, NULL, 0, NULL );
745 av_find_stream_info( context );
748 self->audio_format = context;
750 else if ( av != 2 && video_index != -1 )
752 // We only have a video context
753 self->video_format = context;
755 else if ( audio_index != -1 )
757 // We only have an audio context
758 self->audio_format = context;
762 // Something has gone wrong
768 // Unlock the service
769 pthread_mutex_unlock( &self->audio_mutex );
770 pthread_mutex_unlock( &self->video_mutex );
775 void reopen_video( producer_avformat self, mlt_producer producer, mlt_properties properties )
777 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
778 pthread_mutex_lock( &self->audio_mutex );
780 if ( self->video_codec )
783 avcodec_close( self->video_codec );
786 self->video_codec = NULL;
787 if ( self->dummy_context )
788 av_close_input_file( self->dummy_context );
789 self->dummy_context = NULL;
790 if ( self->video_format )
791 av_close_input_file( self->video_format );
792 self->video_format = NULL;
794 int audio_index = self->audio_index;
795 int video_index = self->video_index;
797 mlt_events_block( properties, producer );
798 pthread_mutex_unlock( &self->audio_mutex );
799 pthread_mutex_unlock( &self->video_mutex );
800 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
801 mlt_properties_get( properties, "resource" ) );
802 pthread_mutex_lock( &self->video_mutex );
803 pthread_mutex_lock( &self->audio_mutex );
804 if ( self->dummy_context )
806 av_close_input_file( self->dummy_context );
807 self->dummy_context = NULL;
809 mlt_events_unblock( properties, producer );
810 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
811 #if LIBAVFORMAT_VERSION_MAJOR > 52
812 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
813 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
816 self->audio_index = audio_index;
817 if ( self->video_format && video_index > -1 )
819 self->video_index = video_index;
820 video_codec_init( self, video_index, properties );
823 pthread_mutex_unlock( &self->audio_mutex );
824 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
827 /** Convert a frame position to a time code.
830 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
832 return ( double )position / mlt_producer_get_fps( producer );
835 // Collect information about all audio streams
837 static void get_audio_streams_info( producer_avformat self )
839 // Fetch the audio format context
840 AVFormatContext *context = self->audio_format;
844 i < context->nb_streams;
847 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
849 AVCodecContext *codec_context = context->streams[i]->codec;
850 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
852 // If we don't have a codec and we can't initialise it, we can't do much more...
854 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
856 self->audio_streams++;
857 self->audio_max_stream = i;
858 self->total_channels += codec_context->channels;
859 if ( codec_context->channels > self->max_channel )
860 self->max_channel = codec_context->channels;
861 if ( codec_context->sample_rate > self->max_frequency )
862 self->max_frequency = codec_context->sample_rate;
863 avcodec_close( codec_context );
868 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
869 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
871 // Other audio-specific initializations
872 self->resample_factor = 1.0;
875 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
877 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
879 const int *new_coefficients;
881 int brightness, contrast, saturation;
883 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
884 &brightness, &contrast, &saturation ) != -1 )
886 // Don't change these from defaults unless explicitly told to.
887 if ( use_full_range >= 0 )
888 full_range = use_full_range;
889 switch ( colorspace )
895 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
898 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
901 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
904 new_coefficients = coefficients;
907 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
908 brightness, contrast, saturation );
913 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
914 mlt_image_format *format, int width, int height, int colorspace )
918 int flags = SWS_BILINEAR | SWS_ACCURATE_RND;
921 flags |= SWS_CPU_CAPS_MMX;
924 flags |= SWS_CPU_CAPS_MMX2;
927 if ( pix_fmt == PIX_FMT_RGB32 )
929 *format = mlt_image_rgb24a;
930 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
931 width, height, PIX_FMT_RGBA, flags, NULL, NULL, NULL);
933 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
934 set_luma_transfer( context, colorspace, full_range );
935 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
936 output.data, output.linesize);
937 sws_freeContext( context );
939 else if ( *format == mlt_image_yuv420p )
941 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
942 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
944 output.data[0] = buffer;
945 output.data[1] = buffer + width * height;
946 output.data[2] = buffer + ( 5 * width * height ) / 4;
947 output.linesize[0] = width;
948 output.linesize[1] = width >> 1;
949 output.linesize[2] = width >> 1;
950 set_luma_transfer( context, colorspace, full_range );
951 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
952 output.data, output.linesize);
953 sws_freeContext( context );
955 else if ( *format == mlt_image_rgb24 )
957 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
958 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
960 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
961 set_luma_transfer( context, colorspace, full_range );
962 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
963 output.data, output.linesize);
964 sws_freeContext( context );
966 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
968 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
969 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
971 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
972 set_luma_transfer( context, colorspace, full_range );
973 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
974 output.data, output.linesize);
975 sws_freeContext( context );
979 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
980 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
982 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
983 set_luma_transfer( context, colorspace, full_range );
984 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
985 output.data, output.linesize);
986 sws_freeContext( context );
989 if ( *format == mlt_image_yuv420p )
992 pict.data[0] = buffer;
993 pict.data[1] = buffer + width * height;
994 pict.data[2] = buffer + ( 5 * width * height ) / 4;
995 pict.linesize[0] = width;
996 pict.linesize[1] = width >> 1;
997 pict.linesize[2] = width >> 1;
998 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
1000 else if ( *format == mlt_image_rgb24 )
1003 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1004 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
1006 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
1009 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
1010 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
1015 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1016 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
1021 /** Allocate the image buffer and set it on the frame.
1024 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1028 if ( codec_context->width == 0 || codec_context->height == 0 )
1031 *width = codec_context->width;
1032 *height = codec_context->height;
1034 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
1035 size = *width * ( *height + 1 ) * 4;
1037 size = mlt_image_format_size( *format, *width, *height, NULL );
1039 // Construct the output image
1040 *buffer = mlt_pool_alloc( size );
1042 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1049 /** Get an image from a frame.
1052 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1055 producer_avformat self = mlt_frame_pop_service( frame );
1056 mlt_producer producer = self->parent;
1058 // Get the properties from the frame
1059 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1061 // Obtain the frame number of this frame
1062 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1064 // Get the producer properties
1065 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1067 pthread_mutex_lock( &self->video_mutex );
1069 // Fetch the video format context
1070 AVFormatContext *context = self->video_format;
1072 // Get the video stream
1073 AVStream *stream = context->streams[ self->video_index ];
1075 // Get codec context
1076 AVCodecContext *codec_context = stream->codec;
1078 // Get the image cache
1079 if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1080 self->image_cache = mlt_cache_init();
1081 if ( self->image_cache )
1083 mlt_cache_item item = mlt_cache_get( self->image_cache, (void*) position );
1084 uint8_t *original = mlt_cache_item_data( item, (int*) format );
1087 // Set the resolution
1088 *width = codec_context->width;
1089 *height = codec_context->height;
1091 // Workaround 1088 encodings missing cropping info.
1092 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1096 int size = mlt_image_format_size( *format, *width, *height, NULL );
1099 *buffer = mlt_pool_alloc( size );
1100 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1101 memcpy( *buffer, original, size );
1102 mlt_cache_item_close( item );
1107 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1108 mlt_frame_set_image( frame, *buffer, size, NULL );
1110 self->got_picture = 1;
1112 goto exit_get_image;
1121 // Special case pause handling flag
1124 // Special case ffwd handling
1127 // We may want to use the source fps if available
1128 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1129 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1130 double fps = mlt_producer_get_fps( producer );
1132 // This is the physical frame position in the source
1133 int req_position = ( int )( position / fps * source_fps + 0.5 );
1135 // Determines if we have to decode all frames in a sequence
1136 // Temporary hack to improve intra frame only
1137 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
1138 strcmp( codec_context->codec->name, "dvvideo" ) &&
1139 strcmp( codec_context->codec->name, "huffyuv" ) &&
1140 strcmp( codec_context->codec->name, "mjpeg" ) &&
1141 strcmp( codec_context->codec->name, "rawvideo" );
1143 int last_position = self->last_position;
1145 // Turn on usage of new seek API and PTS for seeking
1146 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1147 if ( mlt_properties_get( properties, "new_seek" ) )
1148 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1150 // Seek if necessary
1151 if ( position != self->video_expected || last_position < 0 )
1153 if ( self->av_frame && position + 1 == self->video_expected )
1155 // We're paused - use last image
1158 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
1160 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1161 ignore = ( int )( ( position - self->video_expected ) / fps * source_fps );
1162 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1164 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || last_position < 0 ) )
1166 if ( use_new_seek && last_position == POSITION_INITIAL )
1168 // find first key frame
1172 while ( ret >= 0 && toscan-- > 0 )
1174 ret = av_read_frame( context, &pkt );
1175 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
1177 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) );
1178 self->first_pts = pkt.pts;
1181 av_free_packet( &pkt );
1184 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1187 // Calculate the timestamp for the requested frame
1191 timestamp = ( req_position - 0.1 / source_fps ) /
1192 ( av_q2d( stream->time_base ) * source_fps );
1193 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %"PRId64" ", req_position, timestamp );
1194 if ( self->first_pts > 0 )
1195 timestamp += self->first_pts;
1196 else if ( context->start_time != AV_NOPTS_VALUE )
1197 timestamp += context->start_time;
1201 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
1202 if ( context->start_time != AV_NOPTS_VALUE )
1203 timestamp += context->start_time;
1206 timestamp -= AV_TIME_BASE;
1207 if ( timestamp < 0 )
1209 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %d\n",
1210 timestamp, position, self->video_expected, last_position );
1212 // Seek to the timestamp
1215 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1216 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1218 else if ( req_position > 0 || last_position <= 0 )
1220 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
1224 // Re-open video stream when rewinding to beginning from somewhere else.
1225 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1226 // not reliably seeking to the first frame across formats.
1227 reopen_video( self, producer, properties );
1228 context = self->video_format;
1229 stream = context->streams[ self->video_index ];
1230 codec_context = stream->codec;
1233 // Remove the cached info relating to the previous position
1234 self->current_position = POSITION_INVALID;
1235 self->last_position = POSITION_INVALID;
1236 av_freep( &self->av_frame );
1240 // flush any pictures still in decode buffer
1241 avcodec_flush_buffers( codec_context );
1246 // Duplicate the last image if necessary
1247 if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture && self->seekable
1249 || self->current_position == req_position
1250 || ( !use_new_seek && self->current_position > req_position ) ) )
1253 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1255 // Workaround 1088 encodings missing cropping info.
1256 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1259 if ( self->vdpau && self->vdpau->buffer )
1262 picture.data[0] = self->vdpau->buffer;
1263 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1264 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1265 picture.linesize[0] = codec_context->width;
1266 picture.linesize[1] = codec_context->width / 2;
1267 picture.linesize[2] = codec_context->width / 2;
1268 convert_image( (AVFrame*) &picture, *buffer,
1269 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1273 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1274 format, *width, *height, self->colorspace );
1277 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1282 int int_position = 0;
1283 int decode_errors = 0;
1284 int got_picture = 0;
1286 av_init_packet( &pkt );
1288 // Construct an AVFrame for YUV422 conversion
1289 if ( !self->av_frame )
1290 self->av_frame = avcodec_alloc_frame( );
1292 while( ret >= 0 && !got_picture )
1295 ret = av_read_frame( context, &pkt );
1297 // We only deal with video from the selected video_index
1298 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1300 // Determine time code of the packet
1303 int64_t pts = pkt.pts;
1304 if ( self->first_pts > 0 )
1305 pts -= self->first_pts;
1306 else if ( context->start_time != AV_NOPTS_VALUE )
1307 pts -= context->start_time;
1308 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1309 if ( pkt.pts == AV_NOPTS_VALUE )
1311 self->invalid_pts_counter++;
1312 if ( self->invalid_pts_counter > 20 )
1314 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1315 mlt_properties_set_int( properties, "new_seek", 0 );
1316 int_position = req_position;
1322 self->invalid_pts_counter = 0;
1324 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1325 pkt.pts, req_position, self->current_position, int_position );
1329 if ( self->seekable && pkt.dts != AV_NOPTS_VALUE )
1331 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1332 if ( context->start_time != AV_NOPTS_VALUE )
1333 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1334 last_position = self->last_position;
1335 if ( int_position == last_position )
1336 int_position = last_position + 1;
1340 int_position = req_position;
1342 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %"PRId64" req_pos %d cur_pos %d pkt_pos %d\n",
1343 pkt.dts, req_position, self->current_position, int_position );
1344 // Make a dumb assumption on streams that contain wild timestamps
1345 if ( abs( req_position - int_position ) > 999 )
1347 int_position = req_position;
1348 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1351 self->last_position = int_position;
1354 if ( must_decode || int_position >= req_position )
1357 if ( g_vdpau && self->vdpau )
1359 if ( g_vdpau->producer != self )
1361 vdpau_decoder_close();
1362 vdpau_decoder_init( self );
1365 self->vdpau->is_decoded = 0;
1368 codec_context->reordered_opaque = pkt.pts;
1369 if ( int_position >= req_position )
1370 codec_context->skip_loop_filter = AVDISCARD_NONE;
1371 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1372 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1374 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1376 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1379 if ( ++decode_errors <= 10 )
1392 // Determine time code of the packet
1393 int64_t pts = self->av_frame->reordered_opaque;
1394 if ( self->first_pts > 0 )
1395 pts -= self->first_pts;
1396 else if ( context->start_time != AV_NOPTS_VALUE )
1397 pts -= context->start_time;
1398 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1399 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, self->av_frame->key_frame );
1402 if ( int_position < req_position )
1407 else if ( int_position >= req_position )
1410 codec_context->skip_loop_filter = AVDISCARD_NONE;
1412 else if ( ignore -- )
1417 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1420 // Now handle the picture if we have one
1423 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1425 // Workaround 1088 encodings missing cropping info.
1426 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1431 if ( self->vdpau->is_decoded )
1433 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1435 uint32_t pitches[3];
1436 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1438 if ( !self->vdpau->buffer )
1439 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1440 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1441 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1442 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1443 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1444 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1445 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1447 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1448 if ( status == VDP_STATUS_OK )
1450 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1451 format, *width, *height, self->colorspace );
1455 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1456 image_size = self->vdpau->is_decoded = 0;
1461 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1462 image_size = got_picture = 0;
1467 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1468 format, *width, *height, self->colorspace );
1469 self->top_field_first |= self->av_frame->top_field_first;
1470 self->current_position = int_position;
1471 self->got_picture = 1;
1479 av_free_packet( &pkt );
1483 if ( self->got_picture && image_size > 0 && self->image_cache )
1485 // Copy buffer to image cache
1486 uint8_t *image = mlt_pool_alloc( image_size );
1487 memcpy( image, *buffer, image_size );
1488 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1490 // Try to duplicate last image if there was a decoding failure
1491 else if ( !image_size && self->av_frame && self->av_frame->linesize[0] )
1494 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1496 // Workaround 1088 encodings missing cropping info.
1497 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1500 if ( self->vdpau && self->vdpau->buffer )
1503 picture.data[0] = self->vdpau->buffer;
1504 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1505 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1506 picture.linesize[0] = codec_context->width;
1507 picture.linesize[1] = codec_context->width / 2;
1508 picture.linesize[2] = codec_context->width / 2;
1509 convert_image( (AVFrame*) &picture, *buffer,
1510 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1514 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1515 format, *width, *height, self->colorspace );
1516 self->got_picture = 1;
1519 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1522 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1523 self->video_expected = position + 1;
1527 pthread_mutex_unlock( &self->video_mutex );
1529 // Set the progressive flag
1530 if ( mlt_properties_get( properties, "force_progressive" ) )
1531 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1532 else if ( self->av_frame )
1533 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1535 // Set the field order property for this frame
1536 if ( mlt_properties_get( properties, "force_tff" ) )
1537 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1539 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1541 // Set immutable properties of the selected track's (or overridden) source attributes.
1542 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1543 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1544 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1545 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1547 return !self->got_picture;
1550 /** Process properties as AVOptions and apply to AV context obj
1553 static void apply_properties( void *obj, mlt_properties properties, int flags )
1556 int count = mlt_properties_count( properties );
1557 for ( i = 0; i < count; i++ )
1559 const char *opt_name = mlt_properties_get_name( properties, i );
1560 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1561 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1564 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1565 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1566 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1567 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1569 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1575 /** Initialize the video codec context.
1578 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1580 // Initialise the codec if necessary
1581 if ( !self->video_codec )
1583 // Get the video stream
1584 AVStream *stream = self->video_format->streams[ index ];
1586 // Get codec context
1587 AVCodecContext *codec_context = stream->codec;
1590 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1592 if ( codec_context->codec_id == CODEC_ID_H264 )
1594 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1596 if ( vdpau_init( self ) )
1598 self->video_codec = codec_context;
1599 if ( !vdpau_decoder_init( self ) )
1600 vdpau_decoder_close();
1604 codec = avcodec_find_decoder( codec_context->codec_id );
1608 // Initialise multi-threading
1609 int thread_count = mlt_properties_get_int( properties, "threads" );
1610 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1611 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1612 if ( thread_count > 1 )
1613 codec_context->thread_count = thread_count;
1615 // If we don't have a codec and we can't initialise it, we can't do much more...
1617 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1619 // Now store the codec with its destructor
1620 self->video_codec = codec_context;
1624 // Remember that we can't use this later
1625 self->video_index = -1;
1631 // Process properties as AVOptions
1632 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1633 #if LIBAVCODEC_VERSION_MAJOR > 52
1634 if ( codec->priv_class && codec_context->priv_data )
1635 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1638 // Reset some image properties
1639 mlt_properties_set_int( properties, "width", self->video_codec->width );
1640 mlt_properties_set_int( properties, "height", self->video_codec->height );
1641 // For DV, we'll just use the saved aspect ratio
1642 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1643 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1645 // Determine the fps first from the codec
1646 double source_fps = (double) self->video_codec->time_base.den /
1647 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1649 if ( mlt_properties_get( properties, "force_fps" ) )
1651 source_fps = mlt_properties_get_double( properties, "force_fps" );
1652 stream->time_base = av_d2q( source_fps, 1024 );
1653 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1654 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1658 // If the muxer reports a frame rate different than the codec
1659 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1660 double muxer_fps = av_q2d( stream->avg_frame_rate );
1661 if ( isnan( muxer_fps ) || muxer_fps == 0 )
1662 muxer_fps = av_q2d( stream->r_frame_rate );
1664 double muxer_fps = av_q2d( stream->r_frame_rate );
1666 // Choose the lesser - the wrong tends to be off by some multiple of 10
1667 source_fps = FFMIN( source_fps, muxer_fps );
1668 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1670 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1671 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1673 else if ( muxer_fps > 0 )
1675 AVRational frame_rate = stream->r_frame_rate;
1676 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1677 // avg_frame_rate gives some approximate value that does not well match the media.
1678 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1679 // results in some very choppy output, but some value slightly different works
1681 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1682 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1683 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1685 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1686 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1690 source_fps = mlt_producer_get_fps( self->parent );
1691 AVRational frame_rate = av_d2q( source_fps, 255 );
1692 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1693 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1697 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1698 if ( source_fps > 0 )
1699 mlt_properties_set_double( properties, "source_fps", source_fps );
1701 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
1703 // Set the YUV colorspace from override or detect
1704 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1705 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1706 if ( ! self->colorspace )
1708 switch ( self->video_codec->colorspace )
1710 case AVCOL_SPC_SMPTE240M:
1711 self->colorspace = 240;
1713 case AVCOL_SPC_BT470BG:
1714 case AVCOL_SPC_SMPTE170M:
1715 self->colorspace = 601;
1717 case AVCOL_SPC_BT709:
1718 self->colorspace = 709;
1721 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1722 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1727 // Let apps get chosen colorspace
1728 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1730 return self->video_codec && self->video_index > -1;
1733 /** Set up video handling.
1736 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1739 mlt_producer producer = self->parent;
1741 // Get the properties
1742 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1744 // Fetch the video format context
1745 AVFormatContext *context = self->video_format;
1747 // Get the video_index
1748 int index = mlt_properties_get_int( properties, "video_index" );
1750 // Reopen the file if necessary
1751 if ( !context && index > -1 )
1753 mlt_events_block( properties, producer );
1754 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1755 mlt_properties_get( properties, "resource" ) );
1756 context = self->video_format;
1757 if ( self->dummy_context )
1759 av_close_input_file( self->dummy_context );
1760 self->dummy_context = NULL;
1762 mlt_events_unblock( properties, producer );
1763 if ( self->audio_format && !self->audio_streams )
1764 get_audio_streams_info( self );
1766 // Process properties as AVOptions
1769 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1770 #if LIBAVFORMAT_VERSION_MAJOR > 52
1771 if ( context->iformat && context->iformat->priv_class && context->priv_data )
1772 apply_properties( context->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
1777 // Exception handling for video_index
1778 if ( context && index >= (int) context->nb_streams )
1780 // Get the last video stream
1781 for ( index = context->nb_streams - 1;
1782 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1784 mlt_properties_set_int( properties, "video_index", index );
1786 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1788 // Invalidate the video stream
1790 mlt_properties_set_int( properties, "video_index", index );
1793 // Update the video properties if the index changed
1794 if ( index != self->video_index )
1796 // Reset the video properties if the index changed
1797 self->video_index = index;
1798 if ( self->video_codec )
1801 avcodec_close( self->video_codec );
1804 self->video_codec = NULL;
1807 // Get the frame properties
1808 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1811 if ( context && index > -1 && video_codec_init( self, index, properties ) )
1813 // Set the frame properties
1814 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1815 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1816 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1818 // Set the width and height
1819 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
1820 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
1821 // real_width and real_height are deprecated in favor of meta.media.width and .height
1822 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
1823 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
1824 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
1825 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
1826 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1827 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
1829 // Workaround 1088 encodings missing cropping info.
1830 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1832 mlt_properties_set_int( properties, "meta.media.height", 1080 );
1833 mlt_properties_set_int( frame_properties, "real_height", 1080 );
1836 // Add our image operation
1837 mlt_frame_push_service( frame, self );
1838 mlt_frame_push_get_image( frame, producer_get_image );
1842 // If something failed, use test card image
1843 mlt_properties_set_int( frame_properties, "test_image", 1 );
1847 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
1851 // Seek if necessary
1852 if ( position != self->audio_expected )
1854 if ( position + 1 == self->audio_expected )
1856 // We're paused - silence required
1859 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
1861 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1862 *ignore = position - self->audio_expected;
1864 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
1866 AVFormatContext *context = self->audio_format;
1867 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1868 if ( context->start_time != AV_NOPTS_VALUE )
1869 timestamp += context->start_time;
1870 if ( timestamp < 0 )
1873 // Set to the real timecode
1874 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1877 // Clear the usage in the audio buffer
1878 int i = MAX_AUDIO_STREAMS + 1;
1880 self->audio_used[i - 1] = 0;
1886 static int sample_bytes( AVCodecContext *context )
1888 #if LIBAVCODEC_VERSION_MAJOR > 52
1889 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
1891 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
1895 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
1897 // Fetch the audio_format
1898 AVFormatContext *context = self->audio_format;
1900 // Get the current stream index
1901 int index = pkt.stream_index;
1903 // Get codec context
1904 AVCodecContext *codec_context = self->audio_codec[ index ];
1906 // Obtain the resample context if it exists (not always needed)
1907 ReSampleContext *resample = self->audio_resample[ index ];
1909 // Obtain the audio buffers
1910 uint8_t *audio_buffer = self->audio_buffer[ index ];
1911 uint8_t *decode_buffer = self->decode_buffer[ index ];
1913 int audio_used = self->audio_used[ index ];
1914 uint8_t *ptr = pkt.data;
1918 while ( ptr && ret >= 0 && len > 0 )
1920 int sizeof_sample = resample? sizeof( int16_t ) : sample_bytes( codec_context );
1921 int data_size = self->audio_buffer_size[ index ];
1924 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1925 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
1926 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1927 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1929 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1933 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
1937 pkt.size = len -= ret;
1938 pkt.data = ptr += ret;
1940 // If decoded successfully
1941 if ( data_size > 0 )
1943 // Figure out how many samples will be needed after resampling
1944 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
1945 int samples_needed = self->resample_factor * convert_samples;
1947 // Resize audio buffer to prevent overflow
1948 if ( ( audio_used + samples_needed ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
1950 self->audio_buffer_size[ index ] = ( audio_used + samples_needed * 2 ) * channels * sizeof_sample;
1951 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
1955 // Copy to audio buffer while resampling
1956 uint8_t *source = decode_buffer;
1957 uint8_t *dest = &audio_buffer[ audio_used * channels * sizeof_sample ];
1958 audio_used += audio_resample( resample, (short*) dest, (short*) source, convert_samples );
1962 // Straight copy to audio buffer
1963 memcpy( &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ], decode_buffer, data_size );
1964 audio_used += convert_samples;
1968 while ( *ignore && audio_used > samples )
1971 audio_used -= samples;
1972 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) * sizeof_sample ],
1973 audio_used * sizeof_sample );
1978 // If we're behind, ignore this packet
1981 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
1982 int req_position = ( int )( timecode * fps + 0.5 );
1983 int int_position = ( int )( current_pts * fps + 0.5 );
1984 if ( context->start_time != AV_NOPTS_VALUE )
1985 int_position -= ( int )( fps * context->start_time / AV_TIME_BASE + 0.5 );
1987 if ( self->seekable && *ignore == 0 )
1989 if ( int_position < req_position )
1990 // We are behind, so skip some
1992 else if ( int_position > req_position + 2 )
1993 // We are ahead, so seek backwards some more
1994 seek_audio( self, req_position, timecode - 1.0, ignore );
1998 self->audio_used[ index ] = audio_used;
2003 /** Get the audio from a frame.
2005 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2008 producer_avformat self = mlt_frame_pop_audio( frame );
2010 pthread_mutex_lock( &self->audio_mutex );
2012 // Obtain the frame number of this frame
2013 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
2015 // Calculate the real time code
2016 double real_timecode = producer_time_of_frame( self->parent, position );
2018 // Get the producer fps
2019 double fps = mlt_producer_get_fps( self->parent );
2021 // Number of frames to ignore (for ffwd)
2024 // Flag for paused (silence)
2025 int paused = seek_audio( self, position, real_timecode, &ignore );
2027 // Fetch the audio_format
2028 AVFormatContext *context = self->audio_format;
2030 int sizeof_sample = sizeof( int16_t );
2032 // Determine the tracks to use
2033 int index = self->audio_index;
2034 int index_max = self->audio_index + 1;
2035 if ( self->audio_index == INT_MAX )
2038 index_max = context->nb_streams;
2039 *channels = self->total_channels;
2040 *samples = *samples * FFMAX( self->max_frequency, *frequency ) / *frequency;
2041 *frequency = FFMAX( self->max_frequency, *frequency );
2044 // Initialize the resamplers and buffers
2045 for ( ; index < index_max; index++ )
2047 // Get codec context
2048 AVCodecContext *codec_context = self->audio_codec[ index ];
2050 if ( codec_context && !self->audio_buffer[ index ] )
2052 // Check for resample and create if necessary
2053 if ( codec_context->channels <= 2 )
2055 // Determine by how much resampling will increase number of samples
2056 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
2057 resample_factor *= (double) *frequency / codec_context->sample_rate;
2058 if ( resample_factor > self->resample_factor )
2059 self->resample_factor = resample_factor;
2061 // Create the resampler
2062 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
2063 self->audio_resample[ index ] = av_audio_resample_init(
2064 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2065 codec_context->channels, *frequency, codec_context->sample_rate,
2066 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
2068 self->audio_resample[ index ] = audio_resample_init(
2069 self->audio_index == INT_MAX ? codec_context->channels : *channels,
2070 codec_context->channels, *frequency, codec_context->sample_rate );
2075 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2076 sizeof_sample = sample_bytes( codec_context );
2079 // Check for audio buffer and create if necessary
2080 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2081 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2083 // Check for decoder buffer and create if necessary
2084 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2088 // Get the audio if required
2095 av_init_packet( &pkt );
2097 // If not resampling, give consumer more than requested.
2098 // It requested number samples based on requested frame rate.
2099 // Do not clean this up with a samples *= ...!
2100 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2101 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2103 while ( ret >= 0 && !got_audio )
2105 // Check if the buffer already contains the samples required
2106 if ( self->audio_index != INT_MAX && self->audio_used[ self->audio_index ] >= *samples && ignore == 0 )
2113 ret = av_read_frame( context, &pkt );
2115 // We only deal with audio from the selected audio index
2116 index = pkt.stream_index;
2117 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2118 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2120 int channels2 = ( self->audio_index == INT_MAX || !self->audio_resample[index] ) ?
2121 self->audio_codec[index]->channels : *channels;
2122 ret = decode_audio( self, &ignore, pkt, channels2, *samples, real_timecode, fps );
2124 av_free_packet( &pkt );
2126 if ( self->audio_index == INT_MAX && ret >= 0 )
2128 // Determine if there is enough audio for all streams
2130 for ( index = 0; index < context->nb_streams; index++ )
2132 if ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples )
2138 // Set some additional return values
2139 *format = mlt_audio_s16;
2140 if ( self->audio_index != INT_MAX && !self->audio_resample[ self->audio_index ] )
2142 index = self->audio_index;
2143 *channels = self->audio_codec[ index ]->channels;
2144 *frequency = self->audio_codec[ index ]->sample_rate;
2145 *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2146 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2148 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2150 else if ( self->audio_index == INT_MAX )
2152 // This only works if all audio tracks have the same sample format.
2153 for ( index = 0; index < index_max; index++ )
2154 if ( self->audio_codec[ index ] && !self->audio_resample[ index ] )
2156 *format = self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_S32 ? mlt_audio_s32le
2157 : self->audio_codec[ index ]->sample_fmt == SAMPLE_FMT_FLT ? mlt_audio_f32le
2159 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2164 // Allocate and set the frame's audio buffer
2165 int size = mlt_audio_format_size( *format, *samples, *channels );
2166 *buffer = mlt_pool_alloc( size );
2167 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2169 // Interleave tracks if audio_index=all
2170 if ( self->audio_index == INT_MAX )
2172 uint8_t *dest = *buffer;
2174 for ( i = 0; i < *samples; i++ )
2176 for ( index = 0; index < index_max; index++ )
2177 if ( self->audio_codec[ index ] )
2179 int current_channels = self->audio_codec[ index ]->channels;
2180 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2181 memcpy( dest, src, current_channels * sizeof_sample );
2182 dest += current_channels * sizeof_sample;
2185 for ( index = 0; index < index_max; index++ )
2186 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2188 int current_channels = self->audio_codec[ index ]->channels;
2189 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2190 self->audio_used[index] -= *samples;
2191 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2194 // Copy a single track to the output buffer
2197 index = self->audio_index;
2199 // Now handle the audio if we have enough
2200 if ( self->audio_used[ index ] > 0 )
2202 uint8_t *src = self->audio_buffer[ index ];
2203 // copy samples from audio_buffer
2204 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2205 memcpy( *buffer, src, size * *channels * sizeof_sample );
2206 // supply the remaining requested samples as silence
2207 if ( *samples > self->audio_used[ index ] )
2208 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2209 // reposition the samples within audio_buffer
2210 self->audio_used[ index ] -= size;
2211 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2215 // Otherwise fill with silence
2216 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2222 // Get silence and don't touch the context
2223 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2226 // Regardless of speed (other than paused), we expect to get the next frame
2228 self->audio_expected = position + 1;
2230 pthread_mutex_unlock( &self->audio_mutex );
2235 /** Initialize the audio codec context.
2238 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2240 // Initialise the codec if necessary
2241 if ( !self->audio_codec[ index ] )
2243 // Get codec context
2244 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2247 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2249 // If we don't have a codec and we can't initialise it, we can't do much more...
2251 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2253 // Now store the codec with its destructor
2254 if ( self->audio_codec[ index ] )
2255 avcodec_close( self->audio_codec[ index ] );
2256 self->audio_codec[ index ] = codec_context;
2260 // Remember that we can't use self later
2261 self->audio_index = -1;
2265 // Process properties as AVOptions
2266 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2267 #if LIBAVCODEC_VERSION_MAJOR > 52
2268 if ( codec && codec->priv_class && codec_context->priv_data )
2269 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2272 return self->audio_codec[ index ] && self->audio_index > -1;
2275 /** Set up audio handling.
2278 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2281 mlt_producer producer = self->parent;
2283 // Get the properties
2284 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2286 // Fetch the audio format context
2287 AVFormatContext *context = self->audio_format;
2289 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2291 // Get the audio_index
2292 int index = mlt_properties_get_int( properties, "audio_index" );
2294 // Handle all audio tracks
2295 if ( self->audio_index > -1 &&
2296 mlt_properties_get( properties, "audio_index" ) &&
2297 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2300 // Reopen the file if necessary
2301 if ( !context && self->audio_index > -1 && index > -1 )
2303 mlt_events_block( properties, producer );
2304 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2305 mlt_properties_get( properties, "resource" ) );
2306 context = self->audio_format;
2307 if ( self->dummy_context )
2309 av_close_input_file( self->dummy_context );
2310 self->dummy_context = NULL;
2312 mlt_events_unblock( properties, producer );
2313 if ( self->audio_format )
2314 get_audio_streams_info( self );
2317 // Exception handling for audio_index
2318 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2320 for ( index = context->nb_streams - 1;
2321 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2323 mlt_properties_set_int( properties, "audio_index", index );
2325 if ( context && index > -1 && index < INT_MAX &&
2326 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2328 index = self->audio_index;
2329 mlt_properties_set_int( properties, "audio_index", index );
2332 // Update the audio properties if the index changed
2333 if ( context && index > -1 && index != self->audio_index )
2335 if ( self->audio_codec[ self->audio_index ] )
2338 avcodec_close( self->audio_codec[ self->audio_index ] );
2341 self->audio_codec[ self->audio_index ] = NULL;
2343 if ( self->audio_index != -1 )
2344 self->audio_index = index;
2349 if ( context && index == INT_MAX )
2351 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2352 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2353 for ( index = 0; index < context->nb_streams; index++ )
2355 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2356 audio_codec_init( self, index, properties );
2359 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2361 // Set the frame properties
2362 if ( index < INT_MAX )
2364 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2365 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2368 if ( context && index > -1 )
2370 // Add our audio operation
2371 mlt_frame_push_audio( frame, self );
2372 mlt_frame_push_audio( frame, producer_get_audio );
2376 /** Our get frame implementation.
2379 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2381 // Access the private data
2382 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2383 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2384 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2389 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2390 producer->child = self;
2391 self->parent = producer;
2392 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2393 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2396 // Create an empty frame
2397 *frame = mlt_frame_init( service);
2401 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2405 mlt_cache_item_close( cache_item );
2409 // Update timecode on the frame we're creating
2410 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2412 // Set the position of this producer
2413 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
2416 producer_set_up_video( self, *frame );
2419 producer_set_up_audio( self, *frame );
2421 // Calculate the next timecode
2422 mlt_producer_prepare_next( producer );
2427 static void producer_avformat_close( producer_avformat self )
2429 mlt_log_debug( NULL, "producer_avformat_close\n" );
2431 av_free( self->av_frame );
2434 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2436 if ( self->audio_resample[i] )
2437 audio_resample_close( self->audio_resample[i] );
2438 mlt_pool_release( self->audio_buffer[i] );
2439 av_free( self->decode_buffer[i] );
2440 if ( self->audio_codec[i] )
2441 avcodec_close( self->audio_codec[i] );
2443 if ( self->video_codec )
2444 avcodec_close( self->video_codec );
2445 if ( self->dummy_context )
2446 av_close_input_file( self->dummy_context );
2447 if ( self->audio_format )
2448 av_close_input_file( self->audio_format );
2449 if ( self->video_format )
2450 av_close_input_file( self->video_format );
2453 vdpau_producer_close( self );
2455 if ( self->image_cache )
2456 mlt_cache_close( self->image_cache );
2457 pthread_mutex_destroy( &self->audio_mutex );
2458 pthread_mutex_destroy( &self->video_mutex );
2462 static void producer_close( mlt_producer parent )
2465 parent->close = NULL;
2466 mlt_producer_close( parent );