Files
QFT/android/app/src/main/java/com/qft/optical/QrAnalyzer.kt
T
2026-08-10 15:45:04 +08:00

163 lines
6.3 KiB
Kotlin

package com.qft.optical
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType
import com.google.zxing.MultiFormatReader
import com.google.zxing.PlanarYUVLuminanceSource
import com.google.zxing.common.GlobalHistogramBinarizer
import com.google.zxing.common.HybridBinarizer
import java.util.concurrent.Callable
import java.util.concurrent.Executors
class QrAnalyzer(
private val profile: Profile,
private val onTexts: (List<String>) -> Unit,
private val onStats: (cameraFramesPerSecond: Double, decodedPerSecond: Double) -> Unit = { _, _ -> },
) : ImageAnalysis.Analyzer {
enum class Profile { PAIR_FAST, OPTICAL_MULTI }
private val readers = Array(5) { newReader() }
private val decodePool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors().coerceIn(2, 4))
private var frameCounter = 0L
private var decodedCounter = 0L
private var windowStarted = android.os.SystemClock.elapsedRealtime()
override fun analyze(image: ImageProxy) {
try {
val gray = GrayFrame.from(image)
frameCounter++
val results = when (profile) {
Profile.PAIR_FAST -> decodePair(gray)
Profile.OPTICAL_MULTI -> decodeOptical(gray)
}.distinct()
if (results.isNotEmpty()) {
decodedCounter += results.size
onTexts(results)
}
reportStatsIfNeeded()
} finally {
image.close()
}
}
private fun decodePair(gray: GrayFrame): List<String> {
// QFTPAIR2 is intentionally compact. Try a cheap centered GlobalHistogram
// pass first, then the full frame every time so off-axis scans do not wait
// several frames. HybridBinarizer is reserved for every third miss.
val marginX = (gray.width * 0.08).toInt()
val marginY = (gray.height * 0.08).toInt()
decodeRegion(
gray, marginX, marginY, gray.width - marginX * 2, gray.height - marginY * 2,
readers[0], hybridFallback = false,
)?.let { return listOf(it) }
decodeRegion(gray, 0, 0, gray.width, gray.height, readers[0], hybridFallback = false)
?.let { return listOf(it) }
if (frameCounter % 3L == 0L) {
decodeRegion(gray, 0, 0, gray.width, gray.height, readers[0], hybridFallback = true)
?.let { return listOf(it) }
}
return emptyList()
}
private fun decodeOptical(gray: GrayFrame): List<String> {
// v0.3 Windows can present a 2x2 grid. Decode quadrants concurrently.
// 8% overlap tolerates perspective/centering error around the middle.
val overlapX = (gray.width * 0.08).toInt()
val overlapY = (gray.height * 0.08).toInt()
val halfW = gray.width / 2
val halfH = gray.height / 2
val regions = arrayOf(
intArrayOf(0, 0, (halfW + overlapX).coerceAtMost(gray.width), (halfH + overlapY).coerceAtMost(gray.height)),
intArrayOf((halfW - overlapX).coerceAtLeast(0), 0, gray.width - (halfW - overlapX).coerceAtLeast(0), (halfH + overlapY).coerceAtMost(gray.height)),
intArrayOf(0, (halfH - overlapY).coerceAtLeast(0), (halfW + overlapX).coerceAtMost(gray.width), gray.height - (halfH - overlapY).coerceAtLeast(0)),
intArrayOf((halfW - overlapX).coerceAtLeast(0), (halfH - overlapY).coerceAtLeast(0), gray.width - (halfW - overlapX).coerceAtLeast(0), gray.height - (halfH - overlapY).coerceAtLeast(0)),
)
val tasks = regions.mapIndexed { index, r ->
Callable {
decodeRegion(gray, r[0], r[1], r[2], r[3], readers[index], hybridFallback = false)
}
}
val found = try {
decodePool.invokeAll(tasks).mapNotNull { future ->
try { future.get() } catch (_: Exception) { null }
}
} catch (_: Exception) {
emptyList()
}
if (found.isNotEmpty()) return found
// Backward-compatible single-QR fallback. Limit the expensive hybrid
// pass to every third frame so low-end Android 7 devices stay responsive.
return if (frameCounter % 3L == 0L) {
decodeRegion(gray, 0, 0, gray.width, gray.height, readers[4], hybridFallback = true)
?.let(::listOf) ?: emptyList()
} else emptyList()
}
private fun decodeRegion(
gray: GrayFrame,
left: Int,
top: Int,
width: Int,
height: Int,
reader: MultiFormatReader,
hybridFallback: Boolean,
): String? {
if (width < 80 || height < 80) return null
val source = try {
PlanarYUVLuminanceSource(
gray.luma, gray.width, gray.height,
left.coerceAtLeast(0), top.coerceAtLeast(0),
width.coerceAtMost(gray.width - left.coerceAtLeast(0)),
height.coerceAtMost(gray.height - top.coerceAtLeast(0)),
false,
)
} catch (_: Exception) { return null }
try {
return reader.decodeWithState(BinaryBitmap(GlobalHistogramBinarizer(source)))?.text
} catch (_: Exception) {
if (!hybridFallback) return null
} finally {
reader.reset()
}
return try {
reader.decodeWithState(BinaryBitmap(HybridBinarizer(source)))?.text
} catch (_: Exception) {
null
} finally {
reader.reset()
}
}
private fun reportStatsIfNeeded() {
val now = android.os.SystemClock.elapsedRealtime()
val elapsed = now - windowStarted
if (elapsed < 1000L) return
val seconds = elapsed / 1000.0
onStats(frameCounter / seconds, decodedCounter / seconds)
frameCounter = 0
decodedCounter = 0
windowStarted = now
}
fun close() {
decodePool.shutdownNow()
}
companion object {
private fun newReader() = MultiFormatReader().apply {
setHints(
mapOf(
DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE),
DecodeHintType.TRY_HARDER to false,
DecodeHintType.CHARACTER_SET to "UTF-8",
)
)
}
}
}