ios - Swift:来自调试器的消息:由于内存问题而终止

标签 ios swift cifilter avasset avvideocomposition

这个问题与Ios Xcode Message from debugger: Terminated due to memory issue中的不同.我正在使用不同的设备,我的应用程序在前台被杀死,除此之外我无法使用 Instruments 查看分配情况。

我正在尝试将许多 AVAssets 的短间隔合并到一个视频文件中。我需要对它们应用额外的过滤器和转换。

我实现了类,它可以采用一种 Assets 并完全按照我想要的方式制作所有内容,但是现在,当我尝试对许多 Assets (cca 7 aasets 仍然可以)做同样的事情时,较短的 Assets (完整持续时间可能会更短然后使用一项 Assets ),应用程序崩溃,我只收到“来自调试器的消息:由于内存问题而终止”日志。

我无法使用大多数 Instruments 工具,因为应用程序会立即崩溃。我尝试了很多方法来解决它,但我没有成功,我真的很感激一些帮助。

谢谢

相关代码片段在这里:

构图的创建:

func export(toURL url: URL, callback: @escaping (_ url: URL?) -> Void){
    var lastTime = kCMTimeZero
    var instructions : [VideoFilterCompositionInstruction] = []
    let composition = AVMutableComposition()
    composition.naturalSize = CGSize(width: 1080, height: 1920)

    for (index, assetURL) in assets.enumerated() {
        let asset : AVURLAsset? = AVURLAsset(url: assetURL)
        guard let track: AVAssetTrack = asset!.tracks(withMediaType: AVMediaType.video).first else{callback(nil); return}

        let range = CMTimeRange(start: CMTime(seconds: ranges[index].lowerBound, preferredTimescale: 1000),
                                end: CMTime(seconds: ranges[index].upperBound, preferredTimescale: 1000))

        let videoTrack = composition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)!
        let audioTrack = composition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid)!

        do{try videoTrack.insertTimeRange(range, of: track, at: lastTime)}
        catch _{callback(nil); return}

        if let audio = asset!.tracks(withMediaType: AVMediaType.audio).first{
            do{try audioTrack.insertTimeRange(range, of: audio, at: lastTime)}
            catch _{callback(nil); return}
        }

        let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)
        layerInstruction.trackID = videoTrack.trackID

        let instruction = VideoFilterCompositionInstruction(trackID: videoTrack.trackID,
                                                            filters: self.filters,
                                                            context: self.context,
                                                            preferredTransform: track.preferredTransform,
                                                            rotate : false)
        instruction.timeRange = CMTimeRange(start: lastTime, duration: range.duration)
        instruction.layerInstructions = [layerInstruction]

        instructions.append(instruction)

        lastTime = lastTime + range.duration
    }

    let videoComposition = AVMutableVideoComposition()
    videoComposition.customVideoCompositorClass = VideoFilterCompositor.self
    videoComposition.frameDuration = CMTimeMake(1, 30)
    videoComposition.renderSize = CGSize(width: 1080, height: 1920)
    videoComposition.instructions = instructions

    let session: AVAssetExportSession = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetHighestQuality)!
    session.videoComposition = videoComposition
    session.outputURL = url
    session.outputFileType = AVFileType.mp4

    session.exportAsynchronously(){
        DispatchQueue.main.async{
            callback(url)
        }
    }

和 AVVideoCompositing 类的一部分:

func startRequest(_ request: AVAsynchronousVideoCompositionRequest){
    autoreleasepool() {
        self.getDispatchQueue().sync{
            guard let instruction = request.videoCompositionInstruction as? VideoFilterCompositionInstruction else{
                request.finish(with: NSError(domain: "jojodmo.com", code: 760, userInfo: nil))
                return
            }
            guard let pixels = request.sourceFrame(byTrackID: instruction.trackID) else{
                request.finish(with: NSError(domain: "jojodmo.com", code: 761, userInfo: nil))
                return
            }

            var image : CIImage? = CIImage(cvPixelBuffer: pixels)

            for filter in instruction.filters{
                filter.setValue(image, forKey: kCIInputImageKey)
                image = filter.outputImage ?? image
            }

            let newBuffer: CVPixelBuffer? = self.renderContext.newPixelBuffer()

            if let buffer = newBuffer{
                instruction.context.render(image!, to: buffer)
                request.finish(withComposedVideoFrame: buffer)
            }
            else{
                request.finish(withComposedVideoFrame: pixels)
            }
        }
    }

最佳答案

App返回内存警告时有一些规避。这是由于我们试图处理大量数据。

为了避免这种内存警告,我们必须养成使用[unowned self] transcript 的习惯。

如果我们没有在闭包中使用这个[unowned self],那么我们会收到内存泄漏警告,并且在某个阶段,应用程序会崩溃。

您可以从下面的链接中找到有关 [unowned self] 的更多信息: Shall we always use [unowned self] inside closure in Swift

添加 [unowned self] 后,在您的类中添加 deinit(){ } 函数并释放或清除不需要的数据。

关于ios - Swift:来自调试器的消息:由于内存问题而终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49902449/

相关文章:

ios - 数据未显示在 UITableViewCell Swift 上

ios - 将 GPUImage 滤镜应用于部分视频

ios - 如何将 CIFilter 输出到相机 View ?

c# - 统一: Detect if the Return or Done key was pressed in the native iOS keyboard

ios - 在没有 Roximity SDK 的情况下检测 Roximity iBeacon?

objective-c - NSVisualEffectView 上的 NSButton : Wrong Background Color

ios - 在 Swift 中使用实时滤镜录制视频

ios - 使用 CIAdditionCompositing 添加纯黑色时的预期行为?

ios - 在 UITableView 中实现 UISearchController 以过滤 User 对象数组

ios - 从 google places api 获取附近的地方。收到错误提供的 API key 无效