2 * producer_avformat.c -- avformat producer
3 * Copyright (C) 2003-2012 Ushodaya Enterprises Limited
4 * Author: Charles Yates <charles.yates@pandora.be>
5 * Author: Dan Dennedy <dan@dennedy.org>
6 * Much code borrowed from ffmpeg.c: Copyright (c) 2000-2003 Fabrice Bellard
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include <framework/mlt_producer.h>
25 #include <framework/mlt_frame.h>
26 #include <framework/mlt_profile.h>
27 #include <framework/mlt_log.h>
28 #include <framework/mlt_deque.h>
29 #include <framework/mlt_factory.h>
30 #include <framework/mlt_cache.h>
32 // ffmpeg Header files
33 #include <libavformat/avformat.h>
34 #include <libswscale/swscale.h>
35 #include <libavutil/samplefmt.h>
36 #include <libavutil/pixdesc.h>
39 # include <libavcodec/vdpau.h>
41 #if (LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0))
42 # include <libavutil/dict.h>
45 // System header files
51 #if LIBAVCODEC_VERSION_MAJOR >= 53
52 #include <libavutil/opt.h>
53 #define CODEC_TYPE_VIDEO AVMEDIA_TYPE_VIDEO
54 #define CODEC_TYPE_AUDIO AVMEDIA_TYPE_AUDIO
55 #define PKT_FLAG_KEY AV_PKT_FLAG_KEY
57 #include <libavcodec/opt.h>
60 #if LIBAVCODEC_VERSION_MAJOR < 55
61 #define AV_CODEC_ID_DVVIDEO CODEC_ID_DVVIDEO
62 #define AV_CODEC_ID_H264 CODEC_ID_H264
65 #define POSITION_INITIAL (-2)
66 #define POSITION_INVALID (-1)
68 #define MAX_AUDIO_STREAMS (32)
69 #define MAX_VDPAU_SURFACES (10)
70 #define MAX_AUDIO_FRAME_SIZE (192000) // 1 second of 48khz 32bit audio
72 struct producer_avformat_s
75 AVFormatContext *dummy_context;
76 AVFormatContext *audio_format;
77 AVFormatContext *video_format;
78 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
79 AVCodecContext *video_codec;
83 mlt_position audio_expected;
84 mlt_position video_expected;
88 int64_t last_position;
90 int64_t current_position;
91 mlt_position nonseek_position;
93 uint8_t *audio_buffer[ MAX_AUDIO_STREAMS ];
94 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
95 uint8_t *decode_buffer[ MAX_AUDIO_STREAMS ];
96 int audio_used[ MAX_AUDIO_STREAMS ];
102 unsigned int invalid_pts_counter;
103 unsigned int invalid_dts_counter;
104 mlt_cache image_cache;
107 pthread_mutex_t video_mutex;
108 pthread_mutex_t audio_mutex;
111 pthread_mutex_t packets_mutex;
112 pthread_mutex_t open_mutex;
114 AVRational video_time_base;
119 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
133 typedef struct producer_avformat_s *producer_avformat;
135 // Forward references.
136 static int list_components( char* file );
137 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock );
138 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
139 static void producer_avformat_close( producer_avformat );
140 static void producer_close( mlt_producer parent );
141 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
142 static void producer_set_up_audio( producer_avformat self, mlt_frame frame );
143 static void apply_properties( void *obj, mlt_properties properties, int flags );
144 static int video_codec_init( producer_avformat self, int index, mlt_properties properties );
145 static void get_audio_streams_info( producer_avformat self );
146 static mlt_audio_format pick_audio_format( int sample_fmt );
152 /** Constructor for libavformat.
155 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
157 if ( list_components( file ) )
160 mlt_producer producer = NULL;
162 // Check that we have a non-NULL argument
165 // Construct the producer
166 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
167 producer = calloc( 1, sizeof( struct mlt_producer_s ) );
170 if ( mlt_producer_init( producer, self ) == 0 )
172 self->parent = producer;
174 // Get the properties
175 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
177 // Set the resource property (required for all producers)
178 mlt_properties_set( properties, "resource", file );
180 // Register transport implementation with the producer
181 producer->close = (mlt_destructor) producer_close;
183 // Register our get_frame implementation
184 producer->get_frame = producer_get_frame;
186 if ( strcmp( service, "avformat-novalidate" ) )
189 if ( producer_open( self, profile, file, 1 ) != 0 )
192 mlt_producer_close( producer );
194 producer_avformat_close( self );
196 else if ( self->seekable )
198 // Close the file to release resources for large playlists - reopen later as needed
199 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
200 if ( self->audio_format )
201 avformat_close_input( &self->audio_format );
202 if ( self->video_format )
203 avformat_close_input( &self->video_format );
205 if ( self->audio_format )
206 av_close_input_file( self->audio_format );
207 if ( self->video_format )
208 av_close_input_file( self->video_format );
210 self->audio_format = NULL;
211 self->video_format = NULL;
216 // Default the user-selectable indices from the auto-detected indices
217 mlt_properties_set_int( properties, "audio_index", self->audio_index );
218 mlt_properties_set_int( properties, "video_index", self->video_index );
220 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
222 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
229 int list_components( char* file )
233 // Report information about available demuxers and codecs as YAML Tiny
234 if ( file && strstr( file, "f-list" ) )
236 fprintf( stderr, "---\nformats:\n" );
237 AVInputFormat *format = NULL;
238 while ( ( format = av_iformat_next( format ) ) )
239 fprintf( stderr, " - %s\n", format->name );
240 fprintf( stderr, "...\n" );
243 if ( file && strstr( file, "acodec-list" ) )
245 fprintf( stderr, "---\naudio_codecs:\n" );
246 AVCodec *codec = NULL;
247 while ( ( codec = av_codec_next( codec ) ) )
248 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
249 fprintf( stderr, " - %s\n", codec->name );
250 fprintf( stderr, "...\n" );
253 if ( file && strstr( file, "vcodec-list" ) )
255 fprintf( stderr, "---\nvideo_codecs:\n" );
256 AVCodec *codec = NULL;
257 while ( ( codec = av_codec_next( codec ) ) )
258 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
259 fprintf( stderr, " - %s\n", codec->name );
260 fprintf( stderr, "...\n" );
267 static int first_video_index( producer_avformat self )
269 AVFormatContext *context = self->video_format? self->video_format : self->audio_format;
270 int i = -1; // not found
273 for ( i = 0; i < context->nb_streams; i++ ) {
274 if ( context->streams[i]->codec &&
275 context->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
278 if ( i == context->nb_streams )
284 /** Find the default streams.
287 static mlt_properties find_default_streams( producer_avformat self )
291 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
292 AVDictionaryEntry *tag = NULL;
294 AVMetadataTag *tag = NULL;
296 AVFormatContext *context = self->video_format;
297 mlt_properties meta_media = MLT_PRODUCER_PROPERTIES( self->parent );
299 // Default to the first audio and video streams found
300 self->audio_index = -1;
301 self->video_index = -1;
303 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
305 // Allow for multiple audio and video streams in the file and select first of each (if available)
306 for( i = 0; i < context->nb_streams; i++ )
308 // Get the codec context
309 AVStream *stream = context->streams[ i ];
310 if ( ! stream ) continue;
311 AVCodecContext *codec_context = stream->codec;
312 if ( ! codec_context ) continue;
313 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
314 if ( ! codec ) continue;
316 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
318 // Determine the type and obtain the first index of each type
319 switch( codec_context->codec_type )
321 case CODEC_TYPE_VIDEO:
322 // Use first video stream
323 if ( self->video_index < 0 )
324 self->video_index = i;
325 mlt_properties_set( meta_media, key, "video" );
326 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
327 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
328 #if LIBAVFORMAT_VERSION_MAJOR < 55
329 if ( isnan( ffmpeg_fps ) || ffmpeg_fps == 0 )
330 ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
332 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
334 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
335 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
336 snprintf( key, sizeof(key), "meta.media.%d.codec.width", i );
337 mlt_properties_set_int( meta_media, key, codec_context->width );
338 snprintf( key, sizeof(key), "meta.media.%d.codec.height", i );
339 mlt_properties_set_int( meta_media, key, codec_context->height );
340 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
341 AVRational frame_rate = { codec_context->time_base.den, codec_context->time_base.num * codec_context->ticks_per_frame };
342 mlt_properties_set_double( meta_media, key, av_q2d( frame_rate ) );
343 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
344 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(3<<8)+0)
345 mlt_properties_set( meta_media, key, av_get_pix_fmt_name( codec_context->pix_fmt ) );
347 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
349 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
350 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
351 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
352 switch ( codec_context->colorspace )
354 case AVCOL_SPC_SMPTE240M:
355 mlt_properties_set_int( meta_media, key, 240 );
357 case AVCOL_SPC_BT470BG:
358 case AVCOL_SPC_SMPTE170M:
359 mlt_properties_set_int( meta_media, key, 601 );
361 case AVCOL_SPC_BT709:
362 mlt_properties_set_int( meta_media, key, 709 );
365 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
366 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
370 case CODEC_TYPE_AUDIO:
371 if ( !codec_context->channels )
373 // Use first audio stream
374 if ( self->audio_index < 0 && pick_audio_format( codec_context->sample_fmt ) != mlt_audio_none )
375 self->audio_index = i;
377 mlt_properties_set( meta_media, key, "audio" );
378 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
379 mlt_properties_set( meta_media, key, av_get_sample_fmt_name( codec_context->sample_fmt ) );
380 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
381 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
382 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
383 mlt_properties_set_int( meta_media, key, codec_context->channels );
388 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
389 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
390 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
391 mlt_properties_set( meta_media, key, codec->name );
392 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
393 mlt_properties_set( meta_media, key, codec->long_name );
394 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
395 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
396 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
397 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
398 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
399 // mlt_properties_set_int( meta_media, key, codec_context->profile );
400 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
401 // mlt_properties_set_int( meta_media, key, codec_context->level );
404 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
405 while ( ( tag = av_dict_get( stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
407 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
410 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
412 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
413 mlt_properties_set( meta_media, key, tag->value );
417 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
418 while ( ( tag = av_dict_get( context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX ) ) )
420 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
423 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
425 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
426 mlt_properties_set( meta_media, key, tag->value );
433 static void get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context )
435 AVRational sar = stream->sample_aspect_ratio;
436 if ( sar.num <= 0 || sar.den <= 0 )
437 sar = codec_context->sample_aspect_ratio;
438 if ( sar.num <= 0 || sar.den <= 0 )
439 sar.num = sar.den = 1;
440 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", sar.num );
441 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", sar.den );
442 mlt_properties_set_double( properties, "aspect_ratio", av_q2d( sar ) );
445 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
446 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVDictionary **params )
448 static char* parse_url( mlt_profile profile, const char* URL, AVInputFormat **format, AVFormatParameters *params )
451 if ( !URL ) return NULL;
454 char *protocol = strdup( URL );
455 char *url = strchr( protocol, ':' );
457 // Only if there is not a protocol specification that avformat can handle
458 #if LIBAVFORMAT_VERSION_MAJOR >= 53
459 if ( url && avio_check( URL, 0 ) < 0 )
461 if ( url && !url_exist( URL ) )
464 // Truncate protocol string
466 mlt_log_debug( NULL, "%s: protocol=%s resource=%s\n", __FUNCTION__, protocol, url + 1 );
469 *format = av_find_input_format( protocol );
471 // Eat the format designator
476 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
477 // support for legacy width and height parameters
481 // These are required by video4linux2 (defaults)
482 params->width = profile->width;
483 params->height = profile->height;
484 if ( !strstr( URL, "&frame_rate" ) )
485 params->time_base = (AVRational){ profile->frame_rate_den, profile->frame_rate_num };
486 params->channels = 2;
487 params->sample_rate = 48000;
491 url = strchr( url, '?' );
495 char *name = strdup( ++url );
496 char *value = strchr( name, '=' );
498 // Also accept : as delimiter for backwards compatibility.
499 value = strchr( name, ':' );
504 char *t = strchr( value, '&' );
507 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
508 // translate old parameters to new av_dict names
509 if ( !strcmp( name, "frame_rate" ) )
510 av_dict_set( params, "framerate", value, 0 );
511 else if ( !strcmp( name, "pix_fmt" ) )
512 av_dict_set( params, "pixel_format", value, 0 );
513 else if ( !strcmp( name, "width" ) )
514 width = strdup( value );
515 else if ( !strcmp( name, "height" ) )
516 height = strdup( value );
518 // generic demux/device option support
519 av_dict_set( params, name, value, 0 );
521 if ( !strcmp( name, "frame_rate" ) )
522 params->time_base.den = atoi( value );
523 else if ( !strcmp( name, "frame_rate_base" ) )
524 params->time_base.num = atoi( value );
525 else if ( !strcmp( name, "sample_rate" ) )
526 params->sample_rate = atoi( value );
527 else if ( !strcmp( name, "channel" ) )
528 params->channel = atoi( value );
529 else if ( !strcmp( name, "channels" ) )
530 params->channels = atoi( value );
531 else if ( !strcmp( name, "pix_fmt" ) )
532 params->pix_fmt = av_get_pix_fmt( value );
533 else if ( !strcmp( name, "width" ) )
534 params->width = atoi( value );
535 else if ( !strcmp( name, "height" ) )
536 params->height = atoi( value );
537 else if ( !strcmp( name, "standard" ) )
538 params->standard = strdup( value );
542 url = strchr( url, '&' );
544 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
545 // continued support for legacy width and height parameters
546 if ( width && height )
548 char *s = malloc( strlen( width ) + strlen( height ) + 2 );
552 av_dict_set( params, "video_size", s, 0 );
555 if ( width ) free( width );
556 if ( height ) free ( height );
559 result = strdup( result );
563 result = strdup( URL );
569 static int get_basic_info( producer_avformat self, mlt_profile profile, const char *filename )
573 // Get the properties
574 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
576 AVFormatContext *format = self->video_format;
578 // We will treat everything with the producer fps.
579 // TODO: make this more flexible.
580 double fps = mlt_profile_fps( profile );
583 if ( !mlt_properties_get_int( properties, "_length_computed" ) )
585 // The _length_computed flag prevents overwriting explicity set length/out/eof properties
586 // when producer_open is called after initial call when restoring or reseting the producer.
587 if ( format->duration != AV_NOPTS_VALUE )
589 // This isn't going to be accurate for all formats
590 mlt_position frames = ( mlt_position )( ( ( double )format->duration / ( double )AV_TIME_BASE ) * fps );
591 mlt_properties_set_position( properties, "out", frames - 1 );
592 mlt_properties_set_position( properties, "length", frames );
593 mlt_properties_set_int( properties, "_length_computed", 1 );
597 // Set live sources to run forever
598 mlt_properties_set_position( properties, "length", INT_MAX );
599 mlt_properties_set_position( properties, "out", INT_MAX - 1 );
600 mlt_properties_set( properties, "eof", "loop" );
601 mlt_properties_set_int( properties, "_length_computed", 1 );
605 // Check if we're seekable
606 // avdevices are typically AVFMT_NOFILE and not seekable
607 self->seekable = !format->iformat || !( format->iformat->flags & AVFMT_NOFILE );
610 // protocols can indicate if they support seeking
611 #if LIBAVFORMAT_VERSION_MAJOR >= 53
612 self->seekable = format->pb->seekable;
614 URLContext *uc = url_fileno( format->pb );
616 self->seekable = !uc->is_streamed;
619 if ( self->seekable )
621 // Do a more rigourous test of seekable on a disposable context
622 self->seekable = av_seek_frame( format, -1, format->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
623 mlt_properties_set_int( properties, "seekable", self->seekable );
624 self->dummy_context = format;
625 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
626 self->video_format = NULL;
627 avformat_open_input( &self->video_format, filename, NULL, NULL );
628 avformat_find_stream_info( self->video_format, NULL );
630 av_open_input_file( &self->video_format, filename, NULL, 0, NULL );
631 av_find_stream_info( self->video_format );
633 format = self->video_format;
636 // Fetch the width, height and aspect ratio
637 if ( self->video_index != -1 )
639 AVCodecContext *codec_context = format->streams[ self->video_index ]->codec;
640 mlt_properties_set_int( properties, "width", codec_context->width );
641 mlt_properties_set_int( properties, "height", codec_context->height );
642 get_aspect_ratio( properties, format->streams[ self->video_index ], codec_context );
644 // Verify that we can convert this to YUV 4:2:2
645 // TODO: we can now also return RGB and RGBA and quite possibly more in the future.
646 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
647 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
649 sws_freeContext( context );
659 static int producer_open( producer_avformat self, mlt_profile profile, const char *URL, int take_lock )
661 // Return an error code (0 == no error)
663 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
668 if ( !self->is_mutex_init )
670 pthread_mutex_init( &self->audio_mutex, NULL );
671 pthread_mutex_init( &self->video_mutex, NULL );
672 pthread_mutex_init( &self->packets_mutex, NULL );
673 pthread_mutex_init( &self->open_mutex, NULL );
674 self->is_mutex_init = 1;
676 pthread_mutex_lock( &self->audio_mutex );
677 pthread_mutex_lock( &self->video_mutex );
679 mlt_events_block( properties, self->parent );
682 AVInputFormat *format = NULL;
683 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
684 AVDictionary *params = NULL;
686 AVFormatParameters params;
687 memset( ¶ms, 0, sizeof(params) );
689 char *filename = parse_url( profile, URL, &format, ¶ms );
691 // Now attempt to open the file or device with filename
692 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
693 error = avformat_open_input( &self->video_format, filename, format, ¶ms ) < 0;
695 // If the URL is a network stream URL, then we probably need to open with full URL
696 error = avformat_open_input( &self->video_format, URL, format, ¶ms ) < 0;
698 error = av_open_input_file( &self->video_format, filename, format, 0, ¶ms ) < 0;
700 // If the URL is a network stream URL, then we probably need to open with full URL
701 error = av_open_input_file( &self->video_format, URL, format, 0, ¶ms ) < 0;
704 // Set MLT properties onto video AVFormatContext
705 if ( !error && self->video_format )
707 apply_properties( self->video_format, properties, AV_OPT_FLAG_DECODING_PARAM );
708 if ( self->video_format->iformat && self->video_format->iformat->priv_class && self->video_format->priv_data )
709 apply_properties( self->video_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
712 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
713 av_dict_free( ¶ms );
715 // Cleanup AVFormatParameters
716 if ( params.standard )
717 free( (void*) params.standard );
720 // If successful, then try to get additional info
721 if ( !error && self->video_format )
723 // Get the stream info
724 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
725 error = avformat_find_stream_info( self->video_format, NULL ) < 0;
727 error = av_find_stream_info( self->video_format ) < 0;
730 // Continue if no error
731 if ( !error && self->video_format )
733 // Find default audio and video streams
734 find_default_streams( self );
735 error = get_basic_info( self, profile, filename );
737 // Initialize position info
738 self->first_pts = AV_NOPTS_VALUE;
739 self->last_position = POSITION_INITIAL;
741 if ( !self->audio_format )
743 // We're going to cheat here - for seekable A/V files, we will have separate contexts
744 // to support independent seeking of audio from video.
745 // TODO: Is this really necessary?
746 if ( self->audio_index != -1 && self->video_index != -1 )
748 if ( self->seekable )
750 // And open again for our audio context
751 #if LIBAVFORMAT_VERSION_INT > ((53<<16)+(6<<8)+0)
752 avformat_open_input( &self->audio_format, filename, NULL, NULL );
753 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
754 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
755 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
756 avformat_find_stream_info( self->audio_format, NULL );
758 av_open_input_file( &self->audio_format, filename, NULL, 0, NULL );
759 apply_properties( self->audio_format, properties, AV_OPT_FLAG_DECODING_PARAM );
760 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(110<<8)+0)
761 if ( self->audio_format->iformat && self->audio_format->iformat->priv_class && self->audio_format->priv_data )
762 apply_properties( self->audio_format->priv_data, properties, AV_OPT_FLAG_DECODING_PARAM );
764 av_find_stream_info( self->audio_format );
769 self->audio_format = self->video_format;
772 else if ( self->audio_index != -1 )
774 // We only have an audio context
775 self->audio_format = self->video_format;
776 self->video_format = NULL;
778 else if ( self->video_index == -1 )
780 // Something has gone wrong
783 if ( self->audio_format && !self->audio_streams )
784 get_audio_streams_info( self );
792 self->apackets = mlt_deque_init();
793 self->vpackets = mlt_deque_init();
796 if ( self->dummy_context )
798 pthread_mutex_lock( &self->open_mutex );
799 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
800 avformat_close_input( &self->dummy_context );
802 av_close_input_file( self->dummy_context );
804 self->dummy_context = NULL;
805 pthread_mutex_unlock( &self->open_mutex );
808 // Unlock the service
811 pthread_mutex_unlock( &self->audio_mutex );
812 pthread_mutex_unlock( &self->video_mutex );
814 mlt_events_unblock( properties, self->parent );
819 static void prepare_reopen( producer_avformat self )
821 mlt_service_lock( MLT_PRODUCER_SERVICE( self->parent ) );
822 pthread_mutex_lock( &self->audio_mutex );
823 pthread_mutex_lock( &self->open_mutex );
826 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
828 mlt_pool_release( self->audio_buffer[i] );
829 self->audio_buffer[i] = NULL;
830 av_free( self->decode_buffer[i] );
831 self->decode_buffer[i] = NULL;
832 if ( self->audio_codec[i] )
833 avcodec_close( self->audio_codec[i] );
834 self->audio_codec[i] = NULL;
836 if ( self->video_codec )
837 avcodec_close( self->video_codec );
838 self->video_codec = NULL;
840 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
841 if ( self->seekable && self->audio_format )
842 avformat_close_input( &self->audio_format );
843 if ( self->video_format )
844 avformat_close_input( &self->video_format );
846 if ( self->seekable && self->audio_format )
847 av_close_input_file( self->audio_format );
848 if ( self->video_format )
849 av_close_input_file( self->video_format );
851 self->audio_format = NULL;
852 self->video_format = NULL;
853 pthread_mutex_unlock( &self->open_mutex );
855 // Cleanup the packet queues
857 if ( self->apackets )
859 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
861 av_free_packet( pkt );
864 mlt_deque_close( self->apackets );
865 self->apackets = NULL;
867 if ( self->vpackets )
869 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
871 av_free_packet( pkt );
874 mlt_deque_close( self->vpackets );
875 self->vpackets = NULL;
877 pthread_mutex_unlock( &self->audio_mutex );
878 mlt_service_unlock( MLT_PRODUCER_SERVICE( self->parent ) );
881 static int64_t best_pts( producer_avformat self, int64_t pts, int64_t dts )
883 self->invalid_pts_counter += pts == AV_NOPTS_VALUE;
884 self->invalid_dts_counter += dts == AV_NOPTS_VALUE;
885 if ( ( self->invalid_pts_counter <= self->invalid_dts_counter
886 || dts == AV_NOPTS_VALUE ) && pts != AV_NOPTS_VALUE )
892 static void find_first_pts( producer_avformat self, int video_index )
895 AVFormatContext *context = self->video_format? self->video_format : self->audio_format;
900 while ( ret >= 0 && toscan-- > 0 )
902 ret = av_read_frame( context, &pkt );
903 if ( ret >= 0 && pkt.stream_index == video_index && ( pkt.flags & PKT_FLAG_KEY ) )
905 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
906 "first_pts %"PRId64" dts %"PRId64" pts_dts_delta %d\n",
907 pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
908 self->first_pts = best_pts( self, pkt.pts, pkt.dts );
909 if ( self->first_pts != AV_NOPTS_VALUE )
912 av_free_packet( &pkt );
914 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
917 static int seek_video( producer_avformat self, mlt_position position,
918 int64_t req_position, int preseek )
920 mlt_producer producer = self->parent;
923 if ( self->seekable && ( position != self->video_expected || self->last_position < 0 ) )
925 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
927 // Fetch the video format context
928 AVFormatContext *context = self->video_format;
930 // Get the video stream
931 AVStream *stream = context->streams[ self->video_index ];
934 AVCodecContext *codec_context = stream->codec;
936 // We may want to use the source fps if available
937 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
938 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
940 if ( self->last_position == POSITION_INITIAL )
941 find_first_pts( self, self->video_index );
943 if ( self->video_frame && position + 1 == self->video_expected )
945 // We're paused - use last image
948 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || self->last_position < 0 ) )
950 // Calculate the timestamp for the requested frame
951 int64_t timestamp = req_position / ( av_q2d( self->video_time_base ) * source_fps );
952 if ( req_position <= 0 )
954 else if ( self->first_pts != AV_NOPTS_VALUE )
955 timestamp += self->first_pts;
956 else if ( context->start_time != AV_NOPTS_VALUE )
957 timestamp += context->start_time;
958 if ( preseek && av_q2d( self->video_time_base ) != 0 )
959 timestamp -= 2 / av_q2d( self->video_time_base );
962 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %"PRId64" position %d expected %d last_pos %"PRId64"\n",
963 timestamp, position, self->video_expected, self->last_position );
965 // Seek to the timestamp
966 codec_context->skip_loop_filter = AVDISCARD_NONREF;
967 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
969 // flush any pictures still in decode buffer
970 avcodec_flush_buffers( codec_context );
972 // Remove the cached info relating to the previous position
973 self->current_position = POSITION_INVALID;
974 self->last_position = POSITION_INVALID;
975 av_freep( &self->video_frame );
981 /** Convert a frame position to a time code.
984 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
986 return ( double )position / mlt_producer_get_fps( producer );
989 // Collect information about all audio streams
991 static void get_audio_streams_info( producer_avformat self )
993 // Fetch the audio format context
994 AVFormatContext *context = self->audio_format;
998 i < context->nb_streams;
1001 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
1003 AVCodecContext *codec_context = context->streams[i]->codec;
1004 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1006 // If we don't have a codec and we can't initialise it, we can't do much more...
1007 pthread_mutex_lock( &self->open_mutex );
1008 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1009 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1011 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1014 self->audio_streams++;
1015 self->audio_max_stream = i;
1016 self->total_channels += codec_context->channels;
1017 if ( codec_context->channels > self->max_channel )
1018 self->max_channel = codec_context->channels;
1019 if ( codec_context->sample_rate > self->max_frequency )
1020 self->max_frequency = codec_context->sample_rate;
1021 avcodec_close( codec_context );
1023 pthread_mutex_unlock( &self->open_mutex );
1026 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
1027 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
1030 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
1033 const int *new_coefficients;
1035 int brightness, contrast, saturation;
1037 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
1038 &brightness, &contrast, &saturation ) != -1 )
1040 // Don't change these from defaults unless explicitly told to.
1041 if ( use_full_range >= 0 )
1042 full_range = use_full_range;
1043 switch ( colorspace )
1049 new_coefficients = sws_getCoefficients( SWS_CS_ITU601 );
1052 new_coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
1055 new_coefficients = sws_getCoefficients( SWS_CS_ITU709 );
1058 new_coefficients = coefficients;
1061 sws_setColorspaceDetails( context, new_coefficients, full_range, new_coefficients, full_range,
1062 brightness, contrast, saturation );
1066 static mlt_image_format pick_pix_format( enum PixelFormat pix_fmt )
1074 return mlt_image_rgb24a;
1075 case PIX_FMT_YUV420P:
1076 case PIX_FMT_YUVJ420P:
1077 case PIX_FMT_YUVA420P:
1078 return mlt_image_yuv420p;
1082 case PIX_FMT_MONOWHITE:
1083 case PIX_FMT_MONOBLACK:
1086 return mlt_image_rgb24;
1088 return mlt_image_yuv422;
1092 static mlt_audio_format pick_audio_format( int sample_fmt )
1094 switch ( sample_fmt )
1097 case AV_SAMPLE_FMT_U8:
1098 return mlt_audio_u8;
1099 case AV_SAMPLE_FMT_S16:
1100 return mlt_audio_s16;
1101 case AV_SAMPLE_FMT_S32:
1102 return mlt_audio_s32le;
1103 case AV_SAMPLE_FMT_FLT:
1104 return mlt_audio_f32le;
1105 // planar - this producer converts planar to interleaved
1106 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
1107 case AV_SAMPLE_FMT_U8P:
1108 return mlt_audio_u8;
1109 case AV_SAMPLE_FMT_S16P:
1110 return mlt_audio_s16;
1111 case AV_SAMPLE_FMT_S32P:
1112 return mlt_audio_s32le;
1113 case AV_SAMPLE_FMT_FLTP:
1114 return mlt_audio_f32le;
1117 return mlt_audio_none;
1121 static void convert_image( producer_avformat self, AVFrame *frame, uint8_t *buffer, int pix_fmt,
1122 mlt_image_format *format, int width, int height, uint8_t **alpha )
1124 int flags = SWS_BICUBIC | SWS_ACCURATE_RND;
1127 flags |= SWS_CPU_CAPS_MMX;
1130 flags |= SWS_CPU_CAPS_MMX2;
1133 // extract alpha from planar formats
1134 if ( ( pix_fmt == PIX_FMT_YUVA420P
1135 #if defined(FFUDIV) && LIBAVUTIL_VERSION_INT >= ((51<<16)+(35<<8)+101)
1136 || pix_fmt == PIX_FMT_YUVA444P
1139 *format != mlt_image_rgb24a && *format != mlt_image_opengl &&
1140 frame->data[3] && frame->linesize[3] )
1145 dst = *alpha = mlt_pool_alloc( width * height );
1146 src = frame->data[3];
1148 for ( i = 0; i < height; dst += width, src += frame->linesize[3], i++ )
1149 memcpy( dst, src, FFMIN( width, frame->linesize[3] ) );
1152 if ( *format == mlt_image_yuv420p )
1154 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1155 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
1157 output.data[0] = buffer;
1158 output.data[1] = buffer + width * height;
1159 output.data[2] = buffer + ( 5 * width * height ) / 4;
1160 output.linesize[0] = width;
1161 output.linesize[1] = width >> 1;
1162 output.linesize[2] = width >> 1;
1163 set_luma_transfer( context, self->colorspace, -1 );
1164 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1165 output.data, output.linesize);
1166 sws_freeContext( context );
1168 else if ( *format == mlt_image_rgb24 )
1170 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1171 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1173 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
1174 set_luma_transfer( context, self->colorspace, self->full_luma );
1175 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1176 output.data, output.linesize);
1177 sws_freeContext( context );
1179 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1181 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1182 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
1184 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
1185 set_luma_transfer( context, self->colorspace, self->full_luma );
1186 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1187 output.data, output.linesize);
1188 sws_freeContext( context );
1192 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
1193 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
1195 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
1196 set_luma_transfer( context, self->colorspace, -1 );
1197 sws_scale( context, (const uint8_t* const*) frame->data, frame->linesize, 0, height,
1198 output.data, output.linesize);
1199 sws_freeContext( context );
1203 /** Allocate the image buffer and set it on the frame.
1206 static int allocate_buffer( mlt_frame frame, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
1210 if ( codec_context->width == 0 || codec_context->height == 0 )
1213 if ( *format == mlt_image_glsl )
1214 *format = pick_pix_format( codec_context->pix_fmt );
1216 *width = codec_context->width;
1217 *height = codec_context->height;
1218 size = mlt_image_format_size( *format, *width, *height, NULL );
1219 *buffer = mlt_pool_alloc( size );
1221 mlt_frame_set_image( frame, *buffer, size, mlt_pool_release );
1228 /** Get an image from a frame.
1231 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
1234 producer_avformat self = mlt_frame_pop_service( frame );
1235 mlt_producer producer = self->parent;
1237 // Get the properties from the frame
1238 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1240 // Obtain the frame number of this frame
1241 mlt_position position = mlt_frame_original_position( frame );
1243 // Get the producer properties
1244 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1246 pthread_mutex_lock( &self->video_mutex );
1248 uint8_t *alpha = NULL;
1249 int got_picture = 0;
1252 // Fetch the video format context
1253 AVFormatContext *context = self->video_format;
1255 goto exit_get_image;
1257 // Get the video stream
1258 AVStream *stream = context->streams[ self->video_index ];
1260 // Get codec context
1261 AVCodecContext *codec_context = stream->codec;
1263 // Get the image cache
1264 if ( ! self->image_cache )
1266 // if cache size supplied by environment variable
1267 int cache_supplied = getenv( "MLT_AVFORMAT_CACHE" ) != NULL;
1268 int cache_size = cache_supplied? atoi( getenv( "MLT_AVFORMAT_CACHE" ) ) : 0;
1270 // cache size supplied via property
1271 if ( mlt_properties_get( properties, "cache" ) )
1274 cache_size = mlt_properties_get_int( properties, "cache" );
1276 if ( mlt_properties_get_int( properties, "noimagecache" ) )
1278 // create cache if not disabled
1279 if ( !cache_supplied || cache_size > 0 )
1280 self->image_cache = mlt_cache_init();
1281 // set cache size if supplied
1282 if ( self->image_cache && cache_supplied )
1283 mlt_cache_set_size( self->image_cache, cache_size );
1285 if ( self->image_cache )
1287 mlt_frame original = mlt_cache_get_frame( self->image_cache, position );
1290 mlt_properties orig_props = MLT_FRAME_PROPERTIES( original );
1293 *buffer = mlt_properties_get_data( orig_props, "alpha", &size );
1295 mlt_frame_set_alpha( frame, *buffer, size, NULL );
1296 *buffer = mlt_properties_get_data( orig_props, "image", &size );
1297 mlt_frame_set_image( frame, *buffer, size, NULL );
1298 mlt_properties_set_data( frame_properties, "avformat.image_cache", original, 0, (mlt_destructor) mlt_frame_close, NULL );
1299 *format = mlt_properties_get_int( orig_props, "format" );
1301 // Set the resolution
1302 *width = codec_context->width;
1303 *height = codec_context->height;
1305 // Workaround 1088 encodings missing cropping info.
1306 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1310 goto exit_get_image;
1315 // We may want to use the source fps if available
1316 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1317 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1319 // This is the physical frame position in the source
1320 int64_t req_position = ( int64_t )( position / mlt_producer_get_fps( producer ) * source_fps + 0.5 );
1322 // Determines if we have to decode all frames in a sequence
1323 // Temporary hack to improve intra frame only
1324 int must_decode = !( codec_context->codec && codec_context->codec->name ) || (
1325 strcmp( codec_context->codec->name, "dnxhd" ) &&
1326 strcmp( codec_context->codec->name, "dvvideo" ) &&
1327 strcmp( codec_context->codec->name, "huffyuv" ) &&
1328 strcmp( codec_context->codec->name, "mjpeg" ) &&
1329 strcmp( codec_context->codec->name, "rawvideo" ) );
1331 double delay = mlt_properties_get_double( properties, "video_delay" );
1333 // Seek if necessary
1334 const char *interp = mlt_properties_get( frame_properties, "rescale.interp" );
1335 int preseek = must_decode
1336 #if defined(FFUDIV) && LIBAVFORMAT_VERSION_INT >= ((53<<16)+(24<<8)+2)
1337 && ( interp && strcmp( interp, "nearest" ) )
1339 && codec_context->has_b_frames;
1340 int paused = seek_video( self, position, req_position, preseek );
1342 // Seek might have reopened the file
1343 context = self->video_format;
1344 stream = context->streams[ self->video_index ];
1345 codec_context = stream->codec;
1346 if ( *format == mlt_image_none ||
1347 codec_context->pix_fmt == PIX_FMT_ARGB ||
1348 codec_context->pix_fmt == PIX_FMT_RGBA ||
1349 codec_context->pix_fmt == PIX_FMT_ABGR ||
1350 codec_context->pix_fmt == PIX_FMT_BGRA )
1351 *format = pick_pix_format( codec_context->pix_fmt );
1353 // Duplicate the last image if necessary
1354 if ( self->video_frame && self->video_frame->linesize[0]
1355 && ( paused || self->current_position >= req_position ) )
1358 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1360 // Workaround 1088 encodings missing cropping info.
1361 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1364 if ( self->vdpau && self->vdpau->buffer )
1367 picture.data[0] = self->vdpau->buffer;
1368 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1369 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1370 picture.linesize[0] = codec_context->width;
1371 picture.linesize[1] = codec_context->width / 2;
1372 picture.linesize[2] = codec_context->width / 2;
1373 convert_image( self, (AVFrame*) &picture, *buffer,
1374 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1378 convert_image( self, self->video_frame, *buffer, codec_context->pix_fmt,
1379 format, *width, *height, &alpha );
1386 int64_t int_position = 0;
1387 int decode_errors = 0;
1389 // Construct an AVFrame for YUV422 conversion
1390 if ( !self->video_frame )
1391 self->video_frame = avcodec_alloc_frame( );
1393 while( ret >= 0 && !got_picture )
1396 if ( self->pkt.stream_index == self->video_index )
1397 av_free_packet( &self->pkt );
1398 av_init_packet( &self->pkt );
1399 pthread_mutex_lock( &self->packets_mutex );
1400 if ( mlt_deque_count( self->vpackets ) )
1402 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->vpackets );
1408 ret = av_read_frame( context, &self->pkt );
1409 if ( ret >= 0 && !self->seekable && self->pkt.stream_index == self->audio_index )
1411 if ( !av_dup_packet( &self->pkt ) )
1413 AVPacket *tmp = malloc( sizeof(AVPacket) );
1415 mlt_deque_push_back( self->apackets, tmp );
1420 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "av_read_frame returned error %d inside get_image\n", ret );
1421 if ( !self->seekable && mlt_properties_get_int( properties, "reconnect" ) )
1423 // Try to reconnect to live sources by closing context and codecs,
1424 // and letting next call to get_frame() reopen.
1425 prepare_reopen( self );
1426 pthread_mutex_unlock( &self->packets_mutex );
1427 goto exit_get_image;
1431 pthread_mutex_unlock( &self->packets_mutex );
1433 // We only deal with video from the selected video_index
1434 if ( ret >= 0 && self->pkt.stream_index == self->video_index && self->pkt.size > 0 )
1436 int64_t pts = best_pts( self, self->pkt.pts, self->pkt.dts );
1437 if ( pts != AV_NOPTS_VALUE )
1439 if ( !self->seekable && self->first_pts == AV_NOPTS_VALUE )
1440 self->first_pts = pts;
1441 if ( self->first_pts != AV_NOPTS_VALUE )
1442 pts -= self->first_pts;
1443 else if ( context->start_time != AV_NOPTS_VALUE )
1444 pts -= context->start_time;
1445 int_position = ( int64_t )( ( av_q2d( self->video_time_base ) * pts + delay ) * source_fps + 0.5 );
1446 if ( int_position == self->last_position )
1447 int_position = self->last_position + 1;
1449 mlt_log_debug( MLT_PRODUCER_SERVICE(producer),
1450 "V pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
1451 self->pkt.pts, self->pkt.dts, req_position, self->current_position, int_position );
1453 // Make a dumb assumption on streams that contain wild timestamps
1454 if ( abs( req_position - int_position ) > 999 )
1456 int_position = req_position;
1457 mlt_log_warning( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!\n" );
1459 self->last_position = int_position;
1462 if ( must_decode || int_position >= req_position )
1467 if ( self->vdpau->decoder == VDP_INVALID_HANDLE )
1469 vdpau_decoder_init( self );
1471 self->vdpau->is_decoded = 0;
1474 codec_context->reordered_opaque = int_position;
1475 if ( int_position >= req_position )
1476 codec_context->skip_loop_filter = AVDISCARD_NONE;
1477 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1478 ret = avcodec_decode_video2( codec_context, self->video_frame, &got_picture, &self->pkt );
1480 ret = avcodec_decode_video( codec_context, self->video_frame, &got_picture, self->pkt.data, self->pkt.size );
1482 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1485 if ( ++decode_errors <= 10 )
1488 mlt_log_warning( MLT_PRODUCER_SERVICE(producer), "video decoding error %d\n", ret );
1498 // Get position of reordered frame
1499 int_position = self->video_frame->reordered_opaque;
1500 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(106<<8)+0))
1501 pts = best_pts( self, self->video_frame->pkt_pts, self->video_frame->pkt_dts );
1502 if ( pts != AV_NOPTS_VALUE )
1504 if ( self->first_pts != AV_NOPTS_VALUE )
1505 pts -= self->first_pts;
1506 else if ( context->start_time != AV_NOPTS_VALUE )
1507 pts -= context->start_time;
1508 int_position = ( int64_t )( ( av_q2d( self->video_time_base ) * pts + delay ) * source_fps + 0.5 );
1512 if ( int_position < req_position )
1514 else if ( int_position >= req_position )
1515 codec_context->skip_loop_filter = AVDISCARD_NONE;
1517 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, self->pkt.flags & PKT_FLAG_KEY );
1520 // Now handle the picture if we have one
1523 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1525 // Workaround 1088 encodings missing cropping info.
1526 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1531 if ( self->vdpau->is_decoded )
1533 struct vdpau_render_state *render = (struct vdpau_render_state*) self->video_frame->data[0];
1535 uint32_t pitches[3];
1536 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1538 if ( !self->vdpau->buffer )
1539 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1540 self->video_frame->data[0] = planes[0] = self->vdpau->buffer;
1541 self->video_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1542 self->video_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1543 self->video_frame->linesize[0] = pitches[0] = codec_context->width;
1544 self->video_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1545 self->video_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1547 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1548 if ( status == VDP_STATUS_OK )
1550 convert_image( self, self->video_frame, *buffer, PIX_FMT_YUV420P,
1551 format, *width, *height, &alpha );
1555 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1556 image_size = self->vdpau->is_decoded = 0;
1561 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1562 image_size = got_picture = 0;
1567 convert_image( self, self->video_frame, *buffer, codec_context->pix_fmt,
1568 format, *width, *height, &alpha );
1569 self->top_field_first |= self->video_frame->top_field_first;
1570 self->current_position = int_position;
1578 // Free packet data if not video and not live audio packet
1579 if ( self->pkt.stream_index != self->video_index &&
1580 !( !self->seekable && self->pkt.stream_index == self->audio_index ) )
1581 av_free_packet( &self->pkt );
1587 mlt_frame_set_alpha( frame, alpha, (*width) * (*height), mlt_pool_release );
1589 if ( image_size > 0 && self->image_cache )
1591 mlt_properties_set_int( frame_properties, "format", *format );
1592 mlt_cache_put_frame( self->image_cache, frame );
1595 // Try to duplicate last image if there was a decoding failure
1596 // TODO: with multithread decoding a partial frame decoding resulting
1597 // in failure also resets av_frame making test below fail.
1598 if ( !image_size && self->video_frame && self->video_frame->linesize[0] )
1601 if ( ( image_size = allocate_buffer( frame, codec_context, buffer, format, width, height ) ) )
1603 // Workaround 1088 encodings missing cropping info.
1604 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1607 if ( self->vdpau && self->vdpau->buffer )
1610 picture.data[0] = self->vdpau->buffer;
1611 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1612 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1613 picture.linesize[0] = codec_context->width;
1614 picture.linesize[1] = codec_context->width / 2;
1615 picture.linesize[2] = codec_context->width / 2;
1616 convert_image( self, (AVFrame*) &picture, *buffer,
1617 PIX_FMT_YUV420P, format, *width, *height, &alpha );
1621 convert_image( self, self->video_frame, *buffer, codec_context->pix_fmt,
1622 format, *width, *height, &alpha );
1627 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1628 self->video_expected = position + 1;
1632 pthread_mutex_unlock( &self->video_mutex );
1634 // Set the progressive flag
1635 if ( mlt_properties_get( properties, "force_progressive" ) )
1636 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1637 else if ( self->video_frame )
1638 mlt_properties_set_int( frame_properties, "progressive", !self->video_frame->interlaced_frame );
1640 // Set the field order property for this frame
1641 if ( mlt_properties_get( properties, "force_tff" ) )
1642 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1644 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1646 // Set immutable properties of the selected track's (or overridden) source attributes.
1647 mlt_service_lock( MLT_PRODUCER_SERVICE( producer ) );
1648 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1649 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1650 mlt_service_unlock( MLT_PRODUCER_SERVICE( producer ) );
1652 // If we already have RGB, then the full range processing either happened already
1653 // or does not apply (RGB source).
1654 if ( *format == mlt_image_rgb24 || *format == mlt_image_rgb24a || *format == mlt_image_opengl )
1655 mlt_properties_set( frame_properties, "force_full_luma", NULL );
1657 return !got_picture;
1660 /** Process properties as AVOptions and apply to AV context obj
1663 static void apply_properties( void *obj, mlt_properties properties, int flags )
1666 int count = mlt_properties_count( properties );
1667 for ( i = 0; i < count; i++ )
1669 const char *opt_name = mlt_properties_get_name( properties, i );
1670 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(10<<8)+0)
1671 const AVOption *opt = av_opt_find( obj, opt_name, NULL, flags, flags );
1673 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1675 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1678 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(12<<8)+0)
1679 av_opt_set( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1680 #elif LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1681 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1682 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1683 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1685 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1691 /** Initialize the video codec context.
1694 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1696 // Initialise the codec if necessary
1697 if ( !self->video_codec )
1699 // Get the video stream
1700 AVStream *stream = self->video_format->streams[ index ];
1702 // Get codec context
1703 AVCodecContext *codec_context = stream->codec;
1706 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1708 if ( codec_context->codec_id == AV_CODEC_ID_H264 )
1710 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1712 if ( vdpau_init( self ) )
1714 self->video_codec = codec_context;
1715 if ( !vdpau_decoder_init( self ) )
1720 codec = avcodec_find_decoder( codec_context->codec_id );
1724 // Initialise multi-threading
1725 int thread_count = mlt_properties_get_int( properties, "threads" );
1726 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1727 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1728 if ( thread_count > 1 )
1729 codec_context->thread_count = thread_count;
1731 // If we don't have a codec and we can't initialise it, we can't do much more...
1732 pthread_mutex_lock( &self->open_mutex );
1733 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
1734 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
1736 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1739 // Now store the codec with its destructor
1740 self->video_codec = codec_context;
1744 // Remember that we can't use this later
1745 self->video_index = -1;
1746 pthread_mutex_unlock( &self->open_mutex );
1749 pthread_mutex_unlock( &self->open_mutex );
1751 // Process properties as AVOptions
1752 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1753 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(122<<8)+0)
1754 if ( codec->priv_class && codec_context->priv_data )
1755 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1758 // Reset some image properties
1759 if ( self->video_codec )
1761 mlt_properties_set_int( properties, "width", self->video_codec->width );
1762 mlt_properties_set_int( properties, "height", self->video_codec->height );
1763 get_aspect_ratio( properties, stream, self->video_codec );
1766 // Start with the muxer frame rate.
1767 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1768 AVRational frame_rate = stream->avg_frame_rate;
1770 AVRational frame_rate = stream->r_frame_rate;
1772 double fps = av_q2d( frame_rate );
1774 #if LIBAVFORMAT_VERSION_MAJOR < 55
1775 // Verify and sanitize the muxer frame rate.
1776 if ( isnan( fps ) || isinf( fps ) || fps == 0 )
1778 frame_rate = stream->r_frame_rate;
1779 fps = av_q2d( frame_rate );
1782 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0) && LIBAVFORMAT_VERSION_MAJOR < 55
1783 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1784 // avg_frame_rate gives some approximate value that does not well match the media.
1785 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1786 // results in some very choppy output, but some value slightly different works
1788 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1790 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1791 fps = av_q2d( frame_rate );
1794 // XXX frame rates less than 1 fps are not considered sane
1795 if ( isnan( fps ) || isinf( fps ) || fps < 1.0 )
1797 // Get the frame rate from the codec.
1798 frame_rate.num = self->video_codec->time_base.den;
1799 frame_rate.den = self->video_codec->time_base.num * self->video_codec->ticks_per_frame;
1800 fps = av_q2d( frame_rate );
1802 if ( isnan( fps ) || isinf( fps ) || fps < 1.0 )
1804 // Use the profile frame rate if all else fails.
1805 mlt_profile profile = mlt_service_profile( MLT_PRODUCER_SERVICE( self->parent ) );
1806 frame_rate.num = profile->frame_rate_num;
1807 frame_rate.den = profile->frame_rate_den;
1810 self->video_time_base = stream->time_base;
1811 if ( mlt_properties_get( properties, "force_fps" ) )
1813 AVRational force_fps = av_d2q( mlt_properties_get_double( properties, "force_fps" ), 1024 );
1814 self->video_time_base = av_mul_q( stream->time_base, av_div_q( frame_rate, force_fps ) );
1815 frame_rate = force_fps;
1817 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1818 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1820 // Set the YUV colorspace from override or detect
1821 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1822 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1823 if ( ! self->colorspace )
1825 switch ( self->video_codec->colorspace )
1827 case AVCOL_SPC_SMPTE240M:
1828 self->colorspace = 240;
1830 case AVCOL_SPC_BT470BG:
1831 case AVCOL_SPC_SMPTE170M:
1832 self->colorspace = 601;
1834 case AVCOL_SPC_BT709:
1835 self->colorspace = 709;
1838 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1839 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1844 // Let apps get chosen colorspace
1845 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1847 self->full_luma = -1;
1848 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(72<<8)+2)
1849 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent), "color_range %d\n", codec_context->color_range );
1850 if ( codec_context->color_range == AVCOL_RANGE_JPEG )
1851 self->full_luma = 1;
1853 if ( mlt_properties_get( properties, "set.force_full_luma" ) )
1854 self->full_luma = mlt_properties_get_int( properties, "set.force_full_luma" );
1856 return self->video_codec && self->video_index > -1;
1859 /** Set up video handling.
1862 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1865 mlt_producer producer = self->parent;
1867 // Get the properties
1868 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1870 // Fetch the video format context
1871 AVFormatContext *context = self->video_format;
1873 // Get the video_index
1874 int index = mlt_properties_get_int( properties, "video_index" );
1876 int unlock_needed = 0;
1878 // Reopen the file if necessary
1879 if ( !context && index > -1 )
1882 pthread_mutex_lock( &self->video_mutex );
1883 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1884 mlt_properties_get( properties, "resource" ), 0 );
1885 context = self->video_format;
1888 // Exception handling for video_index
1889 if ( context && index >= (int) context->nb_streams )
1891 // Get the last video stream
1892 for ( index = context->nb_streams - 1;
1893 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1895 mlt_properties_set_int( properties, "video_index", index );
1897 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1899 // Invalidate the video stream
1901 mlt_properties_set_int( properties, "video_index", index );
1904 // Update the video properties if the index changed
1905 if ( index != self->video_index )
1907 // Reset the video properties if the index changed
1908 self->video_index = index;
1909 pthread_mutex_lock( &self->open_mutex );
1910 if ( self->video_codec )
1911 avcodec_close( self->video_codec );
1912 self->video_codec = NULL;
1913 pthread_mutex_unlock( &self->open_mutex );
1916 // Get the frame properties
1917 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1920 if ( context && index > -1 && video_codec_init( self, index, properties ) )
1922 // Set the frame properties
1923 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1924 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1925 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1927 // Set the width and height
1928 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
1929 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
1930 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
1931 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
1932 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1933 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
1935 // Workaround 1088 encodings missing cropping info.
1936 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1938 mlt_properties_set_int( properties, "meta.media.height", 1080 );
1941 // Add our image operation
1942 mlt_frame_push_service( frame, self );
1943 mlt_frame_push_get_image( frame, producer_get_image );
1947 // If something failed, use test card image
1948 mlt_properties_set_int( frame_properties, "test_image", 1 );
1950 if ( unlock_needed )
1951 pthread_mutex_unlock( &self->video_mutex );
1954 static int seek_audio( producer_avformat self, mlt_position position, double timecode )
1958 // Seek if necessary
1959 if ( self->seekable && ( position != self->audio_expected || self->last_position < 0 ) )
1961 if ( self->last_position == POSITION_INITIAL )
1963 int video_index = self->video_index;
1964 if ( video_index == -1 )
1965 video_index = first_video_index( self );
1966 if ( video_index >= 0 )
1967 find_first_pts( self, video_index );
1970 if ( position + 1 == self->audio_expected )
1972 // We're paused - silence required
1975 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
1977 AVFormatContext *context = self->audio_format;
1978 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1979 if ( context->start_time != AV_NOPTS_VALUE )
1980 timestamp += context->start_time;
1981 if ( timestamp < 0 )
1984 // Set to the real timecode
1985 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1988 // Clear the usage in the audio buffer
1989 int i = MAX_AUDIO_STREAMS + 1;
1991 self->audio_used[i - 1] = 0;
1997 static int sample_bytes( AVCodecContext *context )
1999 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(8<<8)+0)
2000 return av_get_bytes_per_sample( context->sample_fmt );
2001 #elif LIBAVCODEC_VERSION_MAJOR >= 53
2002 return av_get_bits_per_sample_fmt( context->sample_fmt ) / 8;
2004 return av_get_bits_per_sample_format( context->sample_fmt ) / 8;
2008 static void planar_to_interleaved( uint8_t *dest, uint8_t *src, int samples, int channels, int bytes_per_sample )
2011 for ( s = 0; s < samples; s++ )
2013 for ( c = 0; c < channels; c++ )
2015 memcpy( dest, src + ( c * samples + s ) * bytes_per_sample, bytes_per_sample );
2016 dest += bytes_per_sample;
2021 static void planar_to_interleaved2( uint8_t *dest, AVFrame *src, int samples, int channels, int bytes_per_sample )
2024 for ( s = 0; s < samples; s++ )
2026 for ( c = 0; c < channels; c++ )
2028 memcpy( dest, &src->data[c][s * bytes_per_sample], bytes_per_sample );
2029 dest += bytes_per_sample;
2034 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
2036 // Fetch the audio_format
2037 AVFormatContext *context = self->audio_format;
2039 // Get the current stream index
2040 int index = pkt.stream_index;
2042 // Get codec context
2043 AVCodecContext *codec_context = self->audio_codec[ index ];
2045 // Obtain the audio buffers
2046 uint8_t *audio_buffer = self->audio_buffer[ index ];
2047 uint8_t *decode_buffer = self->decode_buffer[ index ];
2049 int audio_used = self->audio_used[ index ];
2050 uint8_t *ptr = pkt.data;
2054 while ( ptr && ret >= 0 && len > 0 )
2056 int sizeof_sample = sample_bytes( codec_context );
2057 int data_size = self->audio_buffer_size[ index ];
2060 #if LIBAVCODEC_VERSION_MAJOR >= 55
2061 if ( !self->audio_frame )
2062 self->audio_frame = avcodec_alloc_frame();
2064 avcodec_get_frame_defaults( self->audio_frame );
2065 ret = avcodec_decode_audio4( codec_context, self->audio_frame, &data_size, &pkt );
2067 data_size = av_samples_get_buffer_size( NULL, codec_context->channels,
2068 self->audio_frame->nb_samples, codec_context->sample_fmt, 1 );
2069 decode_buffer = self->audio_frame->data[0];
2072 ret = avcodec_decode_audio3( codec_context, (int16_t*) decode_buffer, &data_size, &pkt );
2076 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
2080 pkt.size = len -= ret;
2081 pkt.data = ptr += ret;
2083 // If decoded successfully
2084 if ( data_size > 0 )
2086 // Figure out how many samples will be needed after resampling
2087 int convert_samples = data_size / codec_context->channels / sample_bytes( codec_context );
2089 // Resize audio buffer to prevent overflow
2090 if ( ( audio_used + convert_samples ) * channels * sizeof_sample > self->audio_buffer_size[ index ] )
2092 self->audio_buffer_size[ index ] = ( audio_used + convert_samples * 2 ) * channels * sizeof_sample;
2093 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] );
2095 uint8_t *dest = &audio_buffer[ audio_used * codec_context->channels * sizeof_sample ];
2096 switch ( codec_context->sample_fmt )
2098 #if LIBAVUTIL_VERSION_INT >= ((51<<16)+(17<<8)+0)
2099 case AV_SAMPLE_FMT_U8P:
2100 case AV_SAMPLE_FMT_S16P:
2101 case AV_SAMPLE_FMT_S32P:
2102 case AV_SAMPLE_FMT_FLTP:
2103 #if LIBAVCODEC_VERSION_MAJOR >= 55
2104 planar_to_interleaved2( dest, self->audio_frame, convert_samples, codec_context->channels, sizeof_sample );
2106 planar_to_interleaved( dest, decode_buffer, convert_samples, codec_context->channels, sizeof_sample );
2111 // Straight copy to audio buffer
2112 memcpy( dest, decode_buffer, data_size );
2114 audio_used += convert_samples;
2117 while ( *ignore && audio_used )
2120 audio_used -= audio_used > samples ? samples : audio_used;
2121 memmove( audio_buffer, &audio_buffer[ samples * codec_context->channels * sizeof_sample ],
2122 audio_used * sizeof_sample );
2127 // If we're behind, ignore this packet
2128 // Skip this on non-seekable, audio-only inputs.
2129 if ( pkt.pts >= 0 && ( self->seekable || self->video_format ) && *ignore == 0 && audio_used > samples / 2 )
2131 int64_t pts = pkt.pts;
2132 if ( self->first_pts != AV_NOPTS_VALUE )
2133 pts -= self->first_pts;
2134 else if ( context->start_time != AV_NOPTS_VALUE )
2135 pts -= context->start_time;
2136 double timebase = av_q2d( context->streams[ index ]->time_base );
2137 int64_t int_position = ( int64_t )( timebase * pts * fps + 0.5 );
2138 int64_t req_position = ( int64_t )( timecode * fps + 0.5 );
2140 mlt_log_debug( MLT_PRODUCER_SERVICE(self->parent),
2141 "A pkt.pts %"PRId64" pkt.dts %"PRId64" req_pos %"PRId64" cur_pos %"PRId64" pkt_pos %"PRId64"\n",
2142 pkt.pts, pkt.dts, req_position, self->current_position, int_position );
2144 if ( int_position > 0 )
2146 if ( int_position < req_position )
2147 // We are behind, so skip some
2148 *ignore = req_position - int_position;
2149 else if ( self->audio_index != INT_MAX && int_position > req_position + 2 )
2150 // We are ahead, so seek backwards some more
2151 seek_audio( self, req_position, timecode - 1.0 );
2153 // Cancel the find_first_pts() in seek_audio()
2154 if ( self->video_index == -1 && self->last_position == POSITION_INITIAL )
2155 self->last_position = int_position;
2158 self->audio_used[ index ] = audio_used;
2163 /** Get the audio from a frame.
2165 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
2168 producer_avformat self = mlt_frame_pop_audio( frame );
2170 pthread_mutex_lock( &self->audio_mutex );
2172 // Obtain the frame number of this frame
2173 mlt_position position = mlt_frame_original_position( frame );
2175 // Calculate the real time code
2176 double real_timecode = producer_time_of_frame( self->parent, position );
2178 // Get the producer fps
2179 double fps = mlt_producer_get_fps( self->parent );
2181 // Number of frames to ignore (for ffwd)
2182 int ignore[ MAX_AUDIO_STREAMS ] = { 0 };
2184 // Flag for paused (silence)
2185 int paused = seek_audio( self, position, real_timecode );
2187 // Initialize ignore for all streams from the seek return value
2188 int i = MAX_AUDIO_STREAMS;
2190 ignore[i] = ignore[0];
2192 // Fetch the audio_format
2193 AVFormatContext *context = self->audio_format;
2195 goto exit_get_audio;
2197 int sizeof_sample = sizeof( int16_t );
2199 // Determine the tracks to use
2200 int index = self->audio_index;
2201 int index_max = self->audio_index + 1;
2202 if ( self->audio_index == INT_MAX )
2205 index_max = FFMIN( MAX_AUDIO_STREAMS, context->nb_streams );
2206 *channels = self->total_channels;
2207 *samples = mlt_sample_calculator( fps, FFMAX( self->max_frequency, *frequency ), position );
2208 *frequency = FFMAX( self->max_frequency, *frequency );
2211 // Initialize the buffers
2212 for ( ; index < index_max && index < MAX_AUDIO_STREAMS; index++ )
2214 // Get codec context
2215 AVCodecContext *codec_context = self->audio_codec[ index ];
2217 if ( codec_context && !self->audio_buffer[ index ] )
2219 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
2220 sizeof_sample = sample_bytes( codec_context );
2222 // Check for audio buffer and create if necessary
2223 self->audio_buffer_size[ index ] = MAX_AUDIO_FRAME_SIZE * sizeof_sample;
2224 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] );
2226 // Check for decoder buffer and create if necessary
2227 self->decode_buffer[ index ] = av_malloc( self->audio_buffer_size[ index ] );
2231 // Get the audio if required
2232 if ( !paused && *frequency > 0 )
2238 av_init_packet( &pkt );
2240 // Caller requested number samples based on requested sample rate.
2241 if ( self->audio_index != INT_MAX )
2242 *samples = mlt_sample_calculator( fps, self->audio_codec[ self->audio_index ]->sample_rate, position );
2244 while ( ret >= 0 && !got_audio )
2246 // Check if the buffer already contains the samples required
2247 if ( self->audio_index != INT_MAX &&
2248 self->audio_used[ self->audio_index ] >= *samples &&
2249 ignore[ self->audio_index ] == 0 )
2254 else if ( self->audio_index == INT_MAX )
2256 // Check if there is enough audio for all streams
2258 for ( index = 0; got_audio && index < index_max; index++ )
2259 if ( ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples ) || ignore[ index ] )
2266 pthread_mutex_lock( &self->packets_mutex );
2267 if ( mlt_deque_count( self->apackets ) )
2269 AVPacket *tmp = (AVPacket*) mlt_deque_pop_front( self->apackets );
2275 ret = av_read_frame( context, &pkt );
2276 if ( ret >= 0 && !self->seekable && pkt.stream_index == self->video_index )
2278 if ( !av_dup_packet( &pkt ) )
2280 AVPacket *tmp = malloc( sizeof(AVPacket) );
2282 mlt_deque_push_back( self->vpackets, tmp );
2287 mlt_log_verbose( MLT_PRODUCER_SERVICE(self->parent), "av_read_frame returned error %d inside get_audio\n", ret );
2288 if ( !self->seekable && mlt_properties_get_int( MLT_PRODUCER_PROPERTIES( self->parent ), "reconnect" ) )
2290 // Try to reconnect to live sources by closing context and codecs,
2291 // and letting next call to get_frame() reopen.
2292 prepare_reopen( self );
2293 pthread_mutex_unlock( &self->packets_mutex );
2294 goto exit_get_audio;
2298 pthread_mutex_unlock( &self->packets_mutex );
2300 // We only deal with audio from the selected audio index
2301 index = pkt.stream_index;
2302 if ( index < MAX_AUDIO_STREAMS && ret >= 0 && pkt.data && pkt.size > 0 && ( index == self->audio_index ||
2303 ( self->audio_index == INT_MAX && context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2305 int channels2 = self->audio_codec[index]->channels;
2306 ret = decode_audio( self, &ignore[index], pkt, channels2, *samples, real_timecode, fps );
2309 if ( self->seekable || index != self->video_index )
2310 av_free_packet( &pkt );
2314 // Set some additional return values
2315 *format = mlt_audio_s16;
2316 if ( self->audio_index != INT_MAX )
2318 index = self->audio_index;
2319 *channels = self->audio_codec[ index ]->channels;
2320 *frequency = self->audio_codec[ index ]->sample_rate;
2321 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2322 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2324 else if ( self->audio_index == INT_MAX )
2326 for ( index = 0; index < index_max; index++ )
2327 if ( self->audio_codec[ index ] )
2329 // XXX: This only works if all audio tracks have the same sample format.
2330 *format = pick_audio_format( self->audio_codec[ index ]->sample_fmt );
2331 sizeof_sample = sample_bytes( self->audio_codec[ index ] );
2336 // Allocate and set the frame's audio buffer
2337 int size = mlt_audio_format_size( *format, *samples, *channels );
2338 *buffer = mlt_pool_alloc( size );
2339 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2341 // Interleave tracks if audio_index=all
2342 if ( self->audio_index == INT_MAX )
2344 uint8_t *dest = *buffer;
2346 for ( i = 0; i < *samples; i++ )
2348 for ( index = 0; index < index_max; index++ )
2349 if ( self->audio_codec[ index ] )
2351 int current_channels = self->audio_codec[ index ]->channels;
2352 uint8_t *src = self->audio_buffer[ index ] + i * current_channels * sizeof_sample;
2353 memcpy( dest, src, current_channels * sizeof_sample );
2354 dest += current_channels * sizeof_sample;
2357 for ( index = 0; index < index_max; index++ )
2358 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2360 int current_channels = self->audio_codec[ index ]->channels;
2361 uint8_t *src = self->audio_buffer[ index ] + *samples * current_channels * sizeof_sample;
2362 self->audio_used[index] -= *samples;
2363 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof_sample );
2366 // Copy a single track to the output buffer
2369 index = self->audio_index;
2371 // Now handle the audio if we have enough
2372 if ( self->audio_used[ index ] > 0 )
2374 uint8_t *src = self->audio_buffer[ index ];
2375 // copy samples from audio_buffer
2376 size = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2377 memcpy( *buffer, src, size * *channels * sizeof_sample );
2378 // supply the remaining requested samples as silence
2379 if ( *samples > self->audio_used[ index ] )
2380 memset( *buffer + size * *channels * sizeof_sample, 0, ( *samples - self->audio_used[ index ] ) * *channels * sizeof_sample );
2381 // reposition the samples within audio_buffer
2382 self->audio_used[ index ] -= size;
2383 memmove( src, src + size * *channels * sizeof_sample, self->audio_used[ index ] * *channels * sizeof_sample );
2387 // Otherwise fill with silence
2388 memset( *buffer, 0, *samples * *channels * sizeof_sample );
2395 // Get silence and don't touch the context
2396 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2399 // Regardless of speed (other than paused), we expect to get the next frame
2401 self->audio_expected = position + 1;
2403 pthread_mutex_unlock( &self->audio_mutex );
2408 /** Initialize the audio codec context.
2411 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2413 // Initialise the codec if necessary
2414 if ( !self->audio_codec[ index ] )
2416 // Get codec context
2417 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2420 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2422 // If we don't have a codec and we can't initialise it, we can't do much more...
2423 pthread_mutex_lock( &self->open_mutex );
2424 #if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
2425 if ( codec && avcodec_open2( codec_context, codec, NULL ) >= 0 )
2427 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2430 // Now store the codec with its destructor
2431 if ( self->audio_codec[ index ] )
2432 avcodec_close( self->audio_codec[ index ] );
2433 self->audio_codec[ index ] = codec_context;
2437 // Remember that we can't use self later
2438 self->audio_index = -1;
2440 pthread_mutex_unlock( &self->open_mutex );
2442 // Process properties as AVOptions
2443 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2444 if ( codec && codec->priv_class && codec_context->priv_data )
2445 apply_properties( codec_context->priv_data, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2447 return self->audio_codec[ index ] && self->audio_index > -1;
2450 /** Set up audio handling.
2453 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2456 mlt_producer producer = self->parent;
2458 // Get the properties
2459 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2461 // Fetch the audio format context
2462 AVFormatContext *context = self->audio_format;
2464 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2466 // Get the audio_index
2467 int index = mlt_properties_get_int( properties, "audio_index" );
2469 // Handle all audio tracks
2470 if ( self->audio_index > -1 &&
2471 mlt_properties_get( properties, "audio_index" ) &&
2472 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2475 // Reopen the file if necessary
2476 if ( !context && self->audio_index > -1 && index > -1 )
2478 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2479 mlt_properties_get( properties, "resource" ), 1 );
2480 context = self->audio_format;
2483 // Exception handling for audio_index
2484 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2486 for ( index = context->nb_streams - 1;
2487 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2489 mlt_properties_set_int( properties, "audio_index", index );
2491 if ( context && index > -1 && index < INT_MAX &&
2492 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2494 index = self->audio_index;
2495 mlt_properties_set_int( properties, "audio_index", index );
2497 if ( context && index > -1 && index < INT_MAX &&
2498 pick_audio_format( context->streams[ index ]->codec->sample_fmt ) == mlt_audio_none )
2503 // Update the audio properties if the index changed
2504 if ( context && index > -1 && index != self->audio_index )
2506 pthread_mutex_lock( &self->open_mutex );
2507 if ( self->audio_codec[ self->audio_index ] )
2508 avcodec_close( self->audio_codec[ self->audio_index ] );
2509 self->audio_codec[ self->audio_index ] = NULL;
2510 pthread_mutex_unlock( &self->open_mutex );
2512 if ( self->audio_index != -1 )
2513 self->audio_index = index;
2518 if ( context && index == INT_MAX )
2520 mlt_properties_set_int( frame_properties, "audio_frequency", self->max_frequency );
2521 mlt_properties_set_int( frame_properties, "audio_channels", self->total_channels );
2522 for ( index = 0; index < context->nb_streams; index++ )
2524 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2525 audio_codec_init( self, index, properties );
2528 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2530 // Set the frame properties
2531 if ( index < MAX_AUDIO_STREAMS )
2533 mlt_properties_set_int( frame_properties, "audio_frequency", self->audio_codec[ index ]->sample_rate );
2534 mlt_properties_set_int( frame_properties, "audio_channels", self->audio_codec[ index ]->channels );
2537 if ( context && index > -1 )
2539 // Add our audio operation
2540 mlt_frame_push_audio( frame, self );
2541 mlt_frame_push_audio( frame, producer_get_audio );
2545 /** Our get frame implementation.
2548 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2550 // Access the private data
2551 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2552 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2553 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2558 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2559 producer->child = self;
2560 self->parent = producer;
2561 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2562 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2565 // Create an empty frame
2566 *frame = mlt_frame_init( service);
2570 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2574 mlt_cache_item_close( cache_item );
2578 // Update timecode on the frame we're creating
2579 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2582 producer_set_up_video( self, *frame );
2585 producer_set_up_audio( self, *frame );
2587 // Set the position of this producer
2588 mlt_position position = self->seekable ? mlt_producer_frame( producer ) : self->nonseek_position++;
2589 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "original_position", position );
2591 // Calculate the next timecode
2592 mlt_producer_prepare_next( producer );
2597 static void producer_avformat_close( producer_avformat self )
2599 mlt_log_debug( NULL, "producer_avformat_close\n" );
2601 // Cleanup av contexts
2602 av_free_packet( &self->pkt );
2603 av_free( self->video_frame );
2604 av_free( self->audio_frame );
2605 pthread_mutex_lock( &self->open_mutex );
2607 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2609 mlt_pool_release( self->audio_buffer[i] );
2610 av_free( self->decode_buffer[i] );
2611 if ( self->audio_codec[i] )
2612 avcodec_close( self->audio_codec[i] );
2613 self->audio_codec[i] = NULL;
2615 if ( self->video_codec )
2616 avcodec_close( self->video_codec );
2617 self->video_codec = NULL;
2619 #if LIBAVFORMAT_VERSION_INT >= ((53<<16)+(17<<8)+0)
2620 if ( self->dummy_context )
2621 avformat_close_input( &self->dummy_context );
2622 if ( self->seekable && self->audio_format )
2623 avformat_close_input( &self->audio_format );
2624 if ( self->video_format )
2625 avformat_close_input( &self->video_format );
2627 if ( self->dummy_context )
2628 av_close_input_file( self->dummy_context );
2629 if ( self->seekable && self->audio_format )
2630 av_close_input_file( self->audio_format );
2631 if ( self->video_format )
2632 av_close_input_file( self->video_format );
2634 pthread_mutex_unlock( &self->open_mutex );
2636 vdpau_producer_close( self );
2638 if ( self->image_cache )
2639 mlt_cache_close( self->image_cache );
2641 // Cleanup the mutexes
2642 if ( self->is_mutex_init )
2644 pthread_mutex_destroy( &self->audio_mutex );
2645 pthread_mutex_destroy( &self->video_mutex );
2646 pthread_mutex_destroy( &self->packets_mutex );
2647 pthread_mutex_destroy( &self->open_mutex );
2650 // Cleanup the packet queues
2652 if ( self->apackets )
2654 while ( ( pkt = mlt_deque_pop_back( self->apackets ) ) )
2656 av_free_packet( pkt );
2659 mlt_deque_close( self->apackets );
2660 self->apackets = NULL;
2662 if ( self->vpackets )
2664 while ( ( pkt = mlt_deque_pop_back( self->vpackets ) ) )
2666 av_free_packet( pkt );
2669 mlt_deque_close( self->vpackets );
2670 self->vpackets = NULL;
2676 static void producer_close( mlt_producer parent )
2678 // Remove this instance from the cache
2679 mlt_service_cache_purge( MLT_PRODUCER_SERVICE(parent) );
2682 parent->close = NULL;
2683 mlt_producer_close( parent );