From 05477e3e373ee9d7c9343769cdbcf187db920d88 Mon Sep 17 00:00:00 2001 From: Karol Bielski Date: Sat, 10 Feb 2024 16:19:22 +0100 Subject: [PATCH 1/9] Update docs --- ...AVCaptureDevice+bestForBuiltInCamera.swift | 123 ++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift diff --git a/Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift b/Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift new file mode 100644 index 0000000..a02377f --- /dev/null +++ b/Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift @@ -0,0 +1,123 @@ +// +// AVCaptureDevice+bestForBuiltInCamera.swift +// https://github.com/twostraws/CodeScanner +// +// Created by Karol Bielski on 10/02/2024. +// Copyright © 2024 Paul Hudson. All rights reserved. +// + +import AVFoundation + +extension AVCaptureDevice { + + /// Returns best built in back camera for scanning QR codes zoomed for a given minimum code size. + static func zoomedCameraForQRCode(withMinimumCodeSize minimumCodeSize: Float = 20) -> AVCaptureDevice? { + let captureDevice = AVCaptureDevice.DiscoverySession( + deviceTypes: [.builtInWideAngleCamera], + mediaType: .video, + position: .back + ).devices.first ?? AVCaptureDevice.default(for: .video) + + if #available(iOS 15.0, *) { + captureDevice?.setRecommendedZoomFactor(forMinimumCodeSize: minimumCodeSize) + } + + return captureDevice + } + + @available(iOS 15.0, *) + private func setRecommendedZoomFactor(forMinimumCodeSize minimumCodeSize: Float) { + /* + Optimize the user experience for scanning QR codes down to given size. + When scanning a QR code of that size, the user may need to get closer than + the camera's minimum focus distance to fill the rect of interest. + To have the QR code both fill the rect and still be in focus, we may need to apply some zoom. + */ + let deviceMinimumFocusDistance = Float(minimumFocusDistance) + guard deviceMinimumFocusDistance != -1 else { return } + + let deviceFieldOfView = activeFormat.videoFieldOfView + let formatDimensions = CMVideoFormatDescriptionGetDimensions(activeFormat.formatDescription) + let rectOfInterestWidth = Double(formatDimensions.height) / Double(formatDimensions.width) + let minimumSubjectDistanceForCode = minimumSubjectDistanceForCode( + fieldOfView: deviceFieldOfView, + minimumCodeSize: minimumCodeSize, + previewFillPercentage: Float(rectOfInterestWidth) + ) + + guard minimumSubjectDistanceForCode < deviceMinimumFocusDistance else { return } + + let zoomFactor = deviceMinimumFocusDistance / minimumSubjectDistanceForCode + do { + try lockForConfiguration() + videoZoomFactor = CGFloat(zoomFactor) + unlockForConfiguration() + } catch { + print("Could not lock for configuration: \(error)") + } + } + + private func minimumSubjectDistanceForCode( + fieldOfView: Float, + minimumCodeSize: Float, + previewFillPercentage: Float + ) -> Float { + /* + Given the camera horizontal field of view, we can compute the distance (mm) to make a code + of minimumCodeSize (mm) fill the previewFillPercentage. + */ + let radians = (fieldOfView / 2).radians + let filledCodeSize = minimumCodeSize / previewFillPercentage + return filledCodeSize / tan(radians) + } +} + +private extension Float { + var radians: Float { + self * Float.pi / 180 + } +} + +/* + Part of this code is copied from Apple sample project "AVCamBarcode: Using AVFoundation to capture barcodes". + + IMPORTANT: This Apple software is supplied to you by Apple + Inc. ("Apple") in consideration of your agreement to the following + terms, and your use, installation, modification or redistribution of + this Apple software constitutes acceptance of these terms. If you do + not agree with these terms, please do not use, install, modify or + redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and + subject to these terms, Apple grants you a personal, non-exclusive + license, under Apple's copyrights in this original Apple software (the + "Apple Software"), to use, reproduce, modify and redistribute the Apple + Software, with or without modifications, in source and/or binary forms; + provided that if you redistribute the Apple Software in its entirety and + without modifications, you must retain this notice and the following + text and disclaimers in all such redistributions of the Apple Software. + Neither the name, trademarks, service marks or logos of Apple Inc. may + be used to endorse or promote products derived from the Apple Software + without specific prior written permission from Apple. Except as + expressly stated in this notice, no other rights or licenses, express or + implied, are granted by Apple herein, including but not limited to any + patent rights that may be infringed by your derivative works or by other + works in which the Apple Software may be incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE + MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION + THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND + OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, + MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED + AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), + STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + + Copyright (C) 2016 Apple Inc. All Rights Reserved. + */ From ba8e8d0d9d90ec91f631cdf700305f3c665d7c84 Mon Sep 17 00:00:00 2001 From: Karol Bielski Date: Sat, 10 Feb 2024 16:31:40 +0100 Subject: [PATCH 2/9] Update README --- README.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/README.md b/README.md index 1f13b06..11077fe 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,26 @@ If things go wrong, your result will contain a `ScanError` set to one of these t **Important:** iOS *requires* you to add the "Privacy - Camera Usage Description" key to your Info.plist file, providing a reason for why you want to access the camera. +### Scanning small QR codes + +It may be hard to scan small QR code on devices with dual or tripple cameras because of minimum focus distance. For more information watch [What’s new in camera capture](https://developer.apple.com/videos/play/wwdc2021/10047/?time=133) session from WWDC 2021. + +If you target to scan small QR codes use `AVCaptureDevice.zoomedCameraForQRCode(withMinimumCodeSize:)` method in `CodeScannerView` initializer. + +Example for scanning 20x20mm QR codes. + +```swift +CodeScannerView(codeTypes: [.qr], simulatedData: "Paul Hudson", videoCaptureDevice: AVCaptureDevice.zoomedCameraForQRCode(withMinimumCodeSize: 20)) { response in + switch response { + case .success(let result): + print("Found code: \(result.string)") + case .failure(let error): + print(error.localizedDescription) + } +} +``` + + ## Customization options You can provide a variety of extra customization options to `CodeScannerView` in its initializer: From cbf42a36b514536bad906e98d9d824c28f4edfcf Mon Sep 17 00:00:00 2001 From: Karol Bielski Date: Sat, 10 Feb 2024 16:36:43 +0100 Subject: [PATCH 3/9] Update README --- README.md | 44 ++++++++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 11077fe..626ae53 100644 --- a/README.md +++ b/README.md @@ -26,26 +26,6 @@ If things go wrong, your result will contain a `ScanError` set to one of these t **Important:** iOS *requires* you to add the "Privacy - Camera Usage Description" key to your Info.plist file, providing a reason for why you want to access the camera. -### Scanning small QR codes - -It may be hard to scan small QR code on devices with dual or tripple cameras because of minimum focus distance. For more information watch [What’s new in camera capture](https://developer.apple.com/videos/play/wwdc2021/10047/?time=133) session from WWDC 2021. - -If you target to scan small QR codes use `AVCaptureDevice.zoomedCameraForQRCode(withMinimumCodeSize:)` method in `CodeScannerView` initializer. - -Example for scanning 20x20mm QR codes. - -```swift -CodeScannerView(codeTypes: [.qr], simulatedData: "Paul Hudson", videoCaptureDevice: AVCaptureDevice.zoomedCameraForQRCode(withMinimumCodeSize: 20)) { response in - switch response { - case .success(let result): - print("Found code: \(result.string)") - case .failure(let error): - print(error.localizedDescription) - } -} -``` - - ## Customization options You can provide a variety of extra customization options to `CodeScannerView` in its initializer: @@ -55,6 +35,7 @@ You can provide a variety of extra customization options to `CodeScannerView` in - `showViewfinder` determines whether to show a box-like viewfinder over the UI. Default: false. - `simulatedData` allows you to provide some test data to use in Simulator, when real scanning isn’t available. Default: an empty string. - `shouldVibrateOnSuccess` allows you to determine whether device should vibrate when a code is found. Default: true. +- `videoCaptureDevice` allows you to choose different capture device that is most suitable for code to scan. If you want to add UI customization, such as a dedicated Cancel button, you should wrap your `CodeScannerView` instance in a `NavigationView` and use a `toolbar()` modifier to add whatever buttons you want. @@ -107,6 +88,29 @@ struct QRCodeScannerExampleView: View { } ``` +## Scanning small QR codes + +Scanning small QR code on devices with dual or tripple cameras has to be adjusted because of minimum focus distance built in these cameras. For more information watch [What’s new in camera capture](https://developer.apple.com/videos/play/wwdc2021/10047/?time=133) session from WWDC 2021. + +If you need to scan small QR codes use `AVCaptureDevice.zoomedCameraForQRCode(withMinimumCodeSize:)` method in `CodeScannerView` initializer for `videoCaptureDevice`. + +Example for scanning 20x20mm QR codes. + +```swift +CodeScannerView( + codeTypes: [.qr], + simulatedData: "Paul Hudson", + videoCaptureDevice: AVCaptureDevice.zoomedCameraForQRCode(withMinimumCodeSize: 20) +) { response in + switch response { + case .success(let result): + print("Found code: \(result.string)") + case .failure(let error): + print(error.localizedDescription) + } +} +``` + ## Credits From eed1196c160b494a7ee257ae5dd001c6838d425f Mon Sep 17 00:00:00 2001 From: Karol Bielski Date: Sat, 10 Feb 2024 16:40:37 +0100 Subject: [PATCH 4/9] Update README --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 626ae53..c47625b 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,8 @@ struct QRCodeScannerExampleView: View { ## Scanning small QR codes -Scanning small QR code on devices with dual or tripple cameras has to be adjusted because of minimum focus distance built in these cameras. For more information watch [What’s new in camera capture](https://developer.apple.com/videos/play/wwdc2021/10047/?time=133) session from WWDC 2021. +Scanning small QR code on devices with dual or tripple cameras has to be adjusted because of minimum focus distance built in these cameras. +To have the best possible focus on the code we scan it is needed to choose the most suitable camera and apply recommended zoom factor. If you need to scan small QR codes use `AVCaptureDevice.zoomedCameraForQRCode(withMinimumCodeSize:)` method in `CodeScannerView` initializer for `videoCaptureDevice`. From e5f135ee22773f1db0bda477f6e3be622b74efec Mon Sep 17 00:00:00 2001 From: Karol Bielski Date: Sat, 10 Feb 2024 16:41:20 +0100 Subject: [PATCH 5/9] Update README --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index c47625b..4cefeba 100644 --- a/README.md +++ b/README.md @@ -91,9 +91,7 @@ struct QRCodeScannerExampleView: View { ## Scanning small QR codes Scanning small QR code on devices with dual or tripple cameras has to be adjusted because of minimum focus distance built in these cameras. -To have the best possible focus on the code we scan it is needed to choose the most suitable camera and apply recommended zoom factor. - -If you need to scan small QR codes use `AVCaptureDevice.zoomedCameraForQRCode(withMinimumCodeSize:)` method in `CodeScannerView` initializer for `videoCaptureDevice`. +To have the best possible focus on the code we scan it is needed to choose the most suitable camera and apply recommended zoom factor. Example for scanning 20x20mm QR codes. From 9cc6ae4778bf75f2fa0618b27b6eee040ec48946 Mon Sep 17 00:00:00 2001 From: Karol Bielski Date: Sat, 10 Feb 2024 16:42:10 +0100 Subject: [PATCH 6/9] Update README --- README.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/README.md b/README.md index 4cefeba..0e55d6c 100644 --- a/README.md +++ b/README.md @@ -96,11 +96,7 @@ To have the best possible focus on the code we scan it is needed to choose the m Example for scanning 20x20mm QR codes. ```swift -CodeScannerView( - codeTypes: [.qr], - simulatedData: "Paul Hudson", - videoCaptureDevice: AVCaptureDevice.zoomedCameraForQRCode(withMinimumCodeSize: 20) -) { response in +CodeScannerView(codeTypes: [.qr], videoCaptureDevice: AVCaptureDevice.zoomedCameraForQRCode(withMinimumCodeSize: 20)) { response in switch response { case .success(let result): print("Found code: \(result.string)") From 718824a97b647f2298b80dffea46a6061737fffc Mon Sep 17 00:00:00 2001 From: Karol Bielski Date: Sat, 10 Feb 2024 16:50:10 +0100 Subject: [PATCH 7/9] Make AVCaptureDevice#setRecommendedZoomFactor(forMinimumCodeSize:) non-private --- Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift b/Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift index a02377f..e753229 100644 --- a/Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift +++ b/Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift @@ -26,7 +26,7 @@ extension AVCaptureDevice { } @available(iOS 15.0, *) - private func setRecommendedZoomFactor(forMinimumCodeSize minimumCodeSize: Float) { + func setRecommendedZoomFactor(forMinimumCodeSize minimumCodeSize: Float) { /* Optimize the user experience for scanning QR codes down to given size. When scanning a QR code of that size, the user may need to get closer than From cc0269453693bcb870b2d64c261ab9b481d98f79 Mon Sep 17 00:00:00 2001 From: Karol Bielski Date: Sat, 10 Feb 2024 16:57:08 +0100 Subject: [PATCH 8/9] Add docs --- Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift b/Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift index e753229..6b4e2fb 100644 --- a/Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift +++ b/Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift @@ -25,6 +25,7 @@ extension AVCaptureDevice { return captureDevice } + /// Sets recommended zoom factor for a given minimum code size. @available(iOS 15.0, *) func setRecommendedZoomFactor(forMinimumCodeSize minimumCodeSize: Float) { /* From a9dc96ac04d4f7c3a4c0e4b5a03017dfd3aed2c9 Mon Sep 17 00:00:00 2001 From: Nathan Fallet Date: Fri, 23 Feb 2024 14:36:24 +0100 Subject: [PATCH 9/9] fix: available on catalyst --- Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift b/Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift index 6b4e2fb..2c1b8f7 100644 --- a/Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift +++ b/Sources/CodeScanner/AVCaptureDevice+bestForBuiltInCamera.swift @@ -8,6 +8,7 @@ import AVFoundation +@available(macCatalyst 14.0, *) extension AVCaptureDevice { /// Returns best built in back camera for scanning QR codes zoomed for a given minimum code size.