AVVideoComposition 应用过滤器处理程序不调用

AVVideoComposition applying filter handler not call

我想在视频中添加叠加图像。我使用 AVVideoComposition 和 CIFilter 来执行此操作,但未调用 AVAsynchronousCIImageFilteringRequest 处理程序。 我放置了一些断点(行 debugPrint"Here"、request.finish),但是 XCode 没有命中断点。

我收到了视频,但是没有水印。

func watermark(video asset: AVAsset, with image: UIImage, output outURL: URL) {
        guard let watermarkImage = CIImage(image: image) else {
            return
        }

        let context = CIContext(options: nil)

        let videoComposition = AVVideoComposition(asset: asset) { (request) in
            debugPrint("Here")
            let source = request.sourceImage.clampedToExtent()

            let watermarkFilter = CIFilter(name: "CISourceOverCompositing")

            watermarkFilter?.setValue(source, forKey: kCIInputBackgroundImageKey)

            let transform = CGAffineTransform(translationX: request.sourceImage.extent.width - watermarkImage.extent.width - 10, y: 10)
            watermarkFilter?.setValue(watermarkImage.transformed(by: transform), forKey: kCIInputImageKey)
            guard let outputImage = watermarkFilter?.outputImage else {
                return
            }

            request.finish(with: outputImage, context: context)
        }

        let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough)
        exporter?.outputFileType = .mov
        exporter?.outputURL = outURL
        exporter?.videoComposition = videoComposition
        exporter?.exportAsynchronously { [weak exporter] in
            guard let export = exporter else {
                return
            }

            switch export.status {
            case  .failed:
                print("failed \(exporter?.error)")
                break
            case .cancelled:
                print("cancelled \(exporter?.error)")
                break
            case .completed:
                print("complete")
            default:
                print("default")
            }
        }
    }

在一些帮助下,我想通了,我使用了预设的 AVAssetExportPresetPassthrough,AVAssetExportSession 忽略了过滤器。我更改了预设,现在可以使用了。

您不应使用带 CI 过滤的直通预设。请尝试使用另一个定义视频格式的预设。

This docs 没有具体提到 CI 过滤,但它指出使用 passthrough 预设会导致图层指令被忽略。我希望 CI 过滤是一样的。

Important: If you export a video composition with an AVAssetExportSession object and specify the AVAssetExportPresetPassthrough export preset to let all tracks pass through, the transform defined in the video composition instruction (AVMutableVideoCompositionLayerInstruction) will not be applied. You must change the export preset to one that defines a video format (AVAssetExportPresetMediumQuality, for example) for the transform to be applied.