-
Notifications
You must be signed in to change notification settings - Fork 436
Expand file tree
/
Copy pathBarcodeScannerCamera.swift
More file actions
367 lines (308 loc) · 12 KB
/
BarcodeScannerCamera.swift
File metadata and controls
367 lines (308 loc) · 12 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import AVFoundation
import CoreImage
import Shared
import UIKit
protocol BarcodeScannerCameraDelegate: AnyObject {
func didDetectBarcode(_ code: String, format: String)
}
final class BarcodeScannerCamera: NSObject {
private let captureSession = AVCaptureSession()
private var isCaptureSessionConfigured = false
private var deviceInput: AVCaptureDeviceInput?
private var videoOutput: AVCaptureVideoDataOutput?
private let metadataOutput = AVCaptureMetadataOutput()
private var sessionQueue: DispatchQueue!
private let feedbackGenerator = UINotificationFeedbackGenerator()
private var allBackCaptureDevices: [AVCaptureDevice] {
AVCaptureDevice.DiscoverySession(
deviceTypes: [
.builtInTripleCamera,
.builtInDualCamera,
.builtInWideAngleCamera,
],
mediaType: .video,
position: .back
).devices
}
public var screenSize: CGSize? {
didSet {
// Prevent unecessary updates
guard let screenSize else { return }
// Calculate normalized rectOfInterest for AVFoundation
let cameraSquareSize = BarcodeScannerView.cameraSquareSize
let x = (screenSize.width - cameraSquareSize) / 2.0
let y = (screenSize.height - cameraSquareSize) / 2.0
// AVFoundation expects (x, y, width, height) in normalized coordinates (0-1),
// and (0,0) is top-left of the video in portrait orientation
let normalizedX = y / screenSize.height
let normalizedY = x / screenSize.width
let normalizedWidth = cameraSquareSize / screenSize.height
let normalizedHeight = cameraSquareSize / screenSize.width
captureSession.beginConfiguration()
metadataOutput.rectOfInterest = CGRect(
x: normalizedX,
y: normalizedY,
width: normalizedWidth,
height: normalizedHeight
)
captureSession.commitConfiguration()
}
}
private var availableCaptureDevices: [AVCaptureDevice] {
allBackCaptureDevices
.filter(\.isConnected)
.filter({ !$0.isSuspended })
}
private var captureDevice: AVCaptureDevice? {
didSet {
guard let captureDevice else { return }
Current.Log.info("Using capture device: \(captureDevice.localizedName)")
sessionQueue.async {
self.updateSessionForCaptureDevice(captureDevice)
}
}
}
/// Last time a barcode was detected
private var lastDetection: Date?
weak var delegate: BarcodeScannerCameraDelegate?
var isRunning: Bool {
captureSession.isRunning
}
private var addToPhotoStream: ((AVCapturePhoto) -> Void)?
private var addToPreviewStream: ((CIImage) -> Void)?
var isPreviewPaused = false
lazy var previewStream: AsyncStream<CIImage>? = AsyncStream { continuation in
addToPreviewStream = { [weak self] ciImage in
guard let self else { return }
if !isPreviewPaused {
continuation.yield(ciImage)
}
}
}
override init() {
super.init()
self.sessionQueue = DispatchQueue(label: "session queue")
self.captureDevice = availableCaptureDevices.first ?? AVCaptureDevice.default(for: .video)
feedbackGenerator.prepare()
}
private func configureCaptureSession(completionHandler: (_ success: Bool) -> Void) {
var success = false
captureSession.beginConfiguration()
defer {
self.captureSession.commitConfiguration()
completionHandler(success)
}
guard
let captureDevice,
let deviceInput = try? AVCaptureDeviceInput(device: captureDevice) else {
Current.Log.error("Failed to obtain video input.")
return
}
let videoOutput = AVCaptureVideoDataOutput()
videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "VideoDataOutputQueue"))
guard captureSession.canAddInput(deviceInput) else {
Current.Log.error("Unable to add device input to capture session.")
return
}
guard captureSession.canAddOutput(videoOutput) else {
Current.Log.error("Unable to add video output to capture session.")
return
}
guard captureSession.canAddOutput(metadataOutput) else {
Current.Log.error("Unable to add metadata output to capture session.")
return
}
captureSession.addInput(deviceInput)
captureSession.addOutput(videoOutput)
captureSession.addOutput(metadataOutput)
metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
var metadataObjectTypes: [AVMetadataObject.ObjectType] = [
.qr,
.aztec,
.code128,
.code39,
.code93,
.dataMatrix,
.ean13,
.ean8,
.itf14,
.pdf417,
.upce,
]
if #available(iOS 15.4, *) {
metadataObjectTypes.append(.codabar)
}
metadataOutput.metadataObjectTypes = metadataObjectTypes
self.deviceInput = deviceInput
self.videoOutput = videoOutput
isCaptureSessionConfigured = true
success = true
}
private func checkAuthorization() async -> Bool {
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .authorized:
Current.Log.info("Camera access authorized.")
return true
case .notDetermined:
Current.Log.info("Camera access not determined.")
sessionQueue.suspend()
let status = await AVCaptureDevice.requestAccess(for: .video)
sessionQueue.resume()
return status
case .denied:
Current.Log.info("Camera access denied.")
return false
case .restricted:
Current.Log.info("Camera library access restricted.")
return false
@unknown default:
return false
}
}
private func deviceInputFor(device: AVCaptureDevice?) -> AVCaptureDeviceInput? {
guard let validDevice = device else { return nil }
do {
return try AVCaptureDeviceInput(device: validDevice)
} catch {
Current.Log.error("Error getting capture device input: \(error.localizedDescription)")
return nil
}
}
private func updateSessionForCaptureDevice(_ captureDevice: AVCaptureDevice) {
guard isCaptureSessionConfigured else { return }
captureSession.beginConfiguration()
defer { captureSession.commitConfiguration() }
for input in captureSession.inputs {
if let deviceInput = input as? AVCaptureDeviceInput {
captureSession.removeInput(deviceInput)
}
}
if let deviceInput = deviceInputFor(device: captureDevice) {
if !captureSession.inputs.contains(deviceInput), captureSession.canAddInput(deviceInput) {
captureSession.addInput(deviceInput)
configureFocus(for: deviceInput.device)
}
}
}
private func configureFocus(for device: AVCaptureDevice) {
do {
try device.lockForConfiguration()
if device.isFocusModeSupported(.continuousAutoFocus) {
device.focusMode = .continuousAutoFocus
}
// Set focus point to center
if device.isFocusPointOfInterestSupported {
device.focusPointOfInterest = CGPoint(x: 0.5, y: 0.5) // Center of the screen
}
device.unlockForConfiguration()
} catch {
Current.Log.error("Error setting barcode scanner camera focus: \(error)")
}
}
func start() async {
guard !captureSession.isRunning else { return }
let authorized = await checkAuthorization()
guard authorized else {
Current.Log.error("Camera access was not authorized.")
return
}
if isCaptureSessionConfigured {
if !captureSession.isRunning {
sessionQueue.async { [self] in
captureSession.startRunning()
}
}
return
}
sessionQueue.async { [self] in
configureCaptureSession { success in
guard success else { return }
self.captureSession.startRunning()
}
}
}
func stop() {
guard isCaptureSessionConfigured else { return }
if captureSession.isRunning {
sessionQueue.async {
self.captureSession.stopRunning()
}
}
previewStream = nil
addToPreviewStream = nil
}
func toggleFlashlight() {
guard let captureDevice, captureDevice.hasTorch else { return }
do {
try captureDevice.lockForConfiguration()
if captureDevice.torchMode == .off {
try captureDevice.setTorchModeOn(level: AVCaptureDevice.maxAvailableTorchLevel)
} else {
captureDevice.torchMode = .off
}
captureDevice.unlockForConfiguration()
} catch {
Current.Log.info("Flashlight could not be used: \(error)")
}
}
func turnOffFlashlight() {
guard let captureDevice, captureDevice.hasTorch else { return }
do {
try captureDevice.lockForConfiguration()
captureDevice.torchMode = .off
captureDevice.unlockForConfiguration()
} catch {
Current.Log.info("Flashlight could not be turned off: \(error)")
}
}
private var deviceOrientation: UIDeviceOrientation {
var orientation = UIDevice.current.orientation
if orientation == UIDeviceOrientation.unknown {
orientation = UIScreen.main.orientation
}
return orientation
}
private func videoOrientationFor(_ deviceOrientation: UIDeviceOrientation) -> AVCaptureVideoOrientation? {
switch deviceOrientation {
case .portrait: return AVCaptureVideoOrientation.portrait
case .portraitUpsideDown: return AVCaptureVideoOrientation.portraitUpsideDown
case .landscapeLeft: return AVCaptureVideoOrientation.landscapeRight
case .landscapeRight: return AVCaptureVideoOrientation.landscapeLeft
default: return nil
}
}
}
extension BarcodeScannerCamera: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(
_ output: AVCaptureOutput,
didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
guard let pixelBuffer = sampleBuffer.imageBuffer else { return }
if connection.isVideoOrientationSupported,
let videoOrientation = videoOrientationFor(deviceOrientation) {
connection.videoOrientation = videoOrientation
}
addToPreviewStream?(CIImage(cvPixelBuffer: pixelBuffer))
}
}
extension BarcodeScannerCamera: AVCaptureMetadataOutputObjectsDelegate {
func metadataOutput(
_ output: AVCaptureMetadataOutput,
didOutput metadataObjects: [AVMetadataObject],
from connection: AVCaptureConnection
) {
// Avoid several detections if user keeps camera pointing to the same barcode
if let lastDetection {
guard Current.date().timeIntervalSince(lastDetection) > 1.5 else { return }
}
if let metadataObject = metadataObjects.first {
let format = metadataObject.type.haString
guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject else { return }
guard let stringValue = readableObject.stringValue else { return }
feedbackGenerator.notificationOccurred(.success)
lastDetection = Current.date()
delegate?.didDetectBarcode(stringValue, format: format)
}
}
}