π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] Improve QR detection with ML Kit fallback and reduce debounce
Amrithesh Kakkoth Ente0d4ea2f2f0b0
diff --git a/mobile/apps/auth/plugins/qr/android/build.gradle b/mobile/apps/auth/plugins/qr/android/build.gradleindex 2e8cdb232a..c3e2573139 100644--- a/mobile/apps/auth/plugins/qr/android/build.gradle+++ b/mobile/apps/auth/plugins/qr/android/build.gradle@@ -50,6 +50,8 @@ android {implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"implementation 'com.journeyapps:zxing-android-embedded:4.3.0'implementation 'com.google.zxing:core:3.5.1'+ // ML Kit bundled barcode scanner (runs fully on-device, no GMS required)+ implementation 'com.google.mlkit:barcode-scanning:17.3.0'}testOptions {diff --git a/mobile/apps/auth/plugins/qr/android/src/main/kotlin/io/ente/auth/ente_qr/EnteQrPlugin.kt b/mobile/apps/auth/plugins/qr/android/src/main/kotlin/io/ente/auth/ente_qr/EnteQrPlugin.ktindex 44f97fa34a..5d1050acdf 100644--- a/mobile/apps/auth/plugins/qr/android/src/main/kotlin/io/ente/auth/ente_qr/EnteQrPlugin.kt+++ b/mobile/apps/auth/plugins/qr/android/src/main/kotlin/io/ente/auth/ente_qr/EnteQrPlugin.kt@@ -2,7 +2,14 @@ package io.ente.auth.ente_qrimport android.graphics.Bitmapimport android.graphics.BitmapFactory+import android.graphics.Matrix+import android.media.ExifInterfaceimport androidx.annotation.NonNull+import com.google.mlkit.vision.barcode.BarcodeScannerOptions+import com.google.mlkit.vision.barcode.BarcodeScanning+import com.google.mlkit.vision.barcode.common.Barcode+import com.google.mlkit.vision.common.InputImage+import com.google.android.gms.tasks.Tasksimport com.google.zxing.BarcodeFormatimport com.google.zxing.BinaryBitmapimport com.google.zxing.DecodeHintType@@ -26,6 +33,10 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {private lateinit var channel : MethodChannelprivate val executor = Executors.newSingleThreadExecutor()+ private val mlKitOptions = BarcodeScannerOptions.Builder()+ .setBarcodeFormats(Barcode.FORMAT_QR_CODE)+ .build()+override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {channel = MethodChannel(flutterPluginBinding.binaryMessenger, "ente_qr")channel.setMethodCallHandler(this)@@ -84,191 +95,233 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {}}+ /**+ * Load a bitmap and apply EXIF orientation so the image is upright+ * before QR detection.+ */+ private fun loadBitmapWithOrientation(imagePath: String): Bitmap? {+ val bitmap = BitmapFactory.decodeFile(imagePath) ?: return null+ return try {+ val exif = ExifInterface(imagePath)+ val orientation = exif.getAttributeInt(+ ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL+ )+ val matrix = Matrix()+ when (orientation) {+ ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90f)+ ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180f)+ ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270f)+ ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.preScale(-1f, 1f)+ ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.preScale(1f, -1f)+ else -> return bitmap+ }+ val rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)+ if (rotated !== bitmap) bitmap.recycle()+ rotated+ } catch (_: Exception) {+ bitmap+ }+ }++ private fun createDecodeHints(): HashMap<DecodeHintType, Any> {+ val hints = HashMap<DecodeHintType, Any>()+ hints[DecodeHintType.POSSIBLE_FORMATS] = listOf(BarcodeFormat.QR_CODE)+ hints[DecodeHintType.TRY_HARDER] = true+ hints[DecodeHintType.ALSO_INVERTED] = true+ return hints+ }++ // ββ ZXing fast path (single pass at original resolution) ββββββββββ++ /**+ * Quick ZXing decode at original resolution with HybridBinarizer.+ * Handles ~80% of clear QR codes instantly.+ */+ private fun zxingQuickDecode(bitmap: Bitmap): ZXingResult? {+ val width = bitmap.width+ val height = bitmap.height+ val pixels = IntArray(width * height)+ bitmap.getPixels(pixels, 0, width, 0, 0, width, height)+ val source = RGBLuminanceSource(width, height, pixels)+ val reader = MultiFormatReader()+ reader.setHints(createDecodeHints())+ return try {+ reader.decode(BinaryBitmap(HybridBinarizer(source)))+ } catch (_: NotFoundException) {+ null+ }+ }++ /**+ * Quick ZXing multi-decode at original resolution.+ */+ private fun zxingQuickDecodeMultiple(bitmap: Bitmap): Array<ZXingResult>? {+ val width = bitmap.width+ val height = bitmap.height+ val pixels = IntArray(width * height)+ bitmap.getPixels(pixels, 0, width, 0, 0, width, height)+ val source = RGBLuminanceSource(width, height, pixels)+ val hints = createDecodeHints()+ val reader = MultiFormatReader()+ reader.setHints(hints)+ val multiReader = GenericMultipleBarcodeReader(reader)+ return try {+ multiReader.decodeMultiple(BinaryBitmap(HybridBinarizer(source)), hints)+ } catch (_: NotFoundException) {+ null+ }+ }++ // ββ ML Kit (handles all difficult cases) ββββββββββββββββββββββββββ++ private fun mlKitScanSingle(bitmap: Bitmap): String? {+ val scanner = BarcodeScanning.getClient(mlKitOptions)+ return try {+ val inputImage = InputImage.fromBitmap(bitmap, 0)+ val barcodes = Tasks.await(scanner.process(inputImage))+ barcodes.firstOrNull { it.rawValue != null }?.rawValue+ } catch (_: Exception) {+ null+ } finally {+ scanner.close()+ }+ }++ private fun mlKitScanMultiple(bitmap: Bitmap): List<Map<String, Any>>? {+ val scanner = BarcodeScanning.getClient(mlKitOptions)+ return try {+ val inputImage = InputImage.fromBitmap(bitmap, 0)+ val barcodes = Tasks.await(scanner.process(inputImage))+ val imgWidth = bitmap.width.toDouble()+ val imgHeight = bitmap.height.toDouble()++ val detections = barcodes.mapNotNull { barcode ->+ val content = barcode.rawValue ?: return@mapNotNull null+ val box = barcode.boundingBox ?: return@mapNotNull null+ mapOf(+ "content" to content,+ "x" to (box.left / imgWidth),+ "y" to (box.top / imgHeight),+ "width" to (box.width() / imgWidth),+ "height" to (box.height() / imgHeight),+ )+ }+ detections.ifEmpty { null }+ } catch (_: Exception) {+ null+ } finally {+ scanner.close()+ }+ }++ // ββ Main scan methods βββββββββββββββββββββββββββββββββββββββββββββ+ //+ // Strategy: ZXing fast pass β ML Kit fallback+ // - ZXing at original resolution handles most clear QR codes instantly+ // - ML Kit handles everything else (moirΓ©, distortion, low contrast,+ // small QR codes, inverted colors) without wasting time on ZXing+ // multi-resolution/multi-binarizer attempts+private fun scanQrCode(imagePath: String): Map<String, Any> {try {val file = File(imagePath)if (!file.exists()) {- return mapOf(- "success" to false,- "error" to "Image file not found: $imagePath"- )+ return mapOf("success" to false, "error" to "Image file not found: $imagePath")}- var bitmap = BitmapFactory.decodeFile(imagePath)- if (bitmap == null) {- return mapOf(- "success" to false,- "error" to "Unable to decode image file"- )- }+ val bitmap = loadBitmapWithOrientation(imagePath)+ ?: return mapOf("success" to false, "error" to "Unable to decode image file")- // Try multiple times with different image sizes like Aegis does- for (i in 0..2) {- if (i != 0) {- // Resize bitmap for subsequent attempts- val newWidth = bitmap.width / (i * 2)- val newHeight = bitmap.height / (i * 2)- if (newWidth > 0 && newHeight > 0) {- bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true)- }+ try {+ // Fast path: ZXing at original resolution+ val zxingResult = zxingQuickDecode(bitmap)+ if (zxingResult != null) {+ return mapOf("success" to true, "content" to zxingResult.text)}- try {- val width = bitmap.width- val height = bitmap.height- val pixels = IntArray(width * height)- bitmap.getPixels(pixels, 0, width, 0, 0, width, height)-- val source = RGBLuminanceSource(width, height, pixels)- val binaryBitmap = BinaryBitmap(HybridBinarizer(source))-- val reader = MultiFormatReader()- val hints = HashMap<DecodeHintType, Any>()- hints[DecodeHintType.POSSIBLE_FORMATS] = listOf(BarcodeFormat.QR_CODE)- hints[DecodeHintType.TRY_HARDER] = true- hints[DecodeHintType.ALSO_INVERTED] = true- reader.setHints(hints)-- val qrResult: ZXingResult = reader.decode(binaryBitmap)-- return mapOf(- "success" to true,- "content" to qrResult.text- )- } catch (e: NotFoundException) {- // Continue to next iteration- continue+ // ML Kit fallback+ val mlResult = mlKitScanSingle(bitmap)+ if (mlResult != null) {+ return mapOf("success" to true, "content" to mlResult)}- }- return mapOf(- "success" to false,- "error" to "No QR code found in image"- )+ return mapOf("success" to false, "error" to "No QR code found in image")+ } finally {+ bitmap.recycle()+ }} catch (e: Exception) {- return mapOf(- "success" to false,- "error" to "Error scanning QR code: ${e.message}"- )+ return mapOf("success" to false, "error" to "Error scanning QR code: ${e.message}")}}private fun scanAllQrCodes(imagePath: String): Map<String, Any> {val file = File(imagePath)if (!file.exists()) {- return mapOf(- "success" to false,- "error" to "Image file not found: $imagePath"- )+ return mapOf("success" to false, "error" to "Image file not found: $imagePath")}- val origBitmap = BitmapFactory.decodeFile(imagePath)- ?: return mapOf(- "success" to false,- "error" to "Unable to decode image file"- )+ val bitmap = loadBitmapWithOrientation(imagePath)+ ?: return mapOf("success" to false, "error" to "Unable to decode image file")- var bitmap = origBitmaptry {- val origWidth = origBitmap.width.toDouble()- val origHeight = origBitmap.height.toDouble()-- for (i in 0..2) {- if (i != 0) {- val newWidth = origBitmap.width / (i * 2)- val newHeight = origBitmap.height / (i * 2)- if (newWidth > 0 && newHeight > 0) {- if (bitmap !== origBitmap) bitmap.recycle()- bitmap = Bitmap.createScaledBitmap(origBitmap, newWidth, newHeight, true)+ val imgWidth = bitmap.width.toDouble()+ val imgHeight = bitmap.height.toDouble()++ // Fast path: ZXing at original resolution+ val zxingResults = zxingQuickDecodeMultiple(bitmap)+ if (zxingResults != null && zxingResults.isNotEmpty()) {+ val detections = mutableListOf<Map<String, Any>>()++ for (qrResult in zxingResults) {+ val points = qrResult.resultPoints+ if (points == null || points.isEmpty()) continue++ var minX = Float.MAX_VALUE+ var minY = Float.MAX_VALUE+ var maxX = -Float.MAX_VALUE+ var maxY = -Float.MAX_VALUE++ for (point in points) {+ if (point == null) continue+ if (point.x < minX) minX = point.x+ if (point.y < minY) minY = point.y+ if (point.x > maxX) maxX = point.x+ if (point.y > maxY) maxY = point.y}- }- try {- val width = bitmap.width- val height = bitmap.height- val pixels = IntArray(width * height)- bitmap.getPixels(pixels, 0, width, 0, 0, width, height)-- val source = RGBLuminanceSource(width, height, pixels)- val binaryBitmap = BinaryBitmap(HybridBinarizer(source))-- val reader = MultiFormatReader()- val hints = HashMap<DecodeHintType, Any>()- hints[DecodeHintType.POSSIBLE_FORMATS] = listOf(BarcodeFormat.QR_CODE)- hints[DecodeHintType.TRY_HARDER] = true- hints[DecodeHintType.ALSO_INVERTED] = true- reader.setHints(hints)-- val multiReader = GenericMultipleBarcodeReader(reader)- val results: Array<ZXingResult> = multiReader.decodeMultiple(binaryBitmap, hints)-- val detections = mutableListOf<Map<String, Any>>()- val scaleX = if (i == 0) 1.0 else (i * 2).toDouble()- val scaleY = if (i == 0) 1.0 else (i * 2).toDouble()-- for (qrResult in results) {- val points = qrResult.resultPoints- if (points == null || points.isEmpty()) continue-- var minX = Float.MAX_VALUE- var minY = Float.MAX_VALUE- var maxX = -Float.MAX_VALUE- var maxY = -Float.MAX_VALUE-- for (point in points) {- if (point == null) continue- val px = point.x * scaleX.toFloat()- val py = point.y * scaleY.toFloat()- if (px < minX) minX = px- if (py < minY) minY = py- if (px > maxX) maxX = px- if (py > maxY) maxY = py- }-- // Add padding around finder patterns (they mark corners, not edges)- val padX = (maxX - minX) * 0.15f- val padY = (maxY - minY) * 0.15f- minX = (minX - padX).coerceAtLeast(0f)- minY = (minY - padY).coerceAtLeast(0f)- maxX = (maxX + padX).coerceAtMost(origWidth.toFloat())- maxY = (maxY + padY).coerceAtMost(origHeight.toFloat())-- detections.add(mapOf(- "content" to qrResult.text,- "x" to (minX / origWidth),- "y" to (minY / origHeight),- "width" to ((maxX - minX) / origWidth),- "height" to ((maxY - minY) / origHeight),- ))- }+ // Add padding around finder patterns+ val padX = (maxX - minX) * 0.15f+ val padY = (maxY - minY) * 0.15f+ minX = (minX - padX).coerceAtLeast(0f)+ minY = (minY - padY).coerceAtLeast(0f)+ maxX = (maxX + padX).coerceAtMost(imgWidth.toFloat())+ maxY = (maxY + padY).coerceAtMost(imgHeight.toFloat())++ detections.add(mapOf(+ "content" to qrResult.text,+ "x" to (minX / imgWidth),+ "y" to (minY / imgHeight),+ "width" to ((maxX - minX) / imgWidth),+ "height" to ((maxY - minY) / imgHeight),+ ))+ }- if (detections.isNotEmpty()) {- if (bitmap !== origBitmap) bitmap.recycle()- origBitmap.recycle()- return mapOf(- "success" to true,- "detections" to detections- )- }- } catch (e: NotFoundException) {- continue+ if (detections.isNotEmpty()) {+ return mapOf("success" to true, "detections" to detections)}}- if (bitmap !== origBitmap) bitmap.recycle()- origBitmap.recycle()+ // ML Kit fallback+ val mlDetections = mlKitScanMultiple(bitmap)+ if (mlDetections != null) {+ return mapOf("success" to true, "detections" to mlDetections)+ }- return mapOf(- "success" to false,- "error" to "No QR code found in image"- )+ return mapOf("success" to false, "error" to "No QR code found in image")} catch (e: Exception) {- if (bitmap !== origBitmap) bitmap.recycle()- origBitmap.recycle()- return mapOf(- "success" to false,- "error" to "Error scanning QR codes: ${e.message}"- )+ return mapOf("success" to false, "error" to "Error scanning QR codes: ${e.message}")+ } finally {+ bitmap.recycle()}}diff --git a/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swift b/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swiftindex f7c656fffd..b198b25719 100644--- a/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swift+++ b/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swift@@ -1,5 +1,6 @@import Flutterimport UIKit+import Visionpublic class EnteQrPlugin: NSObject, FlutterPlugin {private static let detectionQueue = DispatchQueue(label: "io.ente.qr.detection", qos: .userInitiated)@@ -40,52 +41,42 @@ public class EnteQrPlugin: NSObject, FlutterPlugin {result(FlutterMethodNotImplemented)}}-- private func scanQrCode(from imagePath: String, result: @escaping FlutterResult) {- EnteQrPlugin.detectionQueue.async {- guard let image = UIImage(contentsOfFile: imagePath) else {- DispatchQueue.main.async {- result([- "success": false,- "error": "Unable to load image from path: \(imagePath)"- ])- }- return- }- guard let cgImage = image.cgImage else {- DispatchQueue.main.async {- result([- "success": false,- "error": "Unable to get CGImage from UIImage"- ])- }- return- }+ private func detectBarcodes(in cgImage: CGImage) -> [VNBarcodeObservation] {+ let request = VNDetectBarcodesRequest()+ request.symbologies = [.qr]- let detector = CIDetector(ofType: CIDetectorTypeQRCode,- context: nil,- options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])+ let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])+ do {+ try handler.perform([request])+ } catch {+ return []+ }++ return request.results ?? []+ }- guard let qrDetector = detector else {+ private func scanQrCode(from imagePath: String, result: @escaping FlutterResult) {+ EnteQrPlugin.detectionQueue.async {+ guard let image = UIImage(contentsOfFile: imagePath),+ let cgImage = image.cgImage else {DispatchQueue.main.async {result(["success": false,- "error": "Unable to create QR code detector"+ "error": "Unable to load image from path: \(imagePath)"])}return}- let ciImage = CIImage(cgImage: cgImage)- let features = qrDetector.features(in: ciImage)+ let observations = self.detectBarcodes(in: cgImage)- if let qrFeature = features.first as? CIQRCodeFeature,- let messageString = qrFeature.messageString {+ if let obs = observations.first,+ let payload = obs.payloadStringValue {DispatchQueue.main.async {result(["success": true,- "content": messageString+ "content": payload])}} else {@@ -101,7 +92,8 @@ public class EnteQrPlugin: NSObject, FlutterPlugin {private func scanAllQrCodes(from imagePath: String, result: @escaping FlutterResult) {EnteQrPlugin.detectionQueue.async {- guard let image = UIImage(contentsOfFile: imagePath) else {+ guard let image = UIImage(contentsOfFile: imagePath),+ let cgImage = image.cgImage else {DispatchQueue.main.async {result(["success": false,@@ -111,72 +103,22 @@ public class EnteQrPlugin: NSObject, FlutterPlugin {return}- guard let cgImage = image.cgImage else {- DispatchQueue.main.async {- result([- "success": false,- "error": "Unable to get CGImage from UIImage"- ])- }- return- }-- let detector = CIDetector(ofType: CIDetectorTypeQRCode,- context: nil,- options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])-- guard let qrDetector = detector else {- DispatchQueue.main.async {- result([- "success": false,- "error": "Unable to create QR code detector"- ])- }- return- }-- let ciImage = CIImage(cgImage: cgImage)- let features = qrDetector.features(in: ciImage)-- let imageWidth = CGFloat(cgImage.width)- let imageHeight = CGFloat(cgImage.height)+ let observations = self.detectBarcodes(in: cgImage)var detections: [[String: Any]] = []- for feature in features {- guard let qrFeature = feature as? CIQRCodeFeature,- let messageString = qrFeature.messageString else {- continue- }-- // Core Image has origin at bottom-left with y-up.- // Convert to normalized [0,1] coords with origin top-left, y-down.- let minX = min(qrFeature.topLeft.x, qrFeature.bottomLeft.x)- let maxX = max(qrFeature.topRight.x, qrFeature.bottomRight.x)- // In CI coords, topLeft.y > bottomLeft.y (y goes up)- let minYci = min(qrFeature.bottomLeft.y, qrFeature.bottomRight.y)- let maxYci = max(qrFeature.topLeft.y, qrFeature.topRight.y)-- // Add padding around finder patterns (matching Android's 15%)- let padX = (maxX - minX) * 0.15- let padY = (maxYci - minYci) * 0.15- let paddedMinX = max(minX - padX, 0)- let paddedMaxX = min(maxX + padX, imageWidth)- let paddedMinYci = max(minYci - padY, 0)- let paddedMaxYci = min(maxYci + padY, imageHeight)-- // Flip y: top-left origin- let normX = paddedMinX / imageWidth- let normY = 1.0 - (paddedMaxYci / imageHeight)- let normW = (paddedMaxX - paddedMinX) / imageWidth- let normH = (paddedMaxYci - paddedMinYci) / imageHeight+ for obs in observations {+ guard let payload = obs.payloadStringValue else { continue }+ // Vision's boundingBox is normalized [0,1] with origin at bottom-left.+ // Convert to top-left origin (y-down) for Flutter.+ let box = obs.boundingBoxdetections.append([- "content": messageString,- "x": Double(normX),- "y": Double(normY),- "width": Double(normW),- "height": Double(normH),+ "content": payload,+ "x": Double(box.origin.x),+ "y": Double(1.0 - box.origin.y - box.height),+ "width": Double(box.width),+ "height": Double(box.height),])}diff --git a/mobile/apps/auth/plugins/qr/ios/ente_qr.podspec b/mobile/apps/auth/plugins/qr/ios/ente_qr.podspecindex f52d6d032b..11df118b30 100644--- a/mobile/apps/auth/plugins/qr/ios/ente_qr.podspec+++ b/mobile/apps/auth/plugins/qr/ios/ente_qr.podspec@@ -15,7 +15,7 @@ A QR code reader plugin for Ente.s.source = { :path => '.' }s.source_files = 'Classes/**/*'s.dependency 'Flutter'- s.platform = :ios, '9.0'+ s.platform = :ios, '12.0'# Flutter.framework does not contain a i386 slice.s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }diff --git a/mobile/apps/photos/lib/ui/viewer/file/qr_code_detection_helper.dart b/mobile/apps/photos/lib/ui/viewer/file/qr_code_detection_helper.dartindex e3fc39e112..f78b0a5950 100644--- a/mobile/apps/photos/lib/ui/viewer/file/qr_code_detection_helper.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/qr_code_detection_helper.dart@@ -9,7 +9,7 @@ import "package:photos/models/file/file_type.dart";import "package:photos/utils/file_util.dart";class QrCodeDetectionHelper {- static const _debounceDuration = Duration(milliseconds: 1500);+ static const _debounceDuration = Duration(milliseconds: 500);final Logger _logger = Logger("QrCodeDetectionHelper");final EnteQr _enteQr = EnteQr();