0

MPSKernal我尝试使用apple 和 custom 提供的默认过滤器通过金属应用实时相机过滤器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)
    }

带有自定义 Shader 的 Pipeline 状态是这样创建的。

        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]

屏幕截图如下所示。

在此处输入图像描述

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

谢谢。

4

1 回答 1

2

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

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

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

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

于 2017-07-19T22:37:27.203 回答