-
Notifications
You must be signed in to change notification settings - Fork 31
/
CameraTextureGenerater.swift
51 lines (42 loc) · 1.95 KB
/
CameraTextureGenerater.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//
// MetalCamera.swift → CameraTextureGenerater.swift
// MetalCamera → SemanticSegmentation-CoreML
//
// Created by Eric on 2020/06/06.
// Updated by Doyoung Gwak on 2020/11/16.
//
import CoreMedia
class CameraTextureGenerater: NSObject {
public let sourceKey: String
var videoTextureCache: CVMetalTextureCache?
public init(sourceKey: String = "camera") {
self.sourceKey = sourceKey
super.init()
CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, sharedMetalRenderingDevice.device, nil, &videoTextureCache)
}
func texture(from cameraFrame: CVPixelBuffer) -> Texture? {
guard let videoTextureCache = videoTextureCache else { return nil }
let bufferWidth = CVPixelBufferGetWidth(cameraFrame)
let bufferHeight = CVPixelBufferGetHeight(cameraFrame)
var textureRef: CVMetalTexture? = nil
let _ = CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault,
videoTextureCache,
cameraFrame,
nil,
.bgra8Unorm,
bufferWidth,
bufferHeight,
0,
&textureRef)
if let concreteTexture = textureRef,
let cameraTexture = CVMetalTextureGetTexture(concreteTexture) {
return Texture(texture: cameraTexture, textureKey: self.sourceKey)
} else {
return nil
}
}
func texture(from sampleBuffer: CMSampleBuffer) -> Texture? {
guard let cameraFrame = CMSampleBufferGetImageBuffer(sampleBuffer) else { return nil }
return texture(from: cameraFrame)
}
}