2017-07-19 45 views
0

我嘗試使用蘋果公司和自定義compute Shaders給定的默認MPSKernal過濾器通過金屬應用實時相機過濾器。當我在金屬中使用自定義計算着色器時發生內存泄漏

我使用默認和自定義內核函數的組合在網格中的集合視圖上應用自定義過濾器。

它看起來像在應用程序剪輯。

enter image description here

但我觀察到的是,使用自定義過濾器有很多的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是這樣創建的自定義。

 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]方法泄漏。

屏幕截圖如下所示。

enter image description here

我想找到的位置和方式問題的發生幫助。

謝謝。

回答

1

沒有理由明確分配UnsafeMutablePointer來存儲就地紋理參數。順便說一句,這是你的泄漏源:你分配指針,然後永遠不會釋放它。

使用一個局部變量來代替傳遞質地:

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

順便說一句,你(最終)會如果調用就地編碼方法有一個不好的時候沒有提供備用分配器或檢查返回值。在某些情況下就地編碼將失敗,所以您應該提供一個在出現故障時分配適當紋理的閉包。

+0

這工作正常。謝謝。但是,你可以建議我如何實現備用副本分配器。我試過了,但它正在崩潰@warrenm。 –

相關問題