我正在使用AVVideoComposition
来为视频应用过滤器。它工作正常,但生成视频需要很长时间。另一方面,我注意到在不应用过滤器的情况下导出视频非常快,所以我知道应用过滤器的过程就是问题所在。
这是我用来将过滤器添加到视频中的一些代码:
此代码生成视频的合成。
public func generateComposition() -> AVVideoComposition {
let composition = AVVideoComposition(asset: asset) {
request in
let source = request.sourceImage.clampingToExtent()
self.zoomBlurFilter.setValue(source, forKey: kCIInputImageKey)
let currentTime = CMTimeGetSeconds(request.compositionTime)
let totalTime = CMTimeGetSeconds(self.asset.duration)
let timePercentage = currentTime/totalTime
self.zoomBlurFilter.setValue(timePercentage * Float64(self.blurAmount), forKey: "inputAmount")
let imageCenter = self.centerOfFirstFace(for: request.sourceImage) ?? CIVector(x: request.sourceImage.extent.midX, y: request.sourceImage.extent.midY)
self.zoomBlurFilter.setValue(imageCenter, forKey: "inputCenter")
guard let blurFilterOutput = self.zoomBlurFilter.outputImage else { request.finish(with: self.compositionError); return }
self.vignetteFilter.setValue(blurFilterOutput, forKey: kCIInputImageKey)
guard let vignetteFilterOutput = self.vignetteFilter.outputImage?.cropping(to: request.sourceImage.extent) else { request.finish(with: self.compositionError); return }
request.finish(with: vignetteFilterOutput, context: self.context)
}
return composition
}
此代码将视频导出到输出文件。
public func exportFilteredVideo(to outputURL: URL, completion: @escaping (Void) -> Void) {
if FileManager.default.fileExists(atPath: outputURL.path) {
try? FileManager.default.removeItem(at: outputURL)
}
let export = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetMediumQuality)!
export.outputFileType = AVFileTypeQuickTimeMovie
export.outputURL = outputURL
export.videoComposition = generateComposition() // Commenting out this line makes it go very fast, but obviously there is no filter if I comment this line out.
export.exportAsynchronously(completionHandler: completion)
}
以下是我正在使用的背景信息:
let context = CIContext(options: [kCIContextCacheIntermediates: false])
为了最大限度地提高CIFilters
的速度和性能,我是否应采取任何措施?视频本身只有三秒钟,所以我认为不应该花这么长时间:(。