-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
migrate qr code scanning to raw mlkit with camerax
- Loading branch information
Showing
18 changed files
with
642 additions
and
168 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
79 changes: 79 additions & 0 deletions
79
shared/src/androidMain/kotlin/ml/dev/kotlin/openotp/qr/QRCodeAnalyzer.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
package ml.dev.kotlin.openotp.qr | ||
|
||
|
||
import android.media.Image | ||
import androidx.camera.core.ExperimentalGetImage | ||
import androidx.camera.core.ImageAnalysis | ||
import androidx.camera.core.ImageProxy | ||
import com.google.mlkit.vision.barcode.BarcodeScanner | ||
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 java.lang.System.currentTimeMillis | ||
|
||
internal class QRCodeAnalyzer( | ||
private val handle: (QRResult) -> Unit, | ||
private val onPassCompleted: (failureOccurred: Boolean) -> Unit, | ||
) : ImageAnalysis.Analyzer { | ||
|
||
private val barcodeScanner: BarcodeScanner? by lazy { | ||
try { | ||
BarcodeScanning.getClient( | ||
BarcodeScannerOptions.Builder() | ||
.setBarcodeFormats(Barcode.FORMAT_QR_CODE) | ||
.build() | ||
) | ||
} catch (e: Exception) { | ||
handleSynchronized(QRResult.QRError(e)) | ||
null | ||
} | ||
} | ||
|
||
@Volatile | ||
private var failureTimestamp: Long = NO_FAILURE_FLAG | ||
|
||
@ExperimentalGetImage | ||
override fun analyze(imageProxy: ImageProxy) { | ||
val image = imageProxy.image ?: return | ||
|
||
if (failureTimestamp.isFailure && currentTimeMillis() - failureTimestamp < FAILURE_THROTTLE_MILLIS) { | ||
return imageProxy.close() | ||
} | ||
failureTimestamp = NO_FAILURE_FLAG | ||
|
||
val scanner = barcodeScanner ?: return | ||
val rotationDegrees = imageProxy.imageInfo.rotationDegrees | ||
scanner | ||
.process(image.toInputImage(rotationDegrees)) | ||
.addOnSuccessListener { onNonEmptySuccess(it) } | ||
.addOnFailureListener { | ||
failureTimestamp = currentTimeMillis() | ||
handleSynchronized(QRResult.QRError(it)) | ||
} | ||
.addOnCompleteListener { | ||
onPassCompleted(failureTimestamp.isFailure) | ||
imageProxy.close() | ||
} | ||
} | ||
|
||
@Synchronized | ||
private fun handleSynchronized(result: QRResult) { | ||
handle(result) | ||
} | ||
|
||
private fun onNonEmptySuccess(codes: List<Barcode?>?) { | ||
val someCodes = codes?.mapNotNull { it?.rawValue }?.takeIf { it.isNotEmpty() } ?: return | ||
handleSynchronized(QRResult.QRSuccess(someCodes)) | ||
} | ||
} | ||
|
||
private const val FAILURE_THROTTLE_MILLIS: Long = 1_000L | ||
|
||
private const val NO_FAILURE_FLAG: Long = Long.MIN_VALUE | ||
|
||
private inline val Long.isFailure: Boolean get() = this != NO_FAILURE_FLAG | ||
|
||
@ExperimentalGetImage | ||
private fun Image.toInputImage(rotationDegrees: Int): InputImage = | ||
InputImage.fromMediaImage(this, rotationDegrees) |
105 changes: 84 additions & 21 deletions
105
shared/src/androidMain/kotlin/ml/dev/kotlin/openotp/qr/QRCodeScanner.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +1,93 @@ | ||
package ml.dev.kotlin.openotp.qr | ||
|
||
import androidx.activity.compose.rememberLauncherForActivityResult | ||
import android.widget.LinearLayout.LayoutParams | ||
import androidx.appcompat.widget.ListPopupWindow | ||
import androidx.camera.view.LifecycleCameraController | ||
import androidx.camera.view.PreviewView | ||
import androidx.compose.foundation.layout.PaddingValues | ||
import androidx.compose.foundation.layout.fillMaxSize | ||
import androidx.compose.foundation.layout.padding | ||
import androidx.compose.material3.MaterialTheme | ||
import androidx.compose.runtime.Composable | ||
import io.github.g00fy2.quickie.ScanCustomCode | ||
import io.github.g00fy2.quickie.config.ScannerConfig | ||
import io.github.g00fy2.quickie.QRResult as LibQRResult | ||
import androidx.compose.runtime.DisposableEffect | ||
import androidx.compose.runtime.remember | ||
import androidx.compose.ui.Modifier | ||
import androidx.compose.ui.graphics.toArgb | ||
import androidx.compose.ui.platform.LocalContext | ||
import androidx.compose.ui.platform.LocalLifecycleOwner | ||
import androidx.compose.ui.viewinterop.AndroidView | ||
import com.google.accompanist.permissions.PermissionStatus | ||
import com.google.accompanist.permissions.rememberPermissionState | ||
import java.util.concurrent.ExecutorService | ||
import java.util.concurrent.Executors | ||
|
||
@Composable | ||
actual fun rememberQRCodeScanner(resultHandler: (QRResult) -> Unit): (() -> Unit)? { | ||
val scanQrCodeLauncher = rememberLauncherForActivityResult(ScanCustomCode()) { | ||
val result = when (it) { | ||
is LibQRResult.QRError -> QRResult.QRError(it.exception) | ||
LibQRResult.QRMissingPermission -> QRResult.QRMissingPermission | ||
is LibQRResult.QRSuccess -> QRResult.QRSuccess(it.content.rawValue) | ||
LibQRResult.QRUserCanceled -> QRResult.QRUserCanceled | ||
actual fun QRCodeScanner( | ||
onResult: (QRResult) -> Boolean, | ||
innerPadding: PaddingValues, | ||
onIsLoadingChange: (Boolean) -> Unit, | ||
) { | ||
val localContext = LocalContext.current | ||
val lifecycleOwner = LocalLifecycleOwner.current | ||
val backgroundColor = MaterialTheme.colorScheme.background | ||
val analysisExecutor = rememberExecutor() | ||
val cameraController = remember { LifecycleCameraController(localContext) } | ||
AndroidView( | ||
modifier = Modifier | ||
.fillMaxSize() | ||
.padding(innerPadding), | ||
factory = { context -> | ||
PreviewView(context).apply { | ||
setBackgroundColor(backgroundColor.toArgb()) | ||
|
||
layoutParams = LayoutParams(ListPopupWindow.MATCH_PARENT, ListPopupWindow.MATCH_PARENT) | ||
scaleType = PreviewView.ScaleType.FILL_START | ||
implementationMode = PreviewView.ImplementationMode.COMPATIBLE | ||
controller = cameraController | ||
|
||
var handleNext = true | ||
|
||
cameraController.setImageAnalysisAnalyzer( | ||
analysisExecutor, | ||
QRCodeAnalyzer( | ||
handle = { handleNext = handleNext && onResult(it) }, | ||
onPassCompleted = { failureOccurred -> onIsLoadingChange(failureOccurred) }, | ||
) | ||
) | ||
|
||
cameraController.bindToLifecycle(lifecycleOwner) | ||
} | ||
}, | ||
onRelease = { | ||
cameraController.unbind() | ||
analysisExecutor.shutdown() | ||
} | ||
resultHandler(result) | ||
} | ||
return { | ||
scanQrCodeLauncher.launch( | ||
ScannerConfig.build { | ||
setHapticSuccessFeedback(true) | ||
setHorizontalFrameRatio(1f) | ||
setShowCloseButton(true) | ||
setShowTorchToggle(true) | ||
) | ||
} | ||
|
||
@Composable | ||
actual fun rememberCameraPermissionState(): CameraPermissionState? { | ||
val cameraPermissionState = rememberPermissionState( | ||
android.Manifest.permission.CAMERA | ||
) | ||
return object : CameraPermissionState { | ||
override val permission: CameraPermission | ||
get() = when (cameraPermissionState.status) { | ||
PermissionStatus.Granted -> CameraPermission.Granted | ||
is PermissionStatus.Denied -> CameraPermission.Denied | ||
} | ||
) | ||
|
||
override fun launchRequest() = cameraPermissionState.launchPermissionRequest() | ||
} | ||
} | ||
|
||
@Composable | ||
private fun rememberExecutor(): ExecutorService { | ||
val executor = remember { Executors.newSingleThreadExecutor() } | ||
DisposableEffect(Unit) { | ||
onDispose { | ||
executor.shutdown() | ||
} | ||
} | ||
return executor | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.