【问题标题】:Memory leak when I use custom compute shaders in Metal在 Metal 中使用自定义计算着色器时出现内存泄漏
【发布时间】:2017-07-19 07:44:21
【问题描述】:

我正在尝试使用苹果提供的默认MPSKernal 过滤器和自定义compute Shaders 通过金属应用实时相机过滤器。

我在网格中的集合视图上应用自定义过滤器,并结合了默认和自定义内核函数。

它看起来像在应用剪辑中。

但我观察到的是,与苹果给出的默认内核函数相比,使用自定义过滤器有很多memory leaks

我不知道自己犯了什么错误。

这是我的自定义计算着色器。

kernel void customFunction1(

                       texture2d<float, access::read> inTexture [[texture(0)]],

                       texture2d<float, access::write> outTexture [[texture(1)]],

                       uint2 gid [[thread_position_in_grid]]){

const float4 colorAtPixel = inTexture.read(gid);
const float4 outputColor = float4(colorAtPixel.r, colorAtPixel.g, colorAtPixel.b, 1);

outTexture.write(outputColor, gid);

}

关于我创建管道和通过线程组进行调度的代码在这里

let blur = MPSImageGaussianBlur(device: device, sigma: 0)

    let threadsPerThreadgroup = MTLSizeMake(4, 4, 1)
    let threadgroupsPerGrid = MTLSizeMake(destinationTexture.width / threadsPerThreadgroup.width, destinationTexture.height / threadsPerThreadgroup.height, 1)

    let commandEncoder = commandBuffer.makeComputeCommandEncoder()
    commandEncoder.setComputePipelineState(pipelineState!)
    commandEncoder.setTexture(sourceTexture, at: 0)
    commandEncoder.setTexture(destinationTexture, at: 1)

    commandEncoder.dispatchThreadgroups(threadgroupsPerGrid, threadsPerThreadgroup: threadsPerThreadgroup)

    commandEncoder.endEncoding()

    autoreleasepool {
        let inPlaceTexture = UnsafeMutablePointer<MTLTexture>.allocate(capacity: 1)
        inPlaceTexture.initialize(to: destinationTexture)
        blur.encode(commandBuffer: commandBuffer, inPlaceTexture: inPlaceTexture, fallbackCopyAllocator: nil)
    }

带有自定义着色器的管道状态是这样创建的。

        let defaultLibrary = device.newDefaultLibrary()

        let kernelFunction = defaultLibrary!.makeFunction(name: name)

        do {
            pipelineState = try device.makeComputePipelineState(function: kernelFunction!)
        } catch {
            fatalError("Unable to create pipeline state")
        }

在检测中显示某些Malloc 16 bytes[Mtkview draw] 方法存在泄漏。

截图如下。

我需要帮助以找出问题发生的位置和方式。

谢谢。

【问题讨论】:

    标签: ios swift memory-leaks metal metal-performance-shaders


    【解决方案1】:

    没有理由显式分配UnsafeMutablePointer 来存储就地纹理参数。顺便说一句,这就是您的泄漏源:您分配了指针,然后从不释放它。

    改为使用局部变量来传递纹理:

    var inPlaceTexture = destinationTexture
    blur.encode(commandBuffer: commandBuffer, inPlaceTexture: &inPlaceTexture, fallbackCopyAllocator: nil)
    

    顺便说一句,如果您在不提供回退分配器或检查返回值的情况下调用就地编码方法,那么您(最终)会遇到麻烦。就地编码在某些情况下会失败,因此您应该提供一个闭包,以便在失败时分配适当的纹理。

    【讨论】:

    • 效果很好。谢谢你。但是你能建议我如何实现后备副本分配器吗?我试过了,但它崩溃了@wa​​rrenm。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多