AVFoundation是一個(gè)對(duì)多媒體操作的庫(kù)。多媒體一般以文件或者流的形式存在,顯而易見,直接對(duì)多媒體進(jìn)行操作并不是一件愉快的事,這需要我們了解很多底層多媒體方面的知識(shí)。AVFoundation為我們提供了一個(gè)多媒體的載體類:AVAsset,在AVAsset中有著統(tǒng)一并且友好的接口,我們不需要了解太多多媒體的知識(shí)(當(dāng)然還是需要了解一些的),就能對(duì)其進(jìn)行操作。
基本屬性
我們將描述視頻基本信息的屬性稱為基本屬性。AVAsset的屬性從根本上來說是多媒體文件(如視頻文件)的屬性,我們先來看看多媒體文件中有哪些屬性。用十六進(jìn)制編輯器打開一個(gè)視頻文件是最完整的查看視頻中信息的方法,不過這樣并不利于我們的閱讀,因?yàn)閿?shù)據(jù)太多了。apple提供了一個(gè)很好的查看視頻信息的工具Atom Inspector,它會(huì)將十六進(jìn)制的數(shù)據(jù)歸類,并提取出其中有用的信息,即有利于查閱信息,也可以很方便的查看視頻完整的16進(jìn)制,了解視頻的結(jié)構(gòu)。
用Atom Inspector打開一個(gè)視頻文件。
我們可以看到在moov的目錄下有一個(gè)mvhd,mvhd也稱為movie header,它是整個(gè)視頻的描述部分,里面包含著視頻的基本信息,如時(shí)長(zhǎng),創(chuàng)建時(shí)間等。這些信息就是視頻文件的基本屬性,他們對(duì)應(yīng)到AVAsset中有:
// Indicates the duration of the asset. If @"providesPreciseDurationAndTiming" is NO, a best-available estimate of the duration is returned. The degree of precision preferred for timing-related properties can be set at initialization time for assets initialized with URLs. See AVURLAssetPreferPreciseDurationAndTimingKey for AVURLAsset below.
@property (nonatomic, readonly) CMTime duration;
// indicates the natural rate at which the asset is to be played; often but not always 1.0
@property (nonatomic, readonly) float preferredRate;
// indicates the preferred volume at which the audible media of an asset is to be played; often but not always 1.0
@property (nonatomic, readonly) float preferredVolume;
// Indicates the creation date of the asset as an AVMetadataItem. May be nil. If a creation date has been stored by the asset in a form that can be converted to an NSDate, the dateValue property of the AVMetadataItem will provide an instance of NSDate. Otherwise the creation date is available only as a string value, via -[AVMetadataItem stringValue].
@property (nonatomic, readonly, nullable) AVMetadataItem *creationDate NS_AVAILABLE(10_8, 5_0);
首先duration
屬性是CMTime類型,CMTime是一個(gè)結(jié)構(gòu)體
typedef struct
{
CMTimeValue value; // @field value The value of the CMTime. value/timescale = seconds.
CMTimeScale timescale; // @field timescale The timescale of the CMTime. value/timescale = seconds.
CMTimeFlags flags; // @field flags The flags, eg. kCMTimeFlags_Valid, kCMTimeFlags_PositiveInfinity, etc.
CMTimeEpoch epoch; // @field epoch Differentiates between equal timestamps that are actually different because of looping, multi-item sequencing, etc. Will be used during comparison: greater epochs happen after lesser ones. Additions/subtraction is only possible within a single epoch, however, since epoch length may be unknown/variable.
} CMTime;
它既包含了value,又包含了timescale,所以duration
屬性由視頻中的duration和timescale共同組成。
一般QuickTime和MPEG-4格式的mvhd中都有duration和timescale字段。不過其他格式可能不存在這2個(gè)字段,這時(shí)duration的值就需要通過計(jì)算才能得出。
如果創(chuàng)建AVURLAsset時(shí)傳入的AVURLAssetPreferPreciseDurationAndTimingKey
值為NO(不傳默認(rèn)為NO),duration會(huì)取一個(gè)估計(jì)值,計(jì)算量比較小。反之如果為YES,duration需要返回一個(gè)精確值,計(jì)算量會(huì)比較大,耗時(shí)比較長(zhǎng)。
preferredRate
和preferredVolume
屬性分別表示視頻默認(rèn)的速度和音量,這兩個(gè)屬性直接從mvhd中取出來即可,一般情況下,他們的都是1。
creationDate
屬性表示視頻的創(chuàng)建時(shí)間,對(duì)應(yīng)著mvhd中的created。如果mvhd中沒有創(chuàng)建時(shí)間,creationDate會(huì)返回nil。
AVAssetTrack
在mvhd下面,我們可以看到有3個(gè)軌道(track),一般的視頻至少有2個(gè)軌道,一個(gè)播放聲音,一個(gè)播放畫面。AVFoundation中有一個(gè)專門的類承載多媒體中的track:AVAssetTrack。
打開Atom Inspector中的track,我們可以看到,track中有一個(gè)tkhd(track header),其中包含了track的基本信息:
跟mvhd類似,tkhd中包含了duration,rate,volume,created,除此之外,tkhd中還有一個(gè)很重要的字段:track id,這是視頻中track的唯一標(biāo)示符。在AVAsset中,可以通過trackId,獲得特定的track
/* Provides an instance of AVAssetTrack that represents the track of the specified trackID. */
- (nullable AVAssetTrack *)trackWithTrackID:(CMPersistentTrackID)trackID;
除了通過trackID獲得track之外,AVAsset中還提供了其他3中方式獲得track
// Provides the array of AVAssetTracks contained by the asset
@property (nonatomic, readonly) NSArray<AVAssetTrack *> *tracks;
// Provides an array of AVAssetTracks of the asset that present media of the specified media type.
- (NSArray<AVAssetTrack *> *)tracksWithMediaType:(NSString *)mediaType;
// Provides an array of AVAssetTracks of the asset that present media with the specified characteristic.
- (NSArray<AVAssetTrack *> *)tracksWithMediaCharacteristic:(NSString *)mediaCharacteristic;
tracks
中包含了當(dāng)前Asset中的所有track,通過遍歷我們可以獲得想要的track.
-tracksWithMediaType:
方法會(huì)根據(jù)指定的媒體類型返回一個(gè)track數(shù)組,數(shù)組中包含著Asset中所有指定媒體類型的track。如果Asset中沒有這個(gè)媒體類型的track,返回一個(gè)空數(shù)組。AVMediaFormat中一共定義了8種媒體類型:
AVF_EXPORT NSString *const AVMediaTypeVideo NS_AVAILABLE(10_7, 4_0);
AVF_EXPORT NSString *const AVMediaTypeAudio NS_AVAILABLE(10_7, 4_0);
AVF_EXPORT NSString *const AVMediaTypeText NS_AVAILABLE(10_7, 4_0);
AVF_EXPORT NSString *const AVMediaTypeClosedCaption NS_AVAILABLE(10_7, 4_0);
AVF_EXPORT NSString *const AVMediaTypeSubtitle NS_AVAILABLE(10_7, 4_0);
AVF_EXPORT NSString *const AVMediaTypeTimecode NS_AVAILABLE(10_7, 4_0);
AVF_EXPORT NSString *const AVMediaTypeMetadata NS_AVAILABLE(10_8, 6_0);
AVF_EXPORT NSString *const AVMediaTypeMuxed NS_AVAILABLE(10_7, 4_0);
-tracksWithMediaCharacteristic:
方法會(huì)根據(jù)指定的媒體特征返回track數(shù)組,數(shù)組的特性與-tracksWithMediaType:類似,如果Asset中沒有這個(gè)媒體特征的track,返回一個(gè)空數(shù)組。AVMediaFormat中一共定義了15種媒體特征:
AVF_EXPORT NSString *const AVMediaTypeMetadataObject NS_AVAILABLE_IOS(9_0);
AVF_EXPORT NSString *const AVMediaCharacteristicVisual NS_AVAILABLE(10_7, 4_0);
AVF_EXPORT NSString *const AVMediaCharacteristicAudible NS_AVAILABLE(10_7, 4_0);
AVF_EXPORT NSString *const AVMediaCharacteristicLegible NS_AVAILABLE(10_7, 4_0);
AVF_EXPORT NSString *const AVMediaCharacteristicFrameBased NS_AVAILABLE(10_7, 4_0);
AVF_EXPORT NSString *const AVMediaCharacteristicIsMainProgramContent NS_AVAILABLE(10_8, 5_0);
AVF_EXPORT NSString *const AVMediaCharacteristicIsAuxiliaryContent NS_AVAILABLE(10_8, 5_0);
AVF_EXPORT NSString *const AVMediaCharacteristicContainsOnlyForcedSubtitles NS_AVAILABLE(10_8, 5_0);
AVF_EXPORT NSString *const AVMediaCharacteristicTranscribesSpokenDialogForAccessibility NS_AVAILABLE(10_8, 5_0);
AVF_EXPORT NSString *const AVMediaCharacteristicDescribesMusicAndSoundForAccessibility NS_AVAILABLE(10_8, 5_0);
AVF_EXPORT NSString *const AVMediaCharacteristicEasyToRead NS_AVAILABLE(10_8, 6_0);
AVF_EXPORT NSString *const AVMediaCharacteristicDescribesVideoForAccessibility NS_AVAILABLE(10_8, 5_0);
AVF_EXPORT NSString *const AVMediaCharacteristicLanguageTranslation NS_AVAILABLE(10_11, 9_0);
AVF_EXPORT NSString *const AVMediaCharacteristicDubbedTranslation NS_AVAILABLE(10_11, 9_0);
AVF_EXPORT NSString *const AVMediaCharacteristicVoiceOverTranslation NS_AVAILABLE(10_11, 9_0);
元數(shù)據(jù)
再往下看有一個(gè)meta(meta data)和udta(user data),里面都保存著視頻的元數(shù)據(jù),不過由于這個(gè)視頻沒有元數(shù)據(jù),可能是因?yàn)閲?guó)內(nèi)正版視頻不好找的原因,我找了幾個(gè)其他的視頻也沒找到元數(shù)據(jù)。所以暫且使用AV Foundation開發(fā)秘籍中的圖片。
用Atom Inspector打開《超人總動(dòng)員》mov格式的視頻,可以看到視頻的結(jié)構(gòu):
在udta中我們可以看到版權(quán)(@cpy)持有者為Pixar公司,導(dǎo)演(@dir)是Brad Bird,另外在meta->ilst中電影的名字是the Incredibles,年份是2006年,類型是Kids & Family。這些數(shù)據(jù)都會(huì)存放在AVAsset的metadata中
/* Provides access to an array of AVMetadataItems for each common metadata key for which a value is available; items can be filtered according to language via +[AVMetadataItem metadataItemsFromArray:filteredAndSortedAccordingToPreferredLanguages:] and according to identifier via +[AVMetadataItem metadataItemsFromArray:filteredByIdentifier:]. */
@property (nonatomic, readonly) NSArray<AVMetadataItem *> *commonMetadata;
// Provides access to an array of AVMetadataItems for all metadata identifiers for which a value is available; items can be filtered according to language via +[AVMetadataItem metadataItemsFromArray:filteredAndSortedAccordingToPreferredLanguages:] and according to identifier via +[AVMetadataItem metadataItemsFromArray:filteredByIdentifier:].
@property (nonatomic, readonly) NSArray<AVMetadataItem *> *metadata NS_AVAILABLE(10_10, 8_0);
// Provides an NSArray of NSStrings, each representing a metadata format that's available to the asset (e.g. ID3, iTunes metadata, etc.). Metadata formats are defined in AVMetadataFormat.h.
@property (nonatomic, readonly) NSArray<NSString *> *availableMetadataFormats;
commonMetadata
屬性中包含著當(dāng)前視頻常見格式類型的元數(shù)據(jù)
metadata
屬性中包含當(dāng)前視頻所有格式類型的元數(shù)據(jù)
availableMetadataFormats
屬性中包含當(dāng)前視頻所有可用元數(shù)據(jù)的格式類型
元數(shù)據(jù)的格式類型在AVMetadataFormat中定義了很多種,常見的有title、creator、subject、publisher等
// Metadata common keys
AVF_EXPORT NSString *const AVMetadataCommonKeyTitle NS_AVAILABLE(10_7, 4_0);
AVF_EXPORT NSString *const AVMetadataCommonKeyCreator NS_AVAILABLE(10_7, 4_0);
AVF_EXPORT NSString *const AVMetadataCommonKeySubject NS_AVAILABLE(10_7, 4_0);
AVF_EXPORT NSString *const AVMetadataCommonKeyPublisher NS_AVAILABLE(10_7, 4_0);
以上只是部分format,要了解更多,可以在apple文檔中查閱
有了metadataFormat,apple提供了通過fromat獲取特定格式類型元數(shù)據(jù)的方法:
- (NSArray<AVMetadataItem *> *)metadataForFormat:(NSString *)format;
章節(jié)元數(shù)據(jù)
Asset中有一種特殊的元數(shù)據(jù):章節(jié)。它是AVTimedMetadataGroup
類型,這種類型表示一個(gè)只在特定時(shí)間段有效的元數(shù)據(jù)集合,也就是說章節(jié)中所包含的元數(shù)據(jù)只在當(dāng)前章節(jié)的時(shí)間段有效。AVAsset中有3個(gè)章節(jié)相關(guān)的API:
// The locales available for chapters in the asset.
@property (readonly) NSArray<NSLocale *> *availableChapterLocales NS_AVAILABLE(10_7, 4_3);
// Returns an array of chapters with a given title locale and containing specified keys.
- (NSArray<AVTimedMetadataGroup *> *)chapterMetadataGroupsWithTitleLocale:(NSLocale *)locale containingItemsWithCommonKeys:(nullable NSArray<NSString *> *)commonKeys NS_AVAILABLE(10_7, 4_3);
// Returns an array of chapters whose locale best matches the the list of preferred languages.
- (NSArray<AVTimedMetadataGroup *> *)chapterMetadataGroupsBestMatchingPreferredLanguages:(NSArray<NSString *> *)preferredLanguages NS_AVAILABLE(10_8, 6_0);
availableChapterLocales
屬性表示當(dāng)前Asset中可用的章節(jié)Locale(感覺翻譯成地域或者區(qū)域在這里都很別扭,所以還是用英文)。數(shù)組類型,里面包含NSLocale對(duì)象
-chapterMetadataGroupsWithTitleLocale:containingItemsWithCommonKeys:
方法通過locale和元數(shù)據(jù)的commonkey篩選出特定的元數(shù)據(jù),這些元數(shù)據(jù)只在當(dāng)前章節(jié)的時(shí)間段有效。
-chapterMetadataGroupsBestMatchingPreferredLanguages:
方法通過指定一種語(yǔ)言,返回一個(gè)章節(jié)元數(shù)據(jù)數(shù)組。數(shù)組中越匹配指定語(yǔ)言的元數(shù)據(jù),位置越靠前。
媒體選擇
一個(gè)多媒體文件中相同的媒體特征的東西可能會(huì)有很多,比如一個(gè)視頻中可能會(huì)有2種字幕。對(duì)于類似選擇哪個(gè)字幕的問題,Asset提供了3個(gè)API:
// Provides an NSArray of NSStrings, each NSString indicating a media characteristic for which a media selection option is available.
@property (nonatomic, readonly) NSArray<NSString *> *availableMediaCharacteristicsWithMediaSelectionOptions NS_AVAILABLE(10_8, 5_0);
// Provides an instance of AVMediaSelectionGroup that contains one or more options with the specified media characteristic.
- (nullable AVMediaSelectionGroup *)mediaSelectionGroupForMediaCharacteristic:(NSString *)mediaCharacteristic NS_AVAILABLE(10_8, 5_0);
// Provides an instance of AVMediaSelection with default selections for each of the receiver's media selection groups.
@property (nonatomic, readonly) AVMediaSelection *preferredMediaSelection NS_AVAILABLE(10_11, 9_0);
availableMediaCharacteristicsWithMediaSelectionOptions
屬性表示當(dāng)前asset中有效的媒體特征選項(xiàng)。數(shù)組類型,里面包含著代表相應(yīng)媒體特征的string.
-mediaSelectionGroupForMediaCharacteristic:
方法通過傳入一個(gè)媒體特征類型,返回可供選擇的媒體選項(xiàng)集合。例如傳入字幕的媒體特征類型,返回當(dāng)前Asset的可供選擇的字幕選項(xiàng)集合。
preferredMediaSelection
屬性是AVMediaSelection類型,他的作用是主要是為各個(gè)媒體選項(xiàng)集合提供默認(rèn)選項(xiàng)。
這里的屬性都不是直接的基本屬性,可能不是那么容易理解。下面舉個(gè)簡(jiǎn)單的例子,以便于理解。打印出當(dāng)前Asset中默認(rèn)的媒體選項(xiàng)。
for (NSString *characteristic in asset.availableMediaCharacteristicsWithMediaSelectionOptions) {
AVMediaSelectionGroup *group = [asset mediaSelectionGroupForMediaCharacteristic:characteristic];
AVMediaSelectionOption *option = [asset.preferredMediaSelection selectedMediaOptionInMediaSelectionGroup:group];
NSLog(@"對(duì)應(yīng)媒體特征%@的默認(rèn)媒體選項(xiàng)是%@",characteristic,option);
}
懶惰加載
由于多媒體文件一般比較大,獲取或計(jì)算出Asset中的屬性非常耗時(shí),apple對(duì)Asset的屬性采用了懶惰加載模式。在創(chuàng)建AVAsset的時(shí)候,只生成一個(gè)實(shí)例,并不初始化屬性。只有當(dāng)?shù)谝淮卧L問屬性時(shí),系統(tǒng)才會(huì)根據(jù)多媒體中的數(shù)據(jù)初始化這個(gè)屬性。
由于不用同時(shí)加載所有屬性,耗時(shí)問題得到了一定緩解。但是屬性加載在計(jì)算量比較大的時(shí)候仍舊可能會(huì)阻塞線程。為了解決這個(gè)問題,AVFoundation提供了AVAsynchronousKeyValueLoading協(xié)議,可以異步加載屬性:
@protocol AVAsynchronousKeyValueLoading
@required
// Directs the target to load the values of any of the specified keys that are not already loaded.
- (void)loadValuesAsynchronouslyForKeys:(NSArray<NSString *> *)keys completionHandler:(nullable void (^)(void))handler;
// Reports whether the value for a key is immediately available without blocking.
- (AVKeyValueStatus)statusOfValueForKey:(NSString *)key error:(NSError * __nullable * __nullable)outError;
-loadValuesAsynchronouslyForKeys:completionHandler:方法用來異步加載屬性,通過keys傳入要加載的key數(shù)組,在handler中做加載完成的操作。
-statusOfValueForKey:error:方法可以獲得屬性的加載狀態(tài),如果是AVKeyValueStatusLoaded狀態(tài),表示已經(jīng)加載完成。
除此之外,Asset也提供了取消加載的API:
// Cancels the loading of all values for all observers.
- (void)cancelLoading;
當(dāng)需要的時(shí)候我們可以通過這個(gè)API終止加載屬性。另外在AVAsset釋放的時(shí)候會(huì)暗中取消所有的加載請(qǐng)求。
End
除了已經(jīng)介紹的API之外,還有一些BOOL值類型的標(biāo)識(shí)屬性,這些屬性都比較簡(jiǎn)單,根據(jù)名字就能明白其中的意思。這里就不多介紹了。
最近剛開始研究AVFoundation,可能是玩這個(gè)的人不多,網(wǎng)上這方面的資料比較少,所以將最近研究的結(jié)果寫成博客,以供大家參考,如果有什么不對(duì)的地方,希望能多多指教
如果你也正在學(xué)習(xí)AVFoundation,可以關(guān)注我的微博,大家互相學(xué)習(xí),共同進(jìn)步
Reference
MP4文件格式詳解——元數(shù)據(jù)moov
AV Foundation開發(fā)秘籍
AVAsset Class Reference