V0.4.0加入锁定二维码
This commit is contained in:
@@ -5,9 +5,13 @@ import android.content.pm.PackageManager
|
||||
import android.content.res.ColorStateList
|
||||
import android.graphics.Color
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.hardware.camera2.CameraCharacteristics
|
||||
import android.hardware.camera2.CameraManager
|
||||
import android.hardware.camera2.CaptureRequest
|
||||
import android.net.Network
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.util.Range
|
||||
import android.util.Size
|
||||
import android.view.Gravity
|
||||
import android.view.ViewGroup
|
||||
@@ -19,6 +23,10 @@ import android.widget.ScrollView
|
||||
import android.widget.TextView
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.camera.camera2.interop.Camera2Interop
|
||||
import androidx.camera.camera2.interop.ExperimentalCamera2Interop
|
||||
import androidx.camera.core.Camera
|
||||
import androidx.camera.core.CameraSelector
|
||||
import androidx.camera.core.FocusMeteringAction
|
||||
import androidx.camera.core.ImageAnalysis
|
||||
@@ -39,8 +47,14 @@ class MainActivity : ComponentActivity() {
|
||||
private lateinit var assembler: SessionAssembler
|
||||
|
||||
private var cameraProvider: ProcessCameraProvider? = null
|
||||
private var activeCamera: Camera? = null
|
||||
private var lastLockFocusAt = 0L
|
||||
private var lastLockFocusX = -1f
|
||||
private var lastLockFocusY = -1f
|
||||
private var currentAnalyzer: QrAnalyzer? = null
|
||||
private var qrLockOverlay: QrLockOverlay? = null
|
||||
private var scannerStatsText: TextView? = null
|
||||
private var scannerLockText: TextView? = null
|
||||
private var scannerMode = ScannerMode.NONE
|
||||
private var pendingScannerMode = ScannerMode.NONE
|
||||
private val pairConsumed = AtomicBoolean(false)
|
||||
@@ -126,8 +140,8 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
root.addView(modeCard(
|
||||
title = "电脑 → 手机",
|
||||
badge = "光学零网络 · 4码并行 · 60FPS显示",
|
||||
body = "手机摄像头连续读取电脑动态二维码。Wi-Fi、蓝牙、局域网和互联网都不参与文件数据传输。",
|
||||
badge = "光学零网络 · 单码锁定 · QFT2低密度字母数字QR · 最高60FPS显示",
|
||||
body = "手机先搜索并锁定一个大二维码,之后只分析锁定区域。QFT2 使用 Base45 让 QR 保持字母数字模式并降低模块密度;Wi-Fi、蓝牙、局域网和互联网都不参与文件数据传输。",
|
||||
buttonLabel = "开始光学接收",
|
||||
) { requestScanner(ScannerMode.OPTICAL) })
|
||||
root.addView(space(16))
|
||||
@@ -139,7 +153,7 @@ class MainActivity : ComponentActivity() {
|
||||
) { requestScanner(ScannerMode.PAIR) })
|
||||
root.addView(space(22))
|
||||
root.addView(text("本机设备:$receiverDeviceLabel", 13f, MUTED))
|
||||
root.addView(text("QFT v0.3.0-rc3 · Android 7+ 到最新", 12f, MUTED))
|
||||
root.addView(text("QFT v0.4.0-rc2 · Android 7+ 到最新", 12f, MUTED))
|
||||
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
|
||||
}
|
||||
|
||||
@@ -158,6 +172,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(markerClass = [ExperimentalCamera2Interop::class])
|
||||
private fun startScanner(mode: ScannerMode) {
|
||||
scannerMode = mode
|
||||
pairConsumed.set(false)
|
||||
@@ -166,19 +181,30 @@ class MainActivity : ComponentActivity() {
|
||||
future.addListener({
|
||||
val provider = future.get()
|
||||
cameraProvider = provider
|
||||
val preview = Preview.Builder().build().also { it.surfaceProvider = previewView.surfaceProvider }
|
||||
val profile = if (mode == ScannerMode.PAIR) QrAnalyzer.Profile.PAIR_FAST else QrAnalyzer.Profile.OPTICAL_MULTI
|
||||
val requestedFps = chooseCameraFpsRange()
|
||||
|
||||
// CameraX 1.4.x ImageAnalysis.Builder has no public setTargetFrameRate().
|
||||
// Apply a range actually advertised by the selected back camera via
|
||||
// Camera2Interop to both bound use cases.
|
||||
val previewBuilder = Preview.Builder()
|
||||
Camera2Interop.Extender(previewBuilder).setCaptureRequestOption(
|
||||
CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,
|
||||
requestedFps,
|
||||
)
|
||||
val preview = previewBuilder.build().also { it.surfaceProvider = previewView.surfaceProvider }
|
||||
|
||||
val profile = if (mode == ScannerMode.PAIR) QrAnalyzer.Profile.PAIR_FAST else QrAnalyzer.Profile.OPTICAL_LOCKED
|
||||
currentAnalyzer?.close()
|
||||
val analyzer = QrAnalyzer(
|
||||
profile = profile,
|
||||
onTexts = { values ->
|
||||
onCode = { code ->
|
||||
when (scannerMode) {
|
||||
ScannerMode.OPTICAL -> values.forEach(assembler::acceptText)
|
||||
ScannerMode.PAIR -> values.firstOrNull { PairingProtocol.isPairingText(it) }?.let(::acceptPairCode)
|
||||
ScannerMode.OPTICAL -> assembler.acceptText(code.text)
|
||||
ScannerMode.PAIR -> if (PairingProtocol.isPairingText(code.text)) acceptPairCode(code.text)
|
||||
ScannerMode.NONE -> Unit
|
||||
}
|
||||
},
|
||||
onStats = { cameraFps, decodedFps ->
|
||||
onStats = { cameraFps, decodedFps, distinctFps, decodeMs ->
|
||||
runOnUiThread {
|
||||
val quality = when (mode) {
|
||||
ScannerMode.PAIR -> when {
|
||||
@@ -187,38 +213,152 @@ class MainActivity : ComponentActivity() {
|
||||
else -> "相机帧率偏低" to WARNING
|
||||
}
|
||||
ScannerMode.OPTICAL -> when {
|
||||
decodedFps >= cameraFps.coerceAtLeast(1.0) * 1.5 -> "光学链路稳定" to SUCCESS
|
||||
decodedFps >= 5.0 -> "可接收 · 建议保持手机稳定" to ACCENT
|
||||
else -> "识别偏低 · 靠近屏幕或降低 Windows FPS" to WARNING
|
||||
distinctFps >= 18.0 -> "新帧吞吐良好" to SUCCESS
|
||||
distinctFps >= 8.0 -> "可接收 · 继续保持二维码稳定" to ACCENT
|
||||
decodedFps >= 8.0 -> "重复帧较多 · 尝试 Windows 30/45 FPS" to WARNING
|
||||
else -> "识别偏低 · 放大 Windows 二维码或降到 30 FPS" to WARNING
|
||||
}
|
||||
ScannerMode.NONE -> "空闲" to MUTED
|
||||
}
|
||||
scannerStatsText?.text = "%s · 相机 %.1f FPS · 有效 QR %.1f/s".format(quality.first, cameraFps, decodedFps)
|
||||
scannerStatsText?.text = if (mode == ScannerMode.OPTICAL) {
|
||||
"%s · 相机 %.1f FPS · 解码 %.1f/s · 新帧 %.1f/s · %.1fms/次".format(
|
||||
quality.first, cameraFps, decodedFps, distinctFps, decodeMs
|
||||
)
|
||||
} else {
|
||||
"%s · 相机 %.1f FPS · 解码 %.1f/s · %.1fms/次".format(quality.first, cameraFps, decodedFps, decodeMs)
|
||||
}
|
||||
scannerStatsText?.setTextColor(quality.second)
|
||||
}
|
||||
},
|
||||
onLock = { lock ->
|
||||
runOnUiThread {
|
||||
qrLockOverlay?.update(lock)
|
||||
if (mode == ScannerMode.OPTICAL) {
|
||||
if (lock.locked && lock.misses == 0) maybeRefocusLockedQr()
|
||||
scannerLockText?.text = if (lock.locked) {
|
||||
val lockHint = if (lock.misses == 0) "稳定锁定" else "保持锁定 · miss ${lock.misses}"
|
||||
"$lockHint · 仅分析 ${(lock.searchAreaFraction * 100f).toInt().coerceIn(1, 100)}% 画面"
|
||||
} else {
|
||||
"区域锁定:搜索中 · 让单个大二维码占取景框 50% 以上"
|
||||
}
|
||||
scannerLockText?.setTextColor(
|
||||
if (!lock.locked) ACCENT else if (lock.misses == 0) SUCCESS else WARNING
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
currentAnalyzer = analyzer
|
||||
val targetSize = if (mode == ScannerMode.PAIR) Size(640, 480) else Size(1280, 720)
|
||||
val analysis = ImageAnalysis.Builder()
|
||||
|
||||
// v0.4 single large QR is intentionally analyzed at 640x480. With the
|
||||
// QR occupying most of the view this still leaves several camera
|
||||
// pixels/module, while substantially reducing Y-copy + ZXing work.
|
||||
val targetSize = Size(640, 480)
|
||||
val analysisBuilder = ImageAnalysis.Builder()
|
||||
.setTargetResolution(targetSize)
|
||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||
.build()
|
||||
.also { it.setAnalyzer(cameraExecutor, analyzer) }
|
||||
Camera2Interop.Extender(analysisBuilder).setCaptureRequestOption(
|
||||
CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,
|
||||
requestedFps,
|
||||
)
|
||||
val analysis = analysisBuilder.build().also { it.setAnalyzer(cameraExecutor, analyzer) }
|
||||
|
||||
provider.unbindAll()
|
||||
val camera = provider.bindToLifecycle(this, CameraSelector.DEFAULT_BACK_CAMERA, preview, analysis)
|
||||
// Screen QR benefits from an immediate center AF/AE metering pass.
|
||||
try {
|
||||
val point = previewView.meteringPointFactory.createPoint(0.5f, 0.5f)
|
||||
val action = FocusMeteringAction.Builder(
|
||||
point,
|
||||
FocusMeteringAction.FLAG_AF or FocusMeteringAction.FLAG_AE,
|
||||
).setAutoCancelDuration(5, TimeUnit.SECONDS).build()
|
||||
camera.cameraControl.startFocusAndMetering(action)
|
||||
} catch (_: Exception) {}
|
||||
val camera = try {
|
||||
provider.bindToLifecycle(this, CameraSelector.DEFAULT_BACK_CAMERA, preview, analysis).also {
|
||||
scannerStatsText?.text = "相机请求 ${requestedFps.lower}~${requestedFps.upper} FPS · 等待首帧…"
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Some old/OEM devices advertise a Camera2 FPS range that is not
|
||||
// accepted together with the selected CameraX stream combination.
|
||||
// Retry without the explicit AE range rather than failing scanner
|
||||
// startup; KEEP_ONLY_LATEST + ROI still provides the fast path.
|
||||
provider.unbindAll()
|
||||
val fallbackPreview = Preview.Builder().build().also {
|
||||
it.surfaceProvider = previewView.surfaceProvider
|
||||
}
|
||||
val fallbackAnalysis = ImageAnalysis.Builder()
|
||||
.setTargetResolution(targetSize)
|
||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||
.build().also { it.setAnalyzer(cameraExecutor, analyzer) }
|
||||
scannerStatsText?.text = "设备拒绝显式高帧率请求 · 已回退相机自动 FPS · 等待首帧…"
|
||||
provider.bindToLifecycle(
|
||||
this,
|
||||
CameraSelector.DEFAULT_BACK_CAMERA,
|
||||
fallbackPreview,
|
||||
fallbackAnalysis,
|
||||
)
|
||||
}
|
||||
activeCamera = camera
|
||||
|
||||
previewView.post {
|
||||
if (previewView.width <= 0 || previewView.height <= 0) return@post
|
||||
try {
|
||||
val point = previewView.meteringPointFactory.createPoint(
|
||||
previewView.width * 0.5f,
|
||||
previewView.height * 0.5f,
|
||||
)
|
||||
val action = FocusMeteringAction.Builder(
|
||||
point,
|
||||
FocusMeteringAction.FLAG_AF or FocusMeteringAction.FLAG_AE,
|
||||
).setAutoCancelDuration(5, TimeUnit.SECONDS).build()
|
||||
camera.cameraControl.startFocusAndMetering(action)
|
||||
} catch (_: Exception) {}
|
||||
}
|
||||
}, mainExecutor)
|
||||
}
|
||||
|
||||
private fun maybeRefocusLockedQr() {
|
||||
val camera = activeCamera ?: return
|
||||
val center = qrLockOverlay?.lockedCenterInView() ?: return
|
||||
if (previewView.width <= 0 || previewView.height <= 0) return
|
||||
|
||||
// Do not force an AF/AE cycle every few seconds while the phone is
|
||||
// stationary: focus pumping can temporarily destroy QR contrast.
|
||||
// Re-meter only on the first lock or after the locked region moved
|
||||
// materially in the preview.
|
||||
val threshold = minOf(previewView.width, previewView.height) * 0.10f
|
||||
val dx = center.x - lastLockFocusX
|
||||
val dy = center.y - lastLockFocusY
|
||||
val moved = lastLockFocusX < 0f || dx * dx + dy * dy >= threshold * threshold
|
||||
if (!moved) return
|
||||
|
||||
val now = android.os.SystemClock.elapsedRealtime()
|
||||
if (now - lastLockFocusAt < 1200L) return
|
||||
lastLockFocusAt = now
|
||||
lastLockFocusX = center.x
|
||||
lastLockFocusY = center.y
|
||||
try {
|
||||
val point = previewView.meteringPointFactory.createPoint(center.x, center.y)
|
||||
val action = FocusMeteringAction.Builder(
|
||||
point,
|
||||
FocusMeteringAction.FLAG_AF or FocusMeteringAction.FLAG_AE,
|
||||
).setAutoCancelDuration(2, TimeUnit.SECONDS).build()
|
||||
camera.cameraControl.startFocusAndMetering(action)
|
||||
} catch (_: Exception) {}
|
||||
}
|
||||
|
||||
private fun chooseCameraFpsRange(): Range<Int> {
|
||||
return try {
|
||||
val manager = getSystemService(android.content.Context.CAMERA_SERVICE) as CameraManager
|
||||
val characteristics = manager.cameraIdList
|
||||
.asSequence()
|
||||
.map { manager.getCameraCharacteristics(it) }
|
||||
.firstOrNull { it.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK }
|
||||
val ranges = characteristics?.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)
|
||||
?.toList().orEmpty()
|
||||
ranges
|
||||
.filter { it.upper <= 60 && it.lower <= 30 }
|
||||
.maxWithOrNull(compareBy<Range<Int>> { it.upper }.thenBy { it.lower })
|
||||
?: ranges.filter { it.upper <= 60 }
|
||||
.maxWithOrNull(compareBy<Range<Int>> { it.upper }.thenBy { it.lower })
|
||||
?: ranges.maxWithOrNull(compareBy<Range<Int>> { it.upper }.thenBy { it.lower })
|
||||
?: Range(30, 30)
|
||||
} catch (_: Exception) {
|
||||
Range(30, 30)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildCameraUi(mode: ScannerMode): FrameLayout {
|
||||
val root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
|
||||
previewView = PreviewView(this).apply {
|
||||
@@ -226,6 +366,8 @@ class MainActivity : ComponentActivity() {
|
||||
scaleType = PreviewView.ScaleType.FILL_CENTER
|
||||
}
|
||||
root.addView(previewView, FrameLayout.LayoutParams(-1, -1))
|
||||
qrLockOverlay = QrLockOverlay(this)
|
||||
root.addView(qrLockOverlay, FrameLayout.LayoutParams(-1, -1))
|
||||
|
||||
val top = LinearLayout(this).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
@@ -245,20 +387,25 @@ class MainActivity : ComponentActivity() {
|
||||
background = rounded(0xE80C0E12.toInt(), 18)
|
||||
}
|
||||
deviceText = text(
|
||||
if (mode == ScannerMode.OPTICAL) "接收设备:$receiverDeviceLabel\n发送设备:等待 QFT1 MANIFEST…"
|
||||
if (mode == ScannerMode.OPTICAL) "接收设备:$receiverDeviceLabel\n发送设备:等待 QFT2 MANIFEST…"
|
||||
else "目标:等待 QFTPAIR2 配对二维码",
|
||||
14f, Color.WHITE
|
||||
)
|
||||
statusText = text(
|
||||
if (mode == ScannerMode.OPTICAL) "把电脑动态二维码完整放进取景框"
|
||||
if (mode == ScannerMode.OPTICAL) "让电脑的单个大二维码占取景框 50% 以上,识别后会自动锁定区域"
|
||||
else "扫描 Windows“手机传电脑”页面上的二维码",
|
||||
14f, MUTED
|
||||
)
|
||||
progress = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000; progress = 0 }
|
||||
panel.addView(deviceText)
|
||||
panel.addView(statusText, matchWrap(top = 7))
|
||||
scannerLockText = text(
|
||||
if (mode == ScannerMode.OPTICAL) "区域锁定:搜索中" else "配对识别:快速模式",
|
||||
12f, ACCENT
|
||||
)
|
||||
panel.addView(scannerLockText, matchWrap(top = 6))
|
||||
scannerStatsText = text("相机分析:等待首帧…", 12f, ACCENT)
|
||||
panel.addView(scannerStatsText, matchWrap(top = 6))
|
||||
panel.addView(scannerStatsText, matchWrap(top = 4))
|
||||
panel.addView(progress, LinearLayout.LayoutParams(-1, dp(8)).apply { topMargin = dp(12) })
|
||||
root.addView(panel, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM).apply {
|
||||
leftMargin = dp(12); rightMargin = dp(12); bottomMargin = dp(12)
|
||||
@@ -514,9 +661,16 @@ class MainActivity : ComponentActivity() {
|
||||
private fun stopCamera() {
|
||||
try { cameraProvider?.unbindAll() } catch (_: Exception) {}
|
||||
cameraProvider = null
|
||||
activeCamera = null
|
||||
lastLockFocusAt = 0L
|
||||
lastLockFocusX = -1f
|
||||
lastLockFocusY = -1f
|
||||
currentAnalyzer?.close()
|
||||
currentAnalyzer = null
|
||||
qrLockOverlay?.clear()
|
||||
qrLockOverlay = null
|
||||
scannerStatsText = null
|
||||
scannerLockText = null
|
||||
scannerMode = ScannerMode.NONE
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user