-
Notifications
You must be signed in to change notification settings - Fork 3
/
PureVerifierViewController.swift
285 lines (236 loc) · 8.97 KB
/
PureVerifierViewController.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
//
// Example of an implementation from scratch when you need to implement a custom UI
//
// Created by Lukáš Gergel on 18.10.2022.
// Copyright © 2022 Trask, a.s. All rights reserved.
//
import AVFoundation
import Foundation
import RecogLib_iOS
import UIKit
public struct Configuration {
public static let `default` = Configuration(
showDebugVisualisation: false,
dataType: .picture,
role: .Idc,
country: .Cz,
page: .F,
code: nil,
documents: nil,
settings: nil
)
public let showDebugVisualisation: Bool
public let dataType: DataType
public let role: RecogLib_iOS.DocumentRole?
public let country: RecogLib_iOS.Country?
public let page: RecogLib_iOS.PageCodes?
public let code: RecogLib_iOS.DocumentCodes?
public let documents: [Document]?
public let settings: DocumentVerifierSettings?
}
final class PureVerifierViewController: UIViewController {
// MARK: - Private properties
private let verifier: DocumentVerifier
private(set) var previewLayer: AVCaptureVideoPreviewLayer?
private(set) var drawingLayer = DrawingLayer()
private let cameraCaptureQueue = DispatchQueue(label: "cz.trask.zenid.cameraCaptureQueue")
private let captureSession = AVCaptureSession()
private var cameraVideoOutput: AVCaptureVideoDataOutput!
// MARK: - Init
init() {
verifier = .init(
role: RecogLib_iOS.DocumentRole.Idc,
country: RecogLib_iOS.Country.Cz,
page: RecogLib_iOS.PageCodes.F,
code: nil,
language: .Czech
)
verifier.showDebugInfo = true
super.init(nibName: nil, bundle: nil)
NotificationCenter.default.addObserver(
self, selector: #selector(orientationChanged),
name: UIDevice.orientationDidChangeNotification, object: nil
)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
loadModels(url: .modelsDocuments)
guard setupCameraSession() else { return }
setupVerifier(with: .default)
setupUI(with: .default)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setOrientation(orientation: UIDevice.current.orientation)
start()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
verifier.endHologramVerification()
stop()
}
// MARK: - Public functions
func start() {
if captureSession.isRunning {
return
}
DispatchQueue.global(qos: .userInteractive).async { [weak self] in
self?.captureSession.startRunning()
}
}
func stop() {
if !captureSession.isRunning {
return
}
DispatchQueue.global(qos: .userInteractive).async { [weak self] in
self?.captureSession.stopRunning()
}
}
// MARK: - Private functions
@objc
private func orientationChanged() {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
self.setOrientation(orientation: UIDevice.current.orientation)
}
}
private func loadModels(url: URL) {
guard let models = DocumentVerifierModels(url: url) else {
return
}
verifier.loadModels(models)
}
private func verifyImage(buffer: CMSampleBuffer) {
// test code to verify that the image orientation is always correct
// if #available(iOS 13.0, *) {
// if let ib = buffer.imageBuffer {
// let debugImage = UIImage(pixelBuffer: ib)
// }
// }
let result = verifier.verify(buffer: buffer)
// process the verifier result here
}
// Get the objects detected in the current frame and render them over the preview layer.
private func drawRenderables(buffer: CMSampleBuffer) {
guard let size = previewLayer?.frame.size, let commands = verifier.getRenderCommands(canvasWidth: Int(size.width), canvasHeight: Int(size.height))
else { return }
DispatchQueue.main.async { [weak self] in
let renderables = RenderableFactory.createRenderables(commands: commands)
self?.drawingLayer.setRenderables(renderables)
}
}
}
// MARK: - AVCaptureVideoDataOutputSampleBufferDelegate
extension PureVerifierViewController: AVCaptureVideoDataOutputSampleBufferDelegate {
public func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
verifyImage(buffer: sampleBuffer)
drawRenderables(buffer: sampleBuffer)
}
}
// MARK: - UI setup
extension PureVerifierViewController {
func setupUI(with configuration: Configuration) {
if let previewLayer {
view.layer.addSublayer(previewLayer)
previewLayer.frame = view.frame
}
view.layer.addSublayer(drawingLayer)
drawingLayer.frame = view.frame
}
}
// MARK: - Verifier setup
extension PureVerifierViewController {
func setupVerifier(with configuration: Configuration) {
verifier.reset()
verifier.endHologramVerification()
resetDocumentVerifier()
if let settings = configuration.settings {
verifier.update(settings: settings)
}
// This will setup document verifier
if let role = configuration.role {
verifier.documentRole = role
}
if let page = configuration.page {
verifier.page = page
}
if let country = configuration.country {
verifier.country = country
}
if let documents = configuration.documents {
verifier.documentsInput = .init(documents: documents)
}
if configuration.dataType == .video {
verifier.beginHologramVerification()
}
verifier.showDebugInfo = configuration.showDebugVisualisation
}
private func resetDocumentVerifier() {
verifier.documentsInput = nil
verifier.documentRole = nil
verifier.page = nil
verifier.country = nil
verifier.code = nil
}
}
// MARK: - Camera session setup
extension PureVerifierViewController {
func setupCameraSession() -> Bool {
let deviceTypes = [AVCaptureDevice.DeviceType.builtInWideAngleCamera]
let deviceDescoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: deviceTypes,
mediaType: .video,
position: .back)
guard let device = deviceDescoverySession.devices.last else { return false }
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = .resizeAspectFill
self.previewLayer = previewLayer
captureSession.beginConfiguration()
captureSession.sessionPreset = .high
if let inputs = captureSession.inputs as? [AVCaptureDeviceInput] {
for input in inputs {
captureSession.removeInput(input)
}
}
for output in captureSession.outputs {
captureSession.removeOutput(output)
}
guard let input = try? AVCaptureDeviceInput(device: device) else { return false }
captureSession.addInput(input)
let cameraVideoOutput = AVCaptureVideoDataOutput()
cameraVideoOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey: kCVPixelFormatType_32BGRA] as [String: Any]
cameraVideoOutput.setSampleBufferDelegate(self, queue: cameraCaptureQueue)
captureSession.addOutput(cameraVideoOutput)
captureSession.commitConfiguration()
// Zoom factor is necessary to compensate minimal focus distance by newer iphones (13 Pro +)
if #available(iOS 15.0, *) {
Camera.setRecommendedZoomFactor(for: device)
}
return true
}
func setOrientation(orientation: UIDeviceOrientation) {
for connection in captureSession.connections {
switch UIDevice.current.orientation {
case .portrait:
previewLayer?.connection?.videoOrientation = .portrait
connection.videoOrientation = .portrait
case .landscapeRight:
previewLayer?.connection?.videoOrientation = .portrait
connection.videoOrientation = .landscapeLeft
case .landscapeLeft:
previewLayer?.connection?.videoOrientation = .portrait
connection.videoOrientation = .landscapeRight
case .portraitUpsideDown:
previewLayer?.connection?.videoOrientation = .portrait
connection.videoOrientation = .portraitUpsideDown
default:
break
}
}
}
}