通过memcpy将填充添加到CVPixelBuffer扭曲输出

时间:2019-08-18 23:07:57

标签: swift memcpy cvpixelbuffer

我一直在尝试向大小为192x256(分别为宽度和高度)的输入图像添加填充,以生成256x256的图像。我想通过将原始图像的每一行存入归零缓冲区中,然后在行之间添加偏移量来做到这一点,但是我的输出却完全失真了。

我的填充功能:

func padPixelBuffer(_ srcPixelBuffer: CVPixelBuffer,
                       destWidth: Int,
                       destHeight: Int) -> CVPixelBuffer? {

    CVPixelBufferLockBaseAddress(srcPixelBuffer, CVPixelBufferLockFlags(rawValue: 0))

    let srcBytesPerRow = CVPixelBufferGetBytesPerRow(srcPixelBuffer)
    let srcWidth = CVPixelBufferGetWidth(srcPixelBuffer)
    let srcHeight = CVPixelBufferGetHeight(srcPixelBuffer)
    let pixelFormat = CVPixelBufferGetPixelFormatType(srcPixelBuffer)
    let srcBaseAddress = CVPixelBufferGetBaseAddress(srcPixelBuffer)

    var paddedPixelBuffer: CVPixelBuffer?

    let srcBytes = srcBaseAddress!.assumingMemoryBound(to: UInt8.self)
    let destBuffer = calloc(4*destHeight*destWidth, MemoryLayout<UInt8>.size)

    for row in 0..<srcHeight {
        let offset = 4*MemoryLayout<UInt8>.size*((destWidth - srcWidth)/2 + row*destWidth)
        memcpy(destBuffer?.advanced(by: offset), srcBytes, srcBytesPerRow)
    }

    CVPixelBufferUnlockBaseAddress(srcPixelBuffer, CVPixelBufferLockFlags(rawValue: 0))

    let destBytesPerRow = 4*destWidth

    let releaseCallback: CVPixelBufferReleaseBytesCallback = { _, ptr in
        if let ptr = ptr {
            free(UnsafeMutableRawPointer(mutating: ptr))
        }
    }

    CVPixelBufferCreateWithBytes(nil, destWidth, destWidth,
                                              pixelFormat, destBuffer!,
                                              destBytesPerRow, releaseCallback,
                                              nil, nil, &paddedPixelBuffer)

    return paddedPixelBuffer
}

由于输入和输出的尺寸均为16的倍数,因此我认为这不是图像编码方式的问题(因为可能会隐式添加填充)。我使用memcpy是否有问题?

作为参考,srcBytesPerRow = 768(4 * 192),像素格式为BGRA32。

0 个答案:

没有答案