Skip to content

Commit

Permalink
MTLTexture+CVPixelBuffer (#73)
Browse files Browse the repository at this point in the history
* add mtltexture to cvpixelbuffer conversion

* update version to 0.11.6

* move extension to CVPixelFormat+MTLTexture.swift

* remove unsused error type
  • Loading branch information
eugenebokhan authored and s1ddok committed Dec 19, 2019
1 parent 34338da commit e146427
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Alloy.podspec
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'Alloy'
s.version = '0.11.5'
s.version = '0.11.6'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'Nano helpers for Metal framework'
s.homepage = 'https://github.com/s1ddok/Alloy'
Expand Down
39 changes: 39 additions & 0 deletions Alloy/CVPixelBuffer+MTLTexture.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,42 @@ public extension MTLContext {
return videoTextureCache
}
}

public extension MTLTexture {

var pixelBuffer: CVPixelBuffer? {
guard let cvPixelFormat = self.pixelFormat
.compatibleCVPixelFormat
else { return nil }

var pb: CVPixelBuffer? = nil
var status = try CVPixelBufferCreate(nil,
self.width,
self.height,
cvPixelFormat,
nil,
&pb)
guard status == kCVReturnSuccess,
let pixelBuffer = pb
else { return nil }

status = CVPixelBufferLockBaseAddress(pixelBuffer, [])
guard status == kCVReturnSuccess,
let pixelBufferBaseAdress = CVPixelBufferGetBaseAddress(pixelBuffer)
else { return nil }

let bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer)

self.getBytes(pixelBufferBaseAdress,
bytesPerRow: bytesPerRow,
from: self.region,
mipmapLevel: 0)

status = CVPixelBufferUnlockBaseAddress(pixelBuffer, [])
guard status == kCVReturnSuccess
else { return nil }

return pixelBuffer
}

}
32 changes: 32 additions & 0 deletions Alloy/MTLPixelFormat+CVPixelFormat.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//
// MTLPixelFormat+CVPixelFormat.swift
// Alloy
//
// Created by Eugene Bokhan on 19.12.2019.
//

import Metal

public extension MTLPixelFormat {

var compatibleCVPixelFormat: OSType? {
switch self {
case .r8Unorm: return kCVPixelFormatType_OneComponent8
case .r16Float: return kCVPixelFormatType_OneComponent16Half
case .r32Float: return kCVPixelFormatType_OneComponent32Float

case .rg8Unorm: return kCVPixelFormatType_TwoComponent8
case .rg16Float: return kCVPixelFormatType_TwoComponent16Half
case .rg32Float: return kCVPixelFormatType_TwoComponent32Float

case .bgra8Unorm: return kCVPixelFormatType_32BGRA
case .rgba8Unorm: return kCVPixelFormatType_32RGBA
case .rgba16Float: return kCVPixelFormatType_64RGBAHalf
case .rgba32Float: return kCVPixelFormatType_128RGBAFloat

case .depth32Float: return kCVPixelFormatType_DepthFloat32
default: return nil
}
}

}

0 comments on commit e146427

Please sign in to comment.