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>
34 #include <libavcodec/opt.h>
36 # include <libswscale/swscale.h>
38 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
39 # include "audioconvert.h"
42 # include <libavcodec/vdpau.h>
44 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
45 # include <libavutil/pixdesc.h>
48 // System header files
54 #if LIBAVUTIL_VERSION_INT < (50<<16)
55 #define PIX_FMT_RGB32 PIX_FMT_RGBA32
56 #define PIX_FMT_YUYV422 PIX_FMT_YUV422
59 #define POSITION_INITIAL (-2)
60 #define POSITION_INVALID (-1)
62 #define MAX_AUDIO_STREAMS (10)
63 #define MAX_VDPAU_SURFACES (10)
65 void avformat_lock( );
66 void avformat_unlock( );
68 struct producer_avformat_s
71 AVFormatContext *dummy_context;
72 AVFormatContext *audio_format;
73 AVFormatContext *video_format;
74 AVCodecContext *audio_codec[ MAX_AUDIO_STREAMS ];
75 AVCodecContext *video_codec;
77 ReSampleContext *audio_resample[ MAX_AUDIO_STREAMS ];
78 mlt_position audio_expected;
79 mlt_position video_expected;
89 int16_t *audio_buffer[ MAX_AUDIO_STREAMS ];
90 size_t audio_buffer_size[ MAX_AUDIO_STREAMS ];
91 int16_t *decode_buffer[ MAX_AUDIO_STREAMS ];
92 int audio_used[ MAX_AUDIO_STREAMS ];
98 unsigned int invalid_pts_counter;
99 double resample_factor;
100 mlt_cache image_cache;
106 struct vdpau_render_state render_states[MAX_VDPAU_SURFACES];
117 typedef struct producer_avformat_s *producer_avformat;
119 // Forward references.
120 static int producer_open( producer_avformat self, mlt_profile profile, char *file );
121 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
122 static void producer_avformat_close( producer_avformat );
123 static void producer_close( mlt_producer parent );
124 static void producer_set_up_video( producer_avformat self, mlt_frame frame );
130 /** Constructor for libavformat.
133 mlt_producer producer_avformat_init( mlt_profile profile, const char *service, char *file )
137 // Report information about available demuxers and codecs as YAML Tiny
138 if ( file && strstr( file, "f-list" ) )
140 fprintf( stderr, "---\nformats:\n" );
141 AVInputFormat *format = NULL;
142 while ( ( format = av_iformat_next( format ) ) )
143 fprintf( stderr, " - %s\n", format->name );
144 fprintf( stderr, "...\n" );
147 if ( file && strstr( file, "acodec-list" ) )
149 fprintf( stderr, "---\naudio_codecs:\n" );
150 AVCodec *codec = NULL;
151 while ( ( codec = av_codec_next( codec ) ) )
152 if ( codec->decode && codec->type == CODEC_TYPE_AUDIO )
153 fprintf( stderr, " - %s\n", codec->name );
154 fprintf( stderr, "...\n" );
157 if ( file && strstr( file, "vcodec-list" ) )
159 fprintf( stderr, "---\nvideo_codecs:\n" );
160 AVCodec *codec = NULL;
161 while ( ( codec = av_codec_next( codec ) ) )
162 if ( codec->decode && codec->type == CODEC_TYPE_VIDEO )
163 fprintf( stderr, " - %s\n", codec->name );
164 fprintf( stderr, "...\n" );
168 // Check that we have a non-NULL argument
171 // Construct the producer
172 mlt_producer producer = calloc( 1, sizeof( struct mlt_producer_s ) );
173 producer_avformat self = calloc( 1, sizeof( struct producer_avformat_s ) );
176 if ( mlt_producer_init( producer, self ) == 0 )
178 self->parent = producer;
180 // Get the properties
181 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
183 // Set the resource property (required for all producers)
184 mlt_properties_set( properties, "resource", file );
186 // Register transport implementation with the producer
187 producer->close = (mlt_destructor) producer_close;
189 // Register our get_frame implementation
190 producer->get_frame = producer_get_frame;
192 if ( strcmp( service, "avformat-novalidate" ) )
195 if ( producer_open( self, profile, file ) != 0 )
198 mlt_producer_close( producer );
203 // Close the file to release resources for large playlists - reopen later as needed
205 if ( self->dummy_context )
206 av_close_input_file( self->dummy_context );
207 self->dummy_context = NULL;
208 if ( self->audio_format )
209 av_close_input_file( self->audio_format );
210 self->audio_format = NULL;
211 if ( self->video_format )
212 av_close_input_file( self->video_format );
213 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 );
221 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
223 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
229 mlt_service_cache_set_size( MLT_PRODUCER_SERVICE(producer), "producer_avformat", 5 );
231 mlt_service_cache_put( MLT_PRODUCER_SERVICE(producer), "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
239 /** Find the default streams.
242 static mlt_properties find_default_streams( mlt_properties meta_media, AVFormatContext *context, int *audio_index, int *video_index )
246 AVMetadataTag *tag = NULL;
248 mlt_properties_set_int( meta_media, "meta.media.nb_streams", context->nb_streams );
250 // Allow for multiple audio and video streams in the file and select first of each (if available)
251 for( i = 0; i < context->nb_streams; i++ )
253 // Get the codec context
254 AVStream *stream = context->streams[ i ];
255 if ( ! stream ) continue;
256 AVCodecContext *codec_context = stream->codec;
257 if ( ! codec_context ) continue;
258 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
259 if ( ! codec ) continue;
261 snprintf( key, sizeof(key), "meta.media.%d.stream.type", i );
263 // Determine the type and obtain the first index of each type
264 switch( codec_context->codec_type )
266 case CODEC_TYPE_VIDEO:
267 if ( *video_index < 0 )
269 mlt_properties_set( meta_media, key, "video" );
270 snprintf( key, sizeof(key), "meta.media.%d.stream.frame_rate", i );
271 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
272 double ffmpeg_fps = av_q2d( context->streams[ i ]->avg_frame_rate );
273 if (ffmpeg_fps == 0) ffmpeg_fps = av_q2d( context->streams[ i ]->r_frame_rate );
274 mlt_properties_set_double( meta_media, key, ffmpeg_fps );
276 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->r_frame_rate ) );
279 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
280 snprintf( key, sizeof(key), "meta.media.%d.stream.sample_aspect_ratio", i );
281 mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->sample_aspect_ratio ) );
283 snprintf( key, sizeof(key), "meta.media.%d.codec.frame_rate", i );
284 mlt_properties_set_double( meta_media, key, (double) codec_context->time_base.den /
285 ( codec_context->time_base.num == 0 ? 1 : codec_context->time_base.num ) );
286 snprintf( key, sizeof(key), "meta.media.%d.codec.pix_fmt", i );
287 mlt_properties_set( meta_media, key, avcodec_get_pix_fmt_name( codec_context->pix_fmt ) );
288 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_aspect_ratio", i );
289 mlt_properties_set_double( meta_media, key, av_q2d( codec_context->sample_aspect_ratio ) );
290 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
291 snprintf( key, sizeof(key), "meta.media.%d.codec.colorspace", i );
292 switch ( codec_context->colorspace )
294 case AVCOL_SPC_SMPTE240M:
295 mlt_properties_set_int( meta_media, key, 240 );
297 case AVCOL_SPC_BT470BG:
298 case AVCOL_SPC_SMPTE170M:
299 mlt_properties_set_int( meta_media, key, 601 );
301 case AVCOL_SPC_BT709:
302 mlt_properties_set_int( meta_media, key, 709 );
305 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
306 mlt_properties_set_int( meta_media, key, codec_context->width * codec_context->height > 750000 ? 709 : 601 );
311 case CODEC_TYPE_AUDIO:
312 if ( *audio_index < 0 )
314 mlt_properties_set( meta_media, key, "audio" );
315 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(71<<8)+0))
316 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_fmt", i );
317 mlt_properties_set( meta_media, key, avcodec_get_sample_fmt_name( codec_context->sample_fmt ) );
319 snprintf( key, sizeof(key), "meta.media.%d.codec.sample_rate", i );
320 mlt_properties_set_int( meta_media, key, codec_context->sample_rate );
321 snprintf( key, sizeof(key), "meta.media.%d.codec.channels", i );
322 mlt_properties_set_int( meta_media, key, codec_context->channels );
327 // snprintf( key, sizeof(key), "meta.media.%d.stream.time_base", i );
328 // mlt_properties_set_double( meta_media, key, av_q2d( context->streams[ i ]->time_base ) );
329 snprintf( key, sizeof(key), "meta.media.%d.codec.name", i );
330 mlt_properties_set( meta_media, key, codec->name );
331 #if (LIBAVCODEC_VERSION_INT >= ((51<<16)+(55<<8)+0))
332 snprintf( key, sizeof(key), "meta.media.%d.codec.long_name", i );
333 mlt_properties_set( meta_media, key, codec->long_name );
335 snprintf( key, sizeof(key), "meta.media.%d.codec.bit_rate", i );
336 mlt_properties_set_int( meta_media, key, codec_context->bit_rate );
337 // snprintf( key, sizeof(key), "meta.media.%d.codec.time_base", i );
338 // mlt_properties_set_double( meta_media, key, av_q2d( codec_context->time_base ) );
339 // snprintf( key, sizeof(key), "meta.media.%d.codec.profile", i );
340 // mlt_properties_set_int( meta_media, key, codec_context->profile );
341 // snprintf( key, sizeof(key), "meta.media.%d.codec.level", i );
342 // mlt_properties_set_int( meta_media, key, codec_context->level );
345 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
346 while ( ( tag = av_metadata_get( stream->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
348 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
350 snprintf( key, sizeof(key), "meta.attr.%d.stream.%s.markup", i, tag->key );
351 mlt_properties_set( meta_media, key, tag->value );
356 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(31<<8)+0)
357 while ( ( tag = av_metadata_get( context->metadata, "", tag, AV_METADATA_IGNORE_SUFFIX ) ) )
359 if ( tag->value && strcmp( tag->value, "" ) && strcmp( tag->value, "und" ) )
361 snprintf( key, sizeof(key), "meta.attr.%s.markup", tag->key );
362 mlt_properties_set( meta_media, key, tag->value );
366 if ( context->title && strcmp( context->title, "" ) )
367 mlt_properties_set(properties, "meta.attr.title.markup", context->title );
368 if ( context->author && strcmp( context->author, "" ) )
369 mlt_properties_set(properties, "meta.attr.author.markup", context->author );
370 if ( context->copyright && strcmp( context->copyright, "" ) )
371 mlt_properties_set(properties, "meta.attr.copyright.markup", context->copyright );
372 if ( context->comment )
373 mlt_properties_set(properties, "meta.attr.comment.markup", context->comment );
374 if ( context->album )
375 mlt_properties_set(properties, "meta.attr.album.markup", context->album );
377 mlt_properties_set_int(properties, "meta.attr.year.markup", context->year );
378 if ( context->track )
379 mlt_properties_set_int(properties, "meta.attr.track.markup", context->track );
385 static inline int dv_is_pal( AVPacket *pkt )
387 return pkt->data[3] & 0x80;
390 static int dv_is_wide( AVPacket *pkt )
392 int i = 80 /* block size */ *3 /* VAUX starts at block 3 */ +3 /* skip block header */;
394 for ( ; i < pkt->size; i += 5 /* packet size */ )
396 if ( pkt->data[ i ] == 0x61 )
398 uint8_t x = pkt->data[ i + 2 ] & 0x7;
399 return ( x == 2 ) || ( x == 7 );
405 static double get_aspect_ratio( mlt_properties properties, AVStream *stream, AVCodecContext *codec_context, AVPacket *pkt )
407 double aspect_ratio = 1.0;
409 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
413 if ( dv_is_pal( pkt ) )
415 if ( dv_is_wide( pkt ) )
417 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
418 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
422 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
423 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
428 if ( dv_is_wide( pkt ) )
430 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
431 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
435 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
436 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
443 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
444 stream->sample_aspect_ratio;
446 codec_context->sample_aspect_ratio;
448 // Override FFmpeg's notion of DV aspect ratios, which are
449 // based upon a width of 704. Since we do not have a normaliser
450 // that crops (nor is cropping 720 wide ITU-R 601 video always desirable)
451 // we just coerce the values to facilitate a passive behaviour through
452 // the rescale normaliser when using equivalent producers and consumers.
453 // = display_aspect / (width * height)
454 if ( ar.num == 10 && ar.den == 11 )
457 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 8 );
458 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 9 );
460 else if ( ar.num == 59 && ar.den == 54 )
463 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 16 );
464 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 15 );
466 else if ( ar.num == 40 && ar.den == 33 )
469 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 32 );
470 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 27 );
472 else if ( ar.num == 118 && ar.den == 81 )
475 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 64 );
476 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 45 );
482 AVRational codec_sar = codec_context->sample_aspect_ratio;
483 AVRational stream_sar =
484 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(21<<8)+0)
485 stream->sample_aspect_ratio;
489 if ( codec_sar.num > 0 )
491 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", codec_sar.num );
492 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", codec_sar.den );
494 else if ( stream_sar.num > 0 )
496 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", stream_sar.num );
497 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", stream_sar.den );
501 mlt_properties_set_int( properties, "meta.media.sample_aspect_num", 1 );
502 mlt_properties_set_int( properties, "meta.media.sample_aspect_den", 1 );
505 AVRational ar = { mlt_properties_get_double( properties, "meta.media.sample_aspect_num" ), mlt_properties_get_double( properties, "meta.media.sample_aspect_den" ) };
506 aspect_ratio = av_q2d( ar );
507 mlt_properties_set_double( properties, "aspect_ratio", aspect_ratio );
515 static int producer_open( producer_avformat self, mlt_profile profile, char *file )
517 // Return an error code (0 == no error)
520 // Context for avformat
521 AVFormatContext *context = NULL;
523 // Get the properties
524 mlt_properties properties = MLT_PRODUCER_PROPERTIES( self->parent );
526 // We will treat everything with the producer fps
527 double fps = mlt_profile_fps( profile );
529 // Lock the mutex now
532 // If "MRL", then create AVInputFormat
533 AVInputFormat *format = NULL;
534 AVFormatParameters *params = NULL;
535 char *standard = NULL;
536 char *mrl = strchr( file, ':' );
538 // AV option (0 = both, 1 = video, 2 = audio)
541 // Only if there is not a protocol specification that avformat can handle
542 if ( mrl && !url_exist( file ) )
544 // 'file' becomes format abbreviation
548 format = av_find_input_format( file );
550 // Eat the format designator
556 params = calloc( sizeof( AVFormatParameters ), 1 );
558 // These are required by video4linux (defaults)
560 params->height = 480;
561 params->time_base= (AVRational){1,25};
562 params->channels = 2;
563 params->sample_rate = 48000;
567 mrl = strchr( file, '?' );
571 char *name = strdup( ++mrl );
572 char *value = strchr( name, ':' );
577 char *t = strchr( value, '&' );
580 if ( !strcmp( name, "frame_rate" ) )
581 params->time_base.den = atoi( value );
582 else if ( !strcmp( name, "frame_rate_base" ) )
583 params->time_base.num = atoi( value );
584 else if ( !strcmp( name, "sample_rate" ) )
585 params->sample_rate = atoi( value );
586 else if ( !strcmp( name, "channel" ) )
587 params->channel = atoi( value );
588 else if ( !strcmp( name, "channels" ) )
589 params->channels = atoi( value );
590 #if (LIBAVUTIL_VERSION_INT > ((50<<16)+(7<<8)+0))
591 else if ( !strcmp( name, "pix_fmt" ) )
592 params->pix_fmt = av_get_pix_fmt( value );
594 else if ( !strcmp( name, "width" ) )
595 params->width = atoi( value );
596 else if ( !strcmp( name, "height" ) )
597 params->height = atoi( value );
598 else if ( !strcmp( name, "standard" ) )
600 standard = strdup( value );
601 params->standard = standard;
603 else if ( !strcmp( name, "av" ) )
607 mrl = strchr( mrl, '&' );
611 // Now attempt to open the file
612 error = av_open_input_file( &context, file, format, 0, params ) < 0;
614 // Cleanup AVFormatParameters
618 // If successful, then try to get additional info
621 // Get the stream info
622 error = av_find_stream_info( context ) < 0;
624 // Continue if no error
627 // We will default to the first audio and video streams found
628 int audio_index = -1;
629 int video_index = -1;
631 // Find default audio and video streams
632 find_default_streams( properties, context, &audio_index, &video_index );
634 // Now set properties where we can (use default unknowns if required)
635 if ( context->duration != AV_NOPTS_VALUE )
637 // This isn't going to be accurate for all formats
638 mlt_position frames = ( mlt_position )( ( ( double )context->duration / ( double )AV_TIME_BASE ) * fps - 1 );
640 // Workaround some clips whose estimated duration cause problems:
641 // http://www.kdenlive.org/mantis/view.php?id=2003
642 char *comment = mlt_properties_get( properties, "meta.attr.comment.markup" );
643 if ( comment && strstr( comment, "KODAK" ) && strstr( comment, "Zx3" ) )
646 mlt_properties_set_position( properties, "out", frames - 1 );
647 mlt_properties_set_position( properties, "length", frames );
650 if ( context->start_time != AV_NOPTS_VALUE )
651 self->start_time = context->start_time;
653 // Check if we're seekable
654 // avdevices are typically AVFMT_NOFILE and not seekable
655 self->seekable = !format || !( format->flags & AVFMT_NOFILE );
658 // protocols can indicate if they support seeking
659 URLContext *uc = url_fileno( context->pb );
661 self->seekable = !uc->is_streamed;
663 if ( self->seekable )
665 self->seekable = av_seek_frame( context, -1, self->start_time, AVSEEK_FLAG_BACKWARD ) >= 0;
666 mlt_properties_set_int( properties, "seekable", self->seekable );
667 self->dummy_context = context;
668 av_open_input_file( &context, file, NULL, 0, NULL );
669 av_find_stream_info( context );
672 // Store selected audio and video indexes on properties
673 self->audio_index = audio_index;
674 self->video_index = video_index;
675 self->first_pts = -1;
676 self->last_position = POSITION_INITIAL;
678 // Fetch the width, height and aspect ratio
679 if ( video_index != -1 )
681 AVCodecContext *codec_context = context->streams[ video_index ]->codec;
682 mlt_properties_set_int( properties, "width", codec_context->width );
683 mlt_properties_set_int( properties, "height", codec_context->height );
685 if ( codec_context->codec_id == CODEC_ID_DVVIDEO )
687 // Fetch the first frame of DV so we can read it directly
692 ret = av_read_frame( context, &pkt );
693 if ( ret >= 0 && pkt.stream_index == video_index && pkt.size > 0 )
695 get_aspect_ratio( properties, context->streams[ video_index ], codec_context, &pkt );
702 get_aspect_ratio( properties, context->streams[ video_index ], codec_context, NULL );
705 struct SwsContext *context = sws_getContext( codec_context->width, codec_context->height, codec_context->pix_fmt,
706 codec_context->width, codec_context->height, PIX_FMT_YUYV422, SWS_BILINEAR, NULL, NULL, NULL);
708 sws_freeContext( context );
714 // We're going to cheat here - for a/v files, we will have two contexts (reasoning will be clear later)
715 if ( av == 0 && audio_index != -1 && video_index != -1 )
717 // We'll use the open one as our video_format
718 self->video_format = context;
720 // And open again for our audio context
721 av_open_input_file( &context, file, NULL, 0, NULL );
722 av_find_stream_info( context );
725 self->audio_format = context;
727 else if ( av != 2 && video_index != -1 )
729 // We only have a video context
730 self->video_format = context;
732 else if ( audio_index != -1 )
734 // We only have an audio context
735 self->audio_format = context;
739 // Something has gone wrong
745 // Unlock the mutex now
751 /** Convert a frame position to a time code.
754 static double producer_time_of_frame( mlt_producer producer, mlt_position position )
756 return ( double )position / mlt_producer_get_fps( producer );
759 // Collect information about all audio streams
761 static void get_audio_streams_info( producer_avformat self )
763 // Fetch the audio format context
764 AVFormatContext *context = self->audio_format;
768 i < context->nb_streams;
771 if ( context->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO )
773 AVCodecContext *codec_context = context->streams[i]->codec;
774 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
776 // If we don't have a codec and we can't initialise it, we can't do much more...
778 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
780 self->audio_streams++;
781 self->audio_max_stream = i;
782 self->total_channels += codec_context->channels;
783 if ( codec_context->channels > self->max_channel )
784 self->max_channel = codec_context->channels;
785 if ( codec_context->sample_rate > self->max_frequency )
786 self->max_frequency = codec_context->sample_rate;
787 avcodec_close( codec_context );
792 mlt_log_verbose( NULL, "[producer avformat] audio: total_streams %d max_stream %d total_channels %d max_channels %d\n",
793 self->audio_streams, self->audio_max_stream, self->total_channels, self->max_channel );
795 // Other audio-specific initializations
796 self->resample_factor = 1.0;
799 static void set_luma_transfer( struct SwsContext *context, int colorspace, int use_full_range )
801 #if defined(SWSCALE) && (LIBSWSCALE_VERSION_INT >= ((0<<16)+(7<<8)+2))
804 int brightness, contrast, saturation;
806 if ( sws_getColorspaceDetails( context, &coefficients, &full_range, &coefficients, &full_range,
807 &brightness, &contrast, &saturation ) != -1 )
809 // Don't change these from defaults unless explicitly told to.
810 if ( use_full_range >= 0 )
811 full_range = use_full_range;
812 switch ( colorspace )
818 coefficients = sws_getCoefficients( SWS_CS_ITU601 );
821 coefficients = sws_getCoefficients( SWS_CS_SMPTE240M );
824 coefficients = sws_getCoefficients( SWS_CS_ITU709 );
827 sws_setColorspaceDetails( context, coefficients, full_range, coefficients, full_range,
828 brightness, contrast, saturation );
833 static inline void convert_image( AVFrame *frame, uint8_t *buffer, int pix_fmt,
834 mlt_image_format *format, int width, int height, int colorspace )
838 int flags = SWS_BILINEAR | SWS_ACCURATE_RND;
841 flags |= SWS_CPU_CAPS_MMX;
844 flags |= SWS_CPU_CAPS_MMX2;
847 if ( pix_fmt == PIX_FMT_RGB32 )
849 *format = mlt_image_rgb24a;
850 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
851 width, height, PIX_FMT_RGBA, flags, NULL, NULL, NULL);
853 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
854 set_luma_transfer( context, colorspace, full_range );
855 sws_scale( context, frame->data, frame->linesize, 0, height,
856 output.data, output.linesize);
857 sws_freeContext( context );
859 else if ( *format == mlt_image_yuv420p )
861 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
862 width, height, PIX_FMT_YUV420P, flags, NULL, NULL, NULL);
864 output.data[0] = buffer;
865 output.data[1] = buffer + width * height;
866 output.data[2] = buffer + ( 5 * width * height ) / 4;
867 output.linesize[0] = width;
868 output.linesize[1] = width >> 1;
869 output.linesize[2] = width >> 1;
870 set_luma_transfer( context, colorspace, full_range );
871 sws_scale( context, frame->data, frame->linesize, 0, height,
872 output.data, output.linesize);
873 sws_freeContext( context );
875 else if ( *format == mlt_image_rgb24 )
877 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
878 width, height, PIX_FMT_RGB24, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
880 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
881 set_luma_transfer( context, colorspace, full_range );
882 sws_scale( context, frame->data, frame->linesize, 0, height,
883 output.data, output.linesize);
884 sws_freeContext( context );
886 else if ( *format == mlt_image_rgb24a || *format == mlt_image_opengl )
888 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
889 width, height, PIX_FMT_RGBA, flags | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
891 avpicture_fill( &output, buffer, PIX_FMT_RGBA, width, height );
892 set_luma_transfer( context, colorspace, full_range );
893 sws_scale( context, frame->data, frame->linesize, 0, height,
894 output.data, output.linesize);
895 sws_freeContext( context );
899 struct SwsContext *context = sws_getContext( width, height, pix_fmt,
900 width, height, PIX_FMT_YUYV422, flags | SWS_FULL_CHR_H_INP, NULL, NULL, NULL);
902 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
903 set_luma_transfer( context, colorspace, full_range );
904 sws_scale( context, frame->data, frame->linesize, 0, height,
905 output.data, output.linesize);
906 sws_freeContext( context );
909 if ( *format == mlt_image_yuv420p )
912 pict.data[0] = buffer;
913 pict.data[1] = buffer + width * height;
914 pict.data[2] = buffer + ( 5 * width * height ) / 4;
915 pict.linesize[0] = width;
916 pict.linesize[1] = width >> 1;
917 pict.linesize[2] = width >> 1;
918 img_convert( &pict, PIX_FMT_YUV420P, (AVPicture *)frame, pix_fmt, width, height );
920 else if ( *format == mlt_image_rgb24 )
923 avpicture_fill( &output, buffer, PIX_FMT_RGB24, width, height );
924 img_convert( &output, PIX_FMT_RGB24, (AVPicture *)frame, pix_fmt, width, height );
926 else if ( format == mlt_image_rgb24a || format == mlt_image_opengl )
929 avpicture_fill( &output, buffer, PIX_FMT_RGB32, width, height );
930 img_convert( &output, PIX_FMT_RGB32, (AVPicture *)frame, pix_fmt, width, height );
935 avpicture_fill( &output, buffer, PIX_FMT_YUYV422, width, height );
936 img_convert( &output, PIX_FMT_YUYV422, (AVPicture *)frame, pix_fmt, width, height );
941 /** Allocate the image buffer and set it on the frame.
944 static int allocate_buffer( mlt_properties frame_properties, AVCodecContext *codec_context, uint8_t **buffer, mlt_image_format *format, int *width, int *height )
948 if ( codec_context->width == 0 || codec_context->height == 0 )
951 *width = codec_context->width;
952 *height = codec_context->height;
954 if ( codec_context->pix_fmt == PIX_FMT_RGB32 )
955 size = *width * ( *height + 1 ) * 4;
956 else switch ( *format )
958 case mlt_image_yuv420p:
959 size = *width * 3 * ( *height + 1 ) / 2;
961 case mlt_image_rgb24:
962 size = *width * ( *height + 1 ) * 3;
964 case mlt_image_rgb24a:
965 case mlt_image_opengl:
966 size = *width * ( *height + 1 ) * 4;
969 *format = mlt_image_yuv422;
970 size = *width * ( *height + 1 ) * 2;
974 // Construct the output image
975 *buffer = mlt_pool_alloc( size );
977 mlt_properties_set_data( frame_properties, "image", *buffer, size, mlt_pool_release, NULL );
984 /** Get an image from a frame.
987 static int producer_get_image( mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable )
990 producer_avformat self = mlt_frame_pop_service( frame );
991 mlt_service_lock( MLT_PRODUCER_SERVICE(self->parent) );
992 mlt_producer producer = self->parent;
994 // Get the properties from the frame
995 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
997 // Obtain the frame number of this frame
998 mlt_position position = mlt_properties_get_position( frame_properties, "avformat_position" );
1000 // Get the producer properties
1001 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1003 // Fetch the video format context
1004 AVFormatContext *context = self->video_format;
1006 // Get the video stream
1007 AVStream *stream = context->streams[ self->video_index ];
1009 // Get codec context
1010 AVCodecContext *codec_context = stream->codec;
1012 // Get the image cache
1013 if ( ! self->image_cache && ! mlt_properties_get_int( properties, "noimagecache" ) )
1014 self->image_cache = mlt_cache_init();
1015 if ( self->image_cache )
1017 mlt_cache_item item = mlt_cache_get( self->image_cache, (void*) position );
1018 *buffer = mlt_cache_item_data( item, (int*) format );
1021 // Set the resolution
1022 *width = codec_context->width;
1023 *height = codec_context->height;
1025 // Workaround 1088 encodings missing cropping info.
1026 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1033 case mlt_image_yuv420p:
1034 size = *width * 3 * ( *height + 1 ) / 2;
1036 case mlt_image_rgb24:
1037 size = *width * ( *height + 1 ) * 3;
1039 case mlt_image_rgb24a:
1040 case mlt_image_opengl:
1041 size = *width * ( *height + 1 ) * 4;
1044 *format = mlt_image_yuv422;
1045 size = *width * ( *height + 1 ) * 2;
1048 mlt_properties_set_data( frame_properties, "avformat.image_cache", item, 0, ( mlt_destructor )mlt_cache_item_close, NULL );
1049 mlt_properties_set_data( frame_properties, "image", *buffer, size, NULL, NULL );
1050 // self->top_field_first = mlt_properties_get_int( frame_properties, "top_field_first" );
1051 self->got_picture = 1;
1053 goto exit_get_image;
1064 // Special case pause handling flag
1067 // Special case ffwd handling
1070 // We may want to use the source fps if available
1071 double source_fps = mlt_properties_get_double( properties, "meta.media.frame_rate_num" ) /
1072 mlt_properties_get_double( properties, "meta.media.frame_rate_den" );
1073 double fps = mlt_producer_get_fps( producer );
1075 // This is the physical frame position in the source
1076 int req_position = ( int )( position / fps * source_fps + 0.5 );
1078 // Determines if we have to decode all frames in a sequence
1079 // Temporary hack to improve intra frame only
1080 int must_decode = strcmp( codec_context->codec->name, "dnxhd" ) &&
1081 strcmp( codec_context->codec->name, "dvvideo" ) &&
1082 strcmp( codec_context->codec->name, "huffyuv" ) &&
1083 strcmp( codec_context->codec->name, "mjpeg" ) &&
1084 strcmp( codec_context->codec->name, "rawvideo" );
1086 int last_position = self->last_position;
1088 // Turn on usage of new seek API and PTS for seeking
1089 int use_new_seek = codec_context->codec_id == CODEC_ID_H264 && !strcmp( context->iformat->name, "mpegts" );
1090 if ( mlt_properties_get( properties, "new_seek" ) )
1091 use_new_seek = mlt_properties_get_int( properties, "new_seek" );
1093 // Seek if necessary
1094 if ( position != self->video_expected || last_position < 0 )
1096 if ( self->av_frame && position + 1 == self->video_expected )
1098 // We're paused - use last image
1101 else if ( !self->seekable && position > self->video_expected && ( position - self->video_expected ) < 250 )
1103 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1104 ignore = ( int )( ( position - self->video_expected ) / fps * source_fps );
1105 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1107 else if ( self->seekable && ( position < self->video_expected || position - self->video_expected >= 12 || last_position < 0 ) )
1109 if ( use_new_seek && last_position == POSITION_INITIAL )
1111 // find first key frame
1115 while ( ret >= 0 && toscan-- > 0 )
1117 ret = av_read_frame( context, &pkt );
1118 if ( ret >= 0 && ( pkt.flags & PKT_FLAG_KEY ) && pkt.stream_index == self->video_index )
1120 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "first_pts %lld dts %lld pts_dts_delta %d\n", pkt.pts, pkt.dts, (int)(pkt.pts - pkt.dts) );
1121 self->first_pts = pkt.pts;
1124 av_free_packet( &pkt );
1127 av_seek_frame( context, -1, 0, AVSEEK_FLAG_BACKWARD );
1130 // Calculate the timestamp for the requested frame
1134 timestamp = ( req_position - 0.1 / source_fps ) /
1135 ( av_q2d( stream->time_base ) * source_fps );
1136 mlt_log_verbose( MLT_PRODUCER_SERVICE(producer), "pos %d pts %lld ", req_position, timestamp );
1137 if ( self->first_pts > 0 )
1138 timestamp += self->first_pts;
1139 else if ( context->start_time != AV_NOPTS_VALUE )
1140 timestamp += context->start_time;
1144 timestamp = ( int64_t )( ( double )req_position / source_fps * AV_TIME_BASE + 0.5 );
1145 if ( context->start_time != AV_NOPTS_VALUE )
1146 timestamp += context->start_time;
1149 timestamp -= AV_TIME_BASE;
1150 if ( timestamp < 0 )
1152 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "seeking timestamp %lld position %d expected %d last_pos %d\n",
1153 timestamp, position, self->video_expected, last_position );
1155 // Seek to the timestamp
1158 codec_context->skip_loop_filter = AVDISCARD_NONREF;
1159 av_seek_frame( context, self->video_index, timestamp, AVSEEK_FLAG_BACKWARD );
1161 else if ( timestamp > 0 || last_position <= 0 )
1163 av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD );
1167 // Re-open video stream when rewinding to beginning from somewhere else.
1168 // This is rather ugly, and I prefer not to do it this way, but ffmpeg is
1169 // not reliably seeking to the first frame across formats.
1170 if ( self->video_codec )
1171 avcodec_close( self->video_codec );
1172 self->video_codec = NULL;
1173 if ( self->dummy_context )
1174 av_close_input_file( self->dummy_context );
1175 self->dummy_context = NULL;
1176 if ( self->video_format )
1177 av_close_input_file( self->video_format );
1178 self->video_format = NULL;
1180 producer_set_up_video( self, frame );
1181 if ( self->video_index < 0 )
1184 context = self->video_format;
1185 stream = context->streams[ self->video_index ];
1186 codec_context = stream->codec;
1189 // Remove the cached info relating to the previous position
1190 self->current_position = POSITION_INVALID;
1191 self->last_position = POSITION_INVALID;
1192 av_freep( &self->av_frame );
1196 // flush any pictures still in decode buffer
1197 avcodec_flush_buffers( codec_context );
1202 // Duplicate the last image if necessary
1203 if ( self->av_frame && self->av_frame->linesize[0] && self->got_picture && self->seekable
1205 || self->current_position == req_position
1206 || ( !use_new_seek && self->current_position > req_position ) ) )
1209 if ( ( image_size = allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) ) )
1211 // Workaround 1088 encodings missing cropping info.
1212 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1215 if ( self->vdpau && self->vdpau->buffer )
1218 picture.data[0] = self->vdpau->buffer;
1219 picture.data[2] = self->vdpau->buffer + codec_context->width * codec_context->height;
1220 picture.data[1] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1221 picture.linesize[0] = codec_context->width;
1222 picture.linesize[1] = codec_context->width / 2;
1223 picture.linesize[2] = codec_context->width / 2;
1224 convert_image( (AVFrame*) &picture, *buffer,
1225 PIX_FMT_YUV420P, format, *width, *height, self->colorspace );
1229 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1230 format, *width, *height, self->colorspace );
1233 mlt_frame_get_image( frame, buffer, format, width, height, writable );
1238 int int_position = 0;
1239 int decode_errors = 0;
1240 int got_picture = 0;
1242 av_init_packet( &pkt );
1244 // Construct an AVFrame for YUV422 conversion
1245 if ( !self->av_frame )
1246 self->av_frame = avcodec_alloc_frame( );
1248 while( ret >= 0 && !got_picture )
1251 ret = av_read_frame( context, &pkt );
1253 // We only deal with video from the selected video_index
1254 if ( ret >= 0 && pkt.stream_index == self->video_index && pkt.size > 0 )
1256 // Determine time code of the packet
1259 int64_t pts = pkt.pts;
1260 if ( self->first_pts > 0 )
1261 pts -= self->first_pts;
1262 else if ( context->start_time != AV_NOPTS_VALUE )
1263 pts -= context->start_time;
1264 int_position = ( int )( av_q2d( stream->time_base ) * pts * source_fps + 0.1 );
1265 if ( pkt.pts == AV_NOPTS_VALUE )
1267 self->invalid_pts_counter++;
1268 if ( self->invalid_pts_counter > 20 )
1270 mlt_log_panic( MLT_PRODUCER_SERVICE(producer), "\ainvalid PTS; DISABLING NEW_SEEK!\n" );
1271 mlt_properties_set_int( properties, "new_seek", 0 );
1272 int_position = req_position;
1278 self->invalid_pts_counter = 0;
1280 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.pts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1281 pkt.pts, req_position, self->current_position, int_position );
1285 if ( self->seekable && pkt.dts != AV_NOPTS_VALUE )
1287 int_position = ( int )( av_q2d( stream->time_base ) * pkt.dts * source_fps + 0.5 );
1288 if ( context->start_time != AV_NOPTS_VALUE )
1289 int_position -= ( int )( context->start_time * source_fps / AV_TIME_BASE + 0.5 );
1290 last_position = self->last_position;
1291 if ( int_position == last_position )
1292 int_position = last_position + 1;
1296 int_position = req_position;
1298 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "pkt.dts %llu req_pos %d cur_pos %d pkt_pos %d\n",
1299 pkt.dts, req_position, self->current_position, int_position );
1300 // Make a dumb assumption on streams that contain wild timestamps
1301 if ( abs( req_position - int_position ) > 999 )
1303 int_position = req_position;
1304 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " WILD TIMESTAMP!" );
1307 self->last_position = int_position;
1310 if ( must_decode || int_position >= req_position )
1313 if ( g_vdpau && self->vdpau )
1315 if ( g_vdpau->producer != self )
1317 vdpau_decoder_close();
1318 vdpau_decoder_init( self );
1321 self->vdpau->is_decoded = 0;
1324 codec_context->reordered_opaque = pkt.pts;
1325 if ( int_position >= req_position )
1326 codec_context->skip_loop_filter = AVDISCARD_NONE;
1327 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1328 ret = avcodec_decode_video2( codec_context, self->av_frame, &got_picture, &pkt );
1330 ret = avcodec_decode_video( codec_context, self->av_frame, &got_picture, pkt.data, pkt.size );
1332 // Note: decode may fail at the beginning of MPEGfile (B-frames referencing before first I-frame), so allow a few errors.
1335 if ( ++decode_errors <= 10 )
1348 // Determine time code of the packet
1349 int64_t pts = self->av_frame->reordered_opaque;
1350 if ( self->first_pts > 0 )
1351 pts -= self->first_pts;
1352 else if ( context->start_time != AV_NOPTS_VALUE )
1353 pts -= context->start_time;
1354 int_position = ( int )( av_q2d( stream->time_base) * pts * source_fps + 0.1 );
1355 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), "got frame %d, key %d\n", int_position, self->av_frame->key_frame );
1358 if ( int_position < req_position )
1363 else if ( int_position >= req_position )
1366 codec_context->skip_loop_filter = AVDISCARD_NONE;
1368 else if ( ignore -- )
1373 mlt_log_debug( MLT_PRODUCER_SERVICE(producer), " got_pic %d key %d\n", got_picture, pkt.flags & PKT_FLAG_KEY );
1376 // Now handle the picture if we have one
1379 if ( ( image_size = allocate_buffer( frame_properties, codec_context, buffer, format, width, height ) ) )
1381 // Workaround 1088 encodings missing cropping info.
1382 if ( *height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1387 if ( self->vdpau->is_decoded )
1389 struct vdpau_render_state *render = (struct vdpau_render_state*) self->av_frame->data[0];
1391 uint32_t pitches[3];
1392 VdpYCbCrFormat dest_format = VDP_YCBCR_FORMAT_YV12;
1394 if ( !self->vdpau->buffer )
1395 self->vdpau->buffer = mlt_pool_alloc( codec_context->width * codec_context->height * 3 / 2 );
1396 self->av_frame->data[0] = planes[0] = self->vdpau->buffer;
1397 self->av_frame->data[2] = planes[1] = self->vdpau->buffer + codec_context->width * codec_context->height;
1398 self->av_frame->data[1] = planes[2] = self->vdpau->buffer + codec_context->width * codec_context->height * 5 / 4;
1399 self->av_frame->linesize[0] = pitches[0] = codec_context->width;
1400 self->av_frame->linesize[1] = pitches[1] = codec_context->width / 2;
1401 self->av_frame->linesize[2] = pitches[2] = codec_context->width / 2;
1403 VdpStatus status = vdp_surface_get_bits( render->surface, dest_format, planes, pitches );
1404 if ( status == VDP_STATUS_OK )
1406 convert_image( self->av_frame, *buffer, PIX_FMT_YUV420P,
1407 format, *width, *height, self->colorspace );
1411 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU Error: %s\n", vdp_get_error_string( status ) );
1412 self->vdpau->is_decoded = 0;
1417 mlt_log_error( MLT_PRODUCER_SERVICE(producer), "VDPAU error in VdpDecoderRender\n" );
1423 convert_image( self->av_frame, *buffer, codec_context->pix_fmt,
1424 format, *width, *height, self->colorspace );
1425 self->top_field_first |= self->av_frame->top_field_first;
1426 self->current_position = int_position;
1427 self->got_picture = 1;
1435 av_free_packet( &pkt );
1441 if ( self->got_picture && image_size > 0 && self->image_cache )
1443 // Copy buffer to image cache
1444 uint8_t *image = mlt_pool_alloc( image_size );
1445 memcpy( image, *buffer, image_size );
1446 mlt_cache_put( self->image_cache, (void*) position, image, *format, mlt_pool_release );
1449 // Regardless of speed, we expect to get the next frame (cos we ain't too bright)
1450 self->video_expected = position + 1;
1453 // Set the progressive flag
1454 if ( mlt_properties_get( properties, "force_progressive" ) )
1455 mlt_properties_set_int( frame_properties, "progressive", !!mlt_properties_get_int( properties, "force_progressive" ) );
1456 else if ( self->av_frame )
1457 mlt_properties_set_int( frame_properties, "progressive", !self->av_frame->interlaced_frame );
1459 // Set the field order property for this frame
1460 if ( mlt_properties_get( properties, "force_tff" ) )
1461 mlt_properties_set_int( frame_properties, "top_field_first", !!mlt_properties_get_int( properties, "force_tff" ) );
1463 mlt_properties_set_int( frame_properties, "top_field_first", self->top_field_first );
1465 // Set immutable properties of the selected track's (or overridden) source attributes.
1466 mlt_properties_set_int( properties, "meta.media.top_field_first", self->top_field_first );
1467 mlt_properties_set_int( properties, "meta.media.progressive", mlt_properties_get_int( frame_properties, "progressive" ) );
1469 mlt_service_unlock( MLT_PRODUCER_SERVICE(self->parent) );
1471 return !self->got_picture;
1474 /** Process properties as AVOptions and apply to AV context obj
1477 static void apply_properties( void *obj, mlt_properties properties, int flags )
1480 int count = mlt_properties_count( properties );
1481 for ( i = 0; i < count; i++ )
1483 const char *opt_name = mlt_properties_get_name( properties, i );
1484 const AVOption *opt = av_find_opt( obj, opt_name, NULL, flags, flags );
1485 if ( opt_name && mlt_properties_get( properties, opt_name ) )
1488 #if LIBAVCODEC_VERSION_INT >= ((52<<16)+(7<<8)+0)
1489 av_set_string3( obj, opt_name, mlt_properties_get( properties, opt_name), 0, NULL );
1490 #elif LIBAVCODEC_VERSION_INT >= ((51<<16)+(59<<8)+0)
1491 av_set_string2( obj, opt_name, mlt_properties_get( properties, opt_name), 0 );
1493 av_set_string( obj, opt_name, mlt_properties_get( properties, opt_name) );
1499 /** Initialize the video codec context.
1502 static int video_codec_init( producer_avformat self, int index, mlt_properties properties )
1504 // Initialise the codec if necessary
1505 if ( !self->video_codec )
1507 // Get the video stream
1508 AVStream *stream = self->video_format->streams[ index ];
1510 // Get codec context
1511 AVCodecContext *codec_context = stream->codec;
1514 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
1516 if ( codec_context->codec_id == CODEC_ID_H264 )
1518 if ( ( codec = avcodec_find_decoder_by_name( "h264_vdpau" ) ) )
1520 if ( vdpau_init( self ) )
1522 self->video_codec = codec_context;
1523 if ( !vdpau_decoder_init( self ) )
1524 vdpau_decoder_close();
1528 codec = avcodec_find_decoder( codec_context->codec_id );
1532 // Initialise multi-threading
1533 int thread_count = mlt_properties_get_int( properties, "threads" );
1534 if ( thread_count == 0 && getenv( "MLT_AVFORMAT_THREADS" ) )
1535 thread_count = atoi( getenv( "MLT_AVFORMAT_THREADS" ) );
1536 if ( thread_count > 1 )
1538 avcodec_thread_init( codec_context, thread_count );
1539 codec_context->thread_count = thread_count;
1542 // If we don't have a codec and we can't initialise it, we can't do much more...
1544 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
1546 // Now store the codec with its destructor
1547 self->video_codec = codec_context;
1551 // Remember that we can't use this later
1552 self->video_index = -1;
1556 // Process properties as AVOptions
1557 apply_properties( codec_context, properties, AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
1559 // Reset some image properties
1560 mlt_properties_set_int( properties, "width", self->video_codec->width );
1561 mlt_properties_set_int( properties, "height", self->video_codec->height );
1562 // For DV, we'll just use the saved aspect ratio
1563 if ( codec_context->codec_id != CODEC_ID_DVVIDEO )
1564 get_aspect_ratio( properties, stream, self->video_codec, NULL );
1566 // Determine the fps first from the codec
1567 double source_fps = (double) self->video_codec->time_base.den /
1568 ( self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1570 if ( mlt_properties_get( properties, "force_fps" ) )
1572 source_fps = mlt_properties_get_double( properties, "force_fps" );
1573 stream->time_base = av_d2q( source_fps, 1024 );
1574 mlt_properties_set_int( properties, "meta.media.frame_rate_num", stream->time_base.num );
1575 mlt_properties_set_int( properties, "meta.media.frame_rate_den", stream->time_base.den );
1579 // If the muxer reports a frame rate different than the codec
1580 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1581 double muxer_fps = av_q2d( stream->avg_frame_rate );
1582 if ( muxer_fps == 0 ) muxer_fps = av_q2d( stream->r_frame_rate );
1584 double muxer_fps = av_q2d( stream->r_frame_rate );
1586 // Choose the lesser - the wrong tends to be off by some multiple of 10
1587 source_fps = FFMIN( source_fps, muxer_fps );
1588 if ( source_fps >= 1.0 && ( source_fps < muxer_fps || isnan( muxer_fps ) ) )
1590 mlt_properties_set_int( properties, "meta.media.frame_rate_num", self->video_codec->time_base.den );
1591 mlt_properties_set_int( properties, "meta.media.frame_rate_den", self->video_codec->time_base.num == 0 ? 1 : self->video_codec->time_base.num );
1593 else if ( muxer_fps > 0 )
1595 AVRational frame_rate = stream->r_frame_rate;
1596 // With my samples when r_frame_rate != 1000 but avg_frame_rate is valid,
1597 // avg_frame_rate gives some approximate value that does not well match the media.
1598 // Also, on my sample where r_frame_rate = 1000, using avg_frame_rate directly
1599 // results in some very choppy output, but some value slightly different works
1601 #if LIBAVFORMAT_VERSION_INT >= ((52<<16)+(42<<8)+0)
1602 if ( av_q2d( stream->r_frame_rate ) >= 1000 && av_q2d( stream->avg_frame_rate ) > 0 )
1603 frame_rate = av_d2q( av_q2d( stream->avg_frame_rate ), 1024 );
1605 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1606 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1610 source_fps = mlt_producer_get_fps( self->parent );
1611 AVRational frame_rate = av_d2q( source_fps, 255 );
1612 mlt_properties_set_int( properties, "meta.media.frame_rate_num", frame_rate.num );
1613 mlt_properties_set_int( properties, "meta.media.frame_rate_den", frame_rate.den );
1617 // source_fps is deprecated in favor of meta.media.frame_rate_num and .frame_rate_den
1618 if ( source_fps > 0 )
1619 mlt_properties_set_double( properties, "source_fps", source_fps );
1621 mlt_properties_set_double( properties, "source_fps", mlt_producer_get_fps( self->parent ) );
1623 // Set the YUV colorspace from override or detect
1624 self->colorspace = mlt_properties_get_int( properties, "force_colorspace" );
1625 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(28<<8)+0)
1626 if ( ! self->colorspace )
1628 switch ( self->video_codec->colorspace )
1630 case AVCOL_SPC_SMPTE240M:
1631 self->colorspace = 240;
1633 case AVCOL_SPC_BT470BG:
1634 case AVCOL_SPC_SMPTE170M:
1635 self->colorspace = 601;
1637 case AVCOL_SPC_BT709:
1638 self->colorspace = 709;
1641 // This is a heuristic Charles Poynton suggests in "Digital Video and HDTV"
1642 self->colorspace = self->video_codec->width * self->video_codec->height > 750000 ? 709 : 601;
1647 // Let apps get chosen colorspace
1648 mlt_properties_set_int( properties, "meta.media.colorspace", self->colorspace );
1650 return self->video_codec && self->video_index > -1;
1653 /** Set up video handling.
1656 static void producer_set_up_video( producer_avformat self, mlt_frame frame )
1659 mlt_producer producer = self->parent;
1661 // Get the properties
1662 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
1664 // Fetch the video format context
1665 AVFormatContext *context = self->video_format;
1667 // Get the video_index
1668 int index = mlt_properties_get_int( properties, "video_index" );
1670 // Reopen the file if necessary
1671 if ( !context && index > -1 )
1673 mlt_events_block( properties, producer );
1674 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
1675 mlt_properties_get( properties, "resource" ) );
1676 context = self->video_format;
1677 if ( self->dummy_context )
1680 av_close_input_file( self->dummy_context );
1683 self->dummy_context = NULL;
1684 mlt_events_unblock( properties, producer );
1685 if ( self->audio_format )
1686 get_audio_streams_info( self );
1688 // Process properties as AVOptions
1689 apply_properties( context, properties, AV_OPT_FLAG_DECODING_PARAM );
1692 // Exception handling for video_index
1693 if ( context && index >= (int) context->nb_streams )
1695 // Get the last video stream
1696 for ( index = context->nb_streams - 1;
1697 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO;
1699 mlt_properties_set_int( properties, "video_index", index );
1701 if ( context && index > -1 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_VIDEO )
1703 // Invalidate the video stream
1705 mlt_properties_set_int( properties, "video_index", index );
1708 // Update the video properties if the index changed
1709 if ( index != self->video_index )
1711 // Reset the video properties if the index changed
1712 self->video_index = index;
1713 if ( self->video_codec )
1716 avcodec_close( self->video_codec );
1719 self->video_codec = NULL;
1722 // Get the frame properties
1723 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
1726 if ( context && index > -1 && video_codec_init( self, index, properties ) )
1728 // Set the frame properties
1729 double force_aspect_ratio = mlt_properties_get_double( properties, "force_aspect_ratio" );
1730 double aspect_ratio = ( force_aspect_ratio > 0.0 ) ?
1731 force_aspect_ratio : mlt_properties_get_double( properties, "aspect_ratio" );
1733 // Set the width and height
1734 mlt_properties_set_int( frame_properties, "width", self->video_codec->width );
1735 mlt_properties_set_int( frame_properties, "height", self->video_codec->height );
1736 // real_width and real_height are deprecated in favor of meta.media.width and .height
1737 mlt_properties_set_int( properties, "meta.media.width", self->video_codec->width );
1738 mlt_properties_set_int( properties, "meta.media.height", self->video_codec->height );
1739 mlt_properties_set_int( frame_properties, "real_width", self->video_codec->width );
1740 mlt_properties_set_int( frame_properties, "real_height", self->video_codec->height );
1741 mlt_properties_set_double( frame_properties, "aspect_ratio", aspect_ratio );
1742 mlt_properties_set_int( frame_properties, "colorspace", self->colorspace );
1744 // Workaround 1088 encodings missing cropping info.
1745 if ( self->video_codec->height == 1088 && mlt_profile_dar( mlt_service_profile( MLT_PRODUCER_SERVICE( producer ) ) ) == 16.0/9.0 )
1747 mlt_properties_set_int( properties, "meta.media.height", 1080 );
1748 mlt_properties_set_int( frame_properties, "real_height", 1080 );
1751 // Add our image operation
1752 mlt_frame_push_service( frame, self );
1753 mlt_frame_push_get_image( frame, producer_get_image );
1757 // If something failed, use test card image
1758 mlt_properties_set_int( frame_properties, "test_image", 1 );
1762 static int seek_audio( producer_avformat self, mlt_position position, double timecode, int *ignore )
1766 // Seek if necessary
1767 if ( position != self->audio_expected )
1769 if ( position + 1 == self->audio_expected )
1771 // We're paused - silence required
1774 else if ( !self->seekable && position > self->audio_expected && ( position - self->audio_expected ) < 250 )
1776 // Fast forward - seeking is inefficient for small distances - just ignore following frames
1777 *ignore = position - self->audio_expected;
1779 else if ( position < self->audio_expected || position - self->audio_expected >= 12 )
1781 AVFormatContext *context = self->audio_format;
1782 int64_t timestamp = ( int64_t )( timecode * AV_TIME_BASE + 0.5 );
1783 if ( context->start_time != AV_NOPTS_VALUE )
1784 timestamp += context->start_time;
1785 if ( timestamp < 0 )
1788 // Set to the real timecode
1790 if ( av_seek_frame( context, -1, timestamp, AVSEEK_FLAG_BACKWARD ) != 0 )
1794 // Clear the usage in the audio buffer
1795 int i = MAX_AUDIO_STREAMS + 1;
1797 self->audio_used[i - 1] = 0;
1803 static int decode_audio( producer_avformat self, int *ignore, AVPacket pkt, int channels, int samples, double timecode, double fps )
1805 // Fetch the audio_format
1806 AVFormatContext *context = self->audio_format;
1808 // Get the current stream index
1809 int index = pkt.stream_index;
1811 // Get codec context
1812 AVCodecContext *codec_context = self->audio_codec[ index ];
1814 // Obtain the resample context if it exists (not always needed)
1815 ReSampleContext *resample = self->audio_resample[ index ];
1817 // Obtain the audio buffers
1818 int16_t *audio_buffer = self->audio_buffer[ index ];
1819 int16_t *decode_buffer = self->decode_buffer[ index ];
1821 int audio_used = self->audio_used[ index ];
1822 uint8_t *ptr = pkt.data;
1826 while ( ptr && ret >= 0 && len > 0 )
1828 int data_size = sizeof( int16_t ) * AVCODEC_MAX_AUDIO_FRAME_SIZE;
1831 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(26<<8)+0))
1832 ret = avcodec_decode_audio3( codec_context, decode_buffer, &data_size, &pkt );
1833 #elif (LIBAVCODEC_VERSION_INT >= ((51<<16)+(29<<8)+0))
1834 ret = avcodec_decode_audio2( codec_context, decode_buffer, &data_size, ptr, len );
1836 ret = avcodec_decode_audio( codec_context, decode_buffer, &data_size, ptr, len );
1840 mlt_log_warning( MLT_PRODUCER_SERVICE(self->parent), "audio decoding error %d\n", ret );
1844 pkt.size = len -= ret;
1845 pkt.data = ptr += ret;
1847 // If decoded successfully
1848 if ( data_size > 0 )
1850 // Figure out how many samples will be needed after resampling
1851 int convert_samples = data_size / codec_context->channels / ( av_get_bits_per_sample_format( codec_context->sample_fmt ) / 8 );
1852 int samples_needed = self->resample_factor * convert_samples + 1;
1854 // Resize audio buffer to prevent overflow
1855 if ( audio_used * channels + samples_needed > self->audio_buffer_size[ index ] )
1857 self->audio_buffer_size[ index ] *= 2;
1858 audio_buffer = self->audio_buffer[ index ] = mlt_pool_realloc( audio_buffer, self->audio_buffer_size[ index ] * sizeof(int16_t) );
1862 // Copy to audio buffer while resampling
1863 int16_t *source = decode_buffer;
1864 int16_t *dest = &audio_buffer[ audio_used * channels ];
1866 audio_used += audio_resample( resample, dest, source, convert_samples );
1871 // Straight copy to audio buffer
1872 memcpy( &audio_buffer[ audio_used * codec_context->channels ], decode_buffer, data_size );
1873 audio_used += convert_samples;
1877 while ( *ignore && audio_used > samples )
1880 audio_used -= samples;
1881 memmove( audio_buffer, &audio_buffer[ samples * (resample? channels : codec_context->channels) ],
1882 audio_used * sizeof( int16_t ) );
1887 // If we're behind, ignore this packet
1890 double current_pts = av_q2d( context->streams[ index ]->time_base ) * pkt.pts;
1891 int req_position = ( int )( timecode * fps + 0.5 );
1892 int int_position = ( int )( current_pts * fps + 0.5 );
1893 if ( context->start_time != AV_NOPTS_VALUE )
1894 int_position -= ( int )( fps * context->start_time / AV_TIME_BASE + 0.5 );
1896 if ( self->seekable && *ignore == 0 )
1898 if ( int_position < req_position )
1899 // We are behind, so skip some
1901 else if ( int_position > req_position + 2 )
1902 // We are ahead, so seek backwards some more
1903 seek_audio( self, req_position, timecode - 1.0, ignore );
1907 self->audio_used[ index ] = audio_used;
1912 /** Get the audio from a frame.
1915 static int producer_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples )
1918 producer_avformat self = mlt_frame_pop_audio( frame );
1920 mlt_service_lock( MLT_PRODUCER_SERVICE(self->parent) );
1922 // Obtain the frame number of this frame
1923 mlt_position position = mlt_properties_get_position( MLT_FRAME_PROPERTIES( frame ), "avformat_position" );
1925 // Calculate the real time code
1926 double real_timecode = producer_time_of_frame( self->parent, position );
1928 // Get the producer fps
1929 double fps = mlt_producer_get_fps( self->parent );
1931 // Number of frames to ignore (for ffwd)
1934 // Flag for paused (silence)
1935 int paused = seek_audio( self, position, real_timecode, &ignore );
1937 // Fetch the audio_format
1938 AVFormatContext *context = self->audio_format;
1940 // Determine the tracks to use
1941 int index = self->audio_index;
1942 int index_max = self->audio_index + 1;
1943 if ( self->audio_index == INT_MAX )
1946 index_max = context->nb_streams;
1947 *channels = self->total_channels;
1948 *frequency = self->max_frequency;
1951 // Initialize the resamplers and buffers
1952 for ( ; index < index_max; index++ )
1954 // Get codec context
1955 AVCodecContext *codec_context = self->audio_codec[ index ];
1957 if ( codec_context && !self->audio_buffer[ index ] )
1959 // Check for resample and create if necessary
1960 if ( codec_context->channels <= 2 )
1962 // Determine by how much resampling will increase number of samples
1963 double resample_factor = self->audio_index == INT_MAX ? 1 : (double) *channels / codec_context->channels;
1964 resample_factor *= (double) *frequency / codec_context->sample_rate;
1965 if ( resample_factor > self->resample_factor )
1966 self->resample_factor = resample_factor;
1968 // Create the resampler
1969 #if (LIBAVCODEC_VERSION_INT >= ((52<<16)+(15<<8)+0))
1970 self->audio_resample[ index ] = av_audio_resample_init(
1971 self->audio_index == INT_MAX ? codec_context->channels : *channels,
1972 codec_context->channels, *frequency, codec_context->sample_rate,
1973 SAMPLE_FMT_S16, codec_context->sample_fmt, 16, 10, 0, 0.8 );
1975 self->audio_resample[ index ] = audio_resample_init(
1976 self->audio_index == INT_MAX ? codec_context->channels : *channels,
1977 codec_context->channels, *frequency, codec_context->sample_rate );
1982 codec_context->request_channels = self->audio_index == INT_MAX ? codec_context->channels : *channels;
1985 // Check for audio buffer and create if necessary
1986 self->audio_buffer_size[ index ] = AVCODEC_MAX_AUDIO_FRAME_SIZE;
1987 self->audio_buffer[ index ] = mlt_pool_alloc( self->audio_buffer_size[ index ] * sizeof( int16_t ) );
1989 // Check for decoder buffer and create if necessary
1990 self->decode_buffer[ index ] = av_malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE * sizeof( int16_t ) );
1994 // Get the audio if required
2001 av_init_packet( &pkt );
2003 // If not resampling, give consumer more than requested.
2004 // It requested number samples based on requested frame rate.
2005 // Do not clean this up with a samples *= ...!
2006 if ( self->audio_index != INT_MAX && ! self->audio_resample[ self->audio_index ] )
2007 *samples = *samples * self->audio_codec[ self->audio_index ]->sample_rate / *frequency;
2009 while ( ret >= 0 && !got_audio )
2011 // Check if the buffer already contains the samples required
2012 if ( self->audio_index != INT_MAX && self->audio_used[ self->audio_index ] >= *samples && ignore == 0 )
2020 ret = av_read_frame( context, &pkt );
2023 // We only deal with audio from the selected audio index
2024 if ( ret >= 0 && pkt.data && pkt.size > 0 && ( pkt.stream_index == self->audio_index ||
2025 ( self->audio_index == INT_MAX && context->streams[ pkt.stream_index ]->codec->codec_type == CODEC_TYPE_AUDIO ) ) )
2027 int channels2 = self->audio_index == INT_MAX ? self->audio_codec[pkt.stream_index]->channels : *channels;
2028 ret = decode_audio( self, &ignore, pkt, channels2, *samples, real_timecode, fps );
2030 av_free_packet( &pkt );
2032 if ( self->audio_index == INT_MAX && ret >= 0 )
2034 // Determine if there is enough audio for all streams
2036 for ( index = 0; index < context->nb_streams; index++ )
2038 if ( self->audio_codec[ index ] && self->audio_used[ index ] < *samples )
2044 // Allocate and set the frame's audio buffer
2045 int size = *samples * *channels * sizeof(int16_t);
2046 *buffer = mlt_pool_alloc( size );
2047 *format = mlt_audio_s16;
2048 mlt_frame_set_audio( frame, *buffer, *format, size, mlt_pool_release );
2050 // Interleave tracks if audio_index=all
2051 if ( self->audio_index == INT_MAX )
2053 int16_t *dest = *buffer;
2055 for ( i = 0; i < *samples; i++ )
2057 for ( index = 0; index < index_max; index++ )
2058 if ( self->audio_codec[ index ] )
2060 int current_channels = self->audio_codec[ index ]->channels;
2061 int16_t *src = self->audio_buffer[ index ] + i * current_channels;
2062 memcpy( dest, src, current_channels * sizeof(int16_t) );
2063 dest += current_channels;
2066 for ( index = 0; index < index_max; index++ )
2067 if ( self->audio_codec[ index ] && self->audio_used[ index ] >= *samples )
2069 int current_channels = self->audio_codec[ index ]->channels;
2070 int16_t *src = self->audio_buffer[ index ] + *samples * current_channels;
2071 self->audio_used[index] -= *samples;
2072 memmove( self->audio_buffer[ index ], src, self->audio_used[ index ] * current_channels * sizeof(int16_t) );
2075 // Copy a single track to the output buffer
2078 index = self->audio_index;
2080 // Now handle the audio if we have enough
2081 if ( self->audio_used[ index ] > 0 )
2083 int16_t *src = self->audio_buffer[ index ];
2084 *samples = self->audio_used[ index ] < *samples ? self->audio_used[ index ] : *samples;
2085 memcpy( *buffer, src, *samples * *channels * sizeof(int16_t) );
2086 self->audio_used[ index ] -= *samples;
2087 memmove( src, &src[ *samples * *channels ], self->audio_used[ index ] * *channels * sizeof(int16_t) );
2091 // Otherwise fill with silence
2092 memset( *buffer, 0, *samples * *channels * sizeof(int16_t) );
2094 if ( !self->audio_resample[ index ] )
2096 // TODO: uncomment and remove following line when full multi-channel support is ready
2097 // *channels = codec_context->channels;
2098 *frequency = self->audio_codec[ index ]->sample_rate;
2104 // Get silence and don't touch the context
2105 mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples );
2108 // Regardless of speed (other than paused), we expect to get the next frame
2110 self->audio_expected = position + 1;
2112 mlt_service_unlock( MLT_PRODUCER_SERVICE(self->parent) );
2117 /** Initialize the audio codec context.
2120 static int audio_codec_init( producer_avformat self, int index, mlt_properties properties )
2122 // Initialise the codec if necessary
2123 if ( !self->audio_codec[ index ] )
2125 // Get codec context
2126 AVCodecContext *codec_context = self->audio_format->streams[index]->codec;
2129 AVCodec *codec = avcodec_find_decoder( codec_context->codec_id );
2131 // If we don't have a codec and we can't initialise it, we can't do much more...
2133 if ( codec && avcodec_open( codec_context, codec ) >= 0 )
2135 // Now store the codec with its destructor
2136 if ( self->audio_codec[ index ] )
2137 avcodec_close( self->audio_codec[ index ] );
2138 self->audio_codec[ index ] = codec_context;
2142 // Remember that we can't use self later
2143 self->audio_index = -1;
2147 // Process properties as AVOptions
2148 apply_properties( codec_context, properties, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM );
2150 return self->audio_codec[ index ] && self->audio_index > -1;
2153 /** Set up audio handling.
2156 static void producer_set_up_audio( producer_avformat self, mlt_frame frame )
2159 mlt_producer producer = self->parent;
2161 // Get the properties
2162 mlt_properties properties = MLT_PRODUCER_PROPERTIES( producer );
2164 // Fetch the audio format context
2165 AVFormatContext *context = self->audio_format;
2167 mlt_properties frame_properties = MLT_FRAME_PROPERTIES( frame );
2169 // Get the audio_index
2170 int index = mlt_properties_get_int( properties, "audio_index" );
2172 // Handle all audio tracks
2173 if ( self->audio_index > -1 &&
2174 mlt_properties_get( properties, "audio_index" ) &&
2175 !strcmp( mlt_properties_get( properties, "audio_index" ), "all" ) )
2178 // Reopen the file if necessary
2179 if ( !context && self->audio_index > -1 && index > -1 )
2181 mlt_events_block( properties, producer );
2182 producer_open( self, mlt_service_profile( MLT_PRODUCER_SERVICE(producer) ),
2183 mlt_properties_get( properties, "resource" ) );
2184 context = self->audio_format;
2185 if ( self->dummy_context )
2188 av_close_input_file( self->dummy_context );
2191 self->dummy_context = NULL;
2192 mlt_events_unblock( properties, producer );
2193 get_audio_streams_info( self );
2196 // Exception handling for audio_index
2197 if ( context && index >= (int) context->nb_streams && index < INT_MAX )
2199 for ( index = context->nb_streams - 1;
2200 index >= 0 && context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO;
2202 mlt_properties_set_int( properties, "audio_index", index );
2204 if ( context && index > -1 && index < INT_MAX &&
2205 context->streams[ index ]->codec->codec_type != CODEC_TYPE_AUDIO )
2207 index = self->audio_index;
2208 mlt_properties_set_int( properties, "audio_index", index );
2211 // Update the audio properties if the index changed
2212 if ( context && index > -1 && index != self->audio_index )
2214 if ( self->audio_codec[ self->audio_index ] )
2217 avcodec_close( self->audio_codec[ self->audio_index ] );
2220 self->audio_codec[ self->audio_index ] = NULL;
2222 if ( self->audio_index != -1 )
2223 self->audio_index = index;
2228 if ( context && index == INT_MAX )
2230 mlt_properties_set_int( frame_properties, "frequency", self->max_frequency );
2231 mlt_properties_set_int( frame_properties, "channels", self->total_channels );
2232 for ( index = 0; index < context->nb_streams; index++ )
2234 if ( context->streams[ index ]->codec->codec_type == CODEC_TYPE_AUDIO )
2235 audio_codec_init( self, index, properties );
2238 else if ( context && index > -1 && audio_codec_init( self, index, properties ) )
2240 // Set the frame properties
2241 if ( index < INT_MAX )
2243 mlt_properties_set_int( frame_properties, "frequency", self->audio_codec[ index ]->sample_rate );
2244 mlt_properties_set_int( frame_properties, "channels", self->audio_codec[ index ]->channels );
2247 if ( context && index > -1 )
2249 // Add our audio operation
2250 mlt_frame_push_audio( frame, self );
2251 mlt_frame_push_audio( frame, producer_get_audio );
2255 /** Our get frame implementation.
2258 static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
2260 // Access the private data
2261 mlt_service service = MLT_PRODUCER_SERVICE( producer );
2262 mlt_cache_item cache_item = mlt_service_cache_get( service, "producer_avformat" );
2263 producer_avformat self = mlt_cache_item_data( cache_item, NULL );
2268 self = calloc( 1, sizeof( struct producer_avformat_s ) );
2269 producer->child = self;
2270 self->parent = producer;
2271 mlt_service_cache_put( service, "producer_avformat", self, 0, (mlt_destructor) producer_avformat_close );
2272 cache_item = mlt_service_cache_get( service, "producer_avformat" );
2275 // Create an empty frame
2276 *frame = mlt_frame_init( service);
2280 mlt_properties_set_data( MLT_FRAME_PROPERTIES(*frame), "avformat_cache", cache_item, 0, (mlt_destructor) mlt_cache_item_close, NULL );
2284 mlt_cache_item_close( cache_item );
2288 // Update timecode on the frame we're creating
2289 mlt_frame_set_position( *frame, mlt_producer_position( producer ) );
2291 // Set the position of this producer
2292 mlt_properties_set_position( MLT_FRAME_PROPERTIES( *frame ), "avformat_position", mlt_producer_frame( producer ) );
2295 producer_set_up_video( self, *frame );
2298 producer_set_up_audio( self, *frame );
2300 // Calculate the next timecode
2301 mlt_producer_prepare_next( producer );
2306 static void producer_avformat_close( producer_avformat self )
2308 mlt_log_debug( NULL, "producer_avformat_close\n" );
2310 av_free( self->av_frame );
2313 for ( i = 0; i < MAX_AUDIO_STREAMS; i++ )
2315 if ( self->audio_resample[i] )
2316 audio_resample_close( self->audio_resample[i] );
2317 mlt_pool_release( self->audio_buffer[i] );
2318 av_free( self->decode_buffer[i] );
2319 if ( self->audio_codec[i] )
2320 avcodec_close( self->audio_codec[i] );
2322 if ( self->video_codec )
2323 avcodec_close( self->video_codec );
2324 if ( self->dummy_context )
2325 av_close_input_file( self->dummy_context );
2326 if ( self->audio_format )
2327 av_close_input_file( self->audio_format );
2328 if ( self->video_format )
2329 av_close_input_file( self->video_format );
2332 vdpau_producer_close( self );
2334 if ( self->image_cache )
2335 mlt_cache_close( self->image_cache );
2339 static void producer_close( mlt_producer parent )
2342 parent->close = NULL;
2343 mlt_producer_close( parent );