fix direct pairing probe timeout and speed up QR scanning
This commit is contained in:
@@ -310,10 +310,10 @@ class MainActivity : ComponentActivity() {
|
|||||||
)
|
)
|
||||||
currentAnalyzer = analyzer
|
currentAnalyzer = analyzer
|
||||||
|
|
||||||
// v0.4 single large QR is intentionally analyzed at 640x480. With the
|
// Pairing QR codes carry network/file metadata and can be much denser
|
||||||
// QR occupying most of the view this still leaves several camera
|
// than one optical QFT2 frame. Give PAIR_FAST more sensor pixels per
|
||||||
// pixels/module, while substantially reducing Y-copy + ZXing work.
|
// module; the continuous optical path stays at 640x480 to preserve FPS.
|
||||||
val targetSize = Size(640, 480)
|
val targetSize = if (mode == ScannerMode.PAIR) Size(960, 720) else Size(640, 480)
|
||||||
val analysisBuilder = ImageAnalysis.Builder()
|
val analysisBuilder = ImageAnalysis.Builder()
|
||||||
.setTargetResolution(targetSize)
|
.setTargetResolution(targetSize)
|
||||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||||
|
|||||||
@@ -124,26 +124,29 @@ class QrAnalyzer(
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
// Acquisition is center-first, but unlike the old path it establishes
|
// Pairing needs one reliable first hit, not sustained decode FPS. Keep a
|
||||||
// a QR ROI immediately after the first hit. Full-frame work is only a
|
// generous center crop so a large desktop QR is not clipped at the quiet
|
||||||
// recovery path for deliberately off-center QR codes.
|
// zone, and prefer Hybrid thresholding on every frame: it is markedly
|
||||||
val center = LockRect.centeredSearch(image.width, image.height, 0.82f)
|
// more tolerant of monitor glare, PWM bands and uneven exposure.
|
||||||
|
val center = LockRect.centeredSearch(image.width, image.height, 0.92f)
|
||||||
val centered = grayBuffer.capture(image, center)
|
val centered = grayBuffer.capture(image, center)
|
||||||
decodeDense(centered, hybrid = false)?.let { result ->
|
decodeDense(centered, hybrid = true)?.let { result ->
|
||||||
updatePairRegion(result, centered)
|
updatePairRegion(result, centered)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
if (frameCounter % 3L == 0L) {
|
// Global thresholding remains a cheap fallback for very clean displays,
|
||||||
decodeDense(centered, hybrid = true)?.let { result ->
|
// but no longer delays the robust path until the third camera frame.
|
||||||
|
if (frameCounter % 2L == 0L) {
|
||||||
|
decodeDense(centered, hybrid = false)?.let { result ->
|
||||||
updatePairRegion(result, centered)
|
updatePairRegion(result, centered)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (frameCounter % 4L == 0L) {
|
if (frameCounter % 3L == 0L) {
|
||||||
val full = grayBuffer.capture(image)
|
val full = grayBuffer.capture(image)
|
||||||
decodeDense(full, hybrid = false)?.let { result ->
|
decodeDense(full, hybrid = true)?.let { result ->
|
||||||
updatePairRegion(result, full)
|
updatePairRegion(result, full)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,6 +30,33 @@ data class SelectedFile(
|
|||||||
val uploadKey: String = UUID.randomUUID().toString(),
|
val uploadKey: String = UUID.randomUUID().toString(),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wait for completed probes, rather than counting empty queue polls as failed
|
||||||
|
* addresses. This matters immediately after joining QFT Direct: the first ARP
|
||||||
|
* and Windows firewall transition can take longer than a short poll slice even
|
||||||
|
* though the authenticated HTTP request is already reaching the desktop.
|
||||||
|
*/
|
||||||
|
internal fun <T> awaitFirstNonNull(
|
||||||
|
completion: ExecutorCompletionService<T?>,
|
||||||
|
submitted: Int,
|
||||||
|
timeoutMs: Long,
|
||||||
|
): T? {
|
||||||
|
val deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMs.coerceAtLeast(0L))
|
||||||
|
var completed = 0
|
||||||
|
while (completed < submitted) {
|
||||||
|
val remainingNanos = deadline - System.nanoTime()
|
||||||
|
if (remainingNanos <= 0L) return null
|
||||||
|
val future = completion.poll(remainingNanos, TimeUnit.NANOSECONDS) ?: return null
|
||||||
|
completed += 1
|
||||||
|
try {
|
||||||
|
future.get()?.let { return it }
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// One broken address must not discard successful probes still queued.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
object UploadClient {
|
object UploadClient {
|
||||||
private const val TAG = "QftUpload"
|
private const val TAG = "QftUpload"
|
||||||
private const val DISCOVERY_PORT = 39392
|
private const val DISCOVERY_PORT = 39392
|
||||||
@@ -203,15 +230,11 @@ object UploadClient {
|
|||||||
return try {
|
return try {
|
||||||
val overallMs = (connectMs + readMs + 150).toLong() *
|
val overallMs = (connectMs + readMs + 150).toLong() *
|
||||||
((candidates.size + workers - 1) / workers).coerceAtLeast(1)
|
((candidates.size + workers - 1) / workers).coerceAtLeast(1)
|
||||||
val deadline = android.os.SystemClock.elapsedRealtime() + overallMs.coerceAtMost(2_400L)
|
awaitFirstNonNull(
|
||||||
repeat(candidates.size) {
|
completion = completion,
|
||||||
val remaining = deadline - android.os.SystemClock.elapsedRealtime()
|
submitted = candidates.size,
|
||||||
if (remaining <= 0) return null
|
timeoutMs = overallMs.coerceAtMost(2_400L),
|
||||||
val future = completion.poll(remaining.coerceAtMost(350L), TimeUnit.MILLISECONDS) ?: return@repeat
|
)
|
||||||
val result = future.get()
|
|
||||||
if (result != null) return result
|
|
||||||
}
|
|
||||||
null
|
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
null
|
null
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -4,9 +4,51 @@ import org.junit.Assert.*
|
|||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
import java.nio.ByteBuffer
|
import java.nio.ByteBuffer
|
||||||
import java.nio.ByteOrder
|
import java.nio.ByteOrder
|
||||||
|
import java.util.concurrent.Callable
|
||||||
|
import java.util.concurrent.ExecutorCompletionService
|
||||||
|
import java.util.concurrent.Executors
|
||||||
import java.util.zip.CRC32
|
import java.util.zip.CRC32
|
||||||
|
|
||||||
class ProtocolTest {
|
class ProtocolTest {
|
||||||
|
@Test
|
||||||
|
fun probeCompletionWaitsForARealResultInsteadOfConsumingAnEmptyPoll() {
|
||||||
|
val pool = Executors.newSingleThreadExecutor()
|
||||||
|
try {
|
||||||
|
val completion = ExecutorCompletionService<String?>(pool)
|
||||||
|
completion.submit(Callable {
|
||||||
|
Thread.sleep(380)
|
||||||
|
"http://192.168.137.1:39393"
|
||||||
|
})
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"http://192.168.137.1:39393",
|
||||||
|
awaitFirstNonNull(completion, submitted = 1, timeoutMs = 800),
|
||||||
|
)
|
||||||
|
} finally {
|
||||||
|
pool.shutdownNow()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun probeCompletionKeepsWaitingAfterAnEarlierAddressFails() {
|
||||||
|
val pool = Executors.newFixedThreadPool(2)
|
||||||
|
try {
|
||||||
|
val completion = ExecutorCompletionService<String?>(pool)
|
||||||
|
completion.submit(Callable { null })
|
||||||
|
completion.submit(Callable {
|
||||||
|
Thread.sleep(30)
|
||||||
|
"http://192.168.137.1:39393"
|
||||||
|
})
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"http://192.168.137.1:39393",
|
||||||
|
awaitFirstNonNull(completion, submitted = 2, timeoutMs = 500),
|
||||||
|
)
|
||||||
|
} finally {
|
||||||
|
pool.shutdownNow()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun routeCandidatesOnlyKeepEndpointsOnTheActiveSubnet() {
|
fun routeCandidatesOnlyKeepEndpointsOnTheActiveSubnet() {
|
||||||
val endpoints = listOf(
|
val endpoints = listOf(
|
||||||
|
|||||||
@@ -1109,6 +1109,9 @@ impl QftApp {
|
|||||||
self.receive.direct_ap = direct_ap;
|
self.receive.direct_ap = direct_ap;
|
||||||
self.receive.events = Some(rx);
|
self.receive.events = Some(rx);
|
||||||
self.receive.pair_texture = Some(ctx.load_texture("qft-pair-code", image, TextureOptions::NEAREST));
|
self.receive.pair_texture = Some(ctx.load_texture("qft-pair-code", image, TextureOptions::NEAREST));
|
||||||
|
// 扫码是启动后的唯一下一步,默认把窗口让给大二维码;用户仍可退出
|
||||||
|
// 专注模式查看防火墙、地址和接收状态。
|
||||||
|
self.receive.focus_qr = true;
|
||||||
self.receive.session_token = token;
|
self.receive.session_token = token;
|
||||||
self.receive.connected_device = "等待 Android 扫码".into();
|
self.receive.connected_device = "等待 Android 扫码".into();
|
||||||
self.receive.current_file = "—".into();
|
self.receive.current_file = "—".into();
|
||||||
@@ -1190,6 +1193,9 @@ impl QftApp {
|
|||||||
self.send.direct_ap = direct_ap;
|
self.send.direct_ap = direct_ap;
|
||||||
self.send.events = Some(rx);
|
self.send.events = Some(rx);
|
||||||
self.send.pair_texture = Some(ctx.load_texture("qft-send-code", image, TextureOptions::NEAREST));
|
self.send.pair_texture = Some(ctx.load_texture("qft-send-code", image, TextureOptions::NEAREST));
|
||||||
|
// QFTSEND2 往往还带文件名、大小和 SHA-256,比接收码更密;生成后
|
||||||
|
// 直接放大显示,避免控制区把模块压到手机相机的识别下限附近。
|
||||||
|
self.send.qr_focus = true;
|
||||||
self.send.session_token = token;
|
self.send.session_token = token;
|
||||||
self.send.connected_device = "等待 Android 扫码".into();
|
self.send.connected_device = "等待 Android 扫码".into();
|
||||||
self.send.status = if self.send.use_direct_ap {
|
self.send.status = if self.send.use_direct_ap {
|
||||||
|
|||||||
+15
-2
@@ -3,6 +3,7 @@ use eframe::egui::ColorImage;
|
|||||||
use qrcode::{types::Color, EcLevel, QrCode};
|
use qrcode::{types::Color, EcLevel, QrCode};
|
||||||
|
|
||||||
const QUIET_MODULES: usize = 4;
|
const QUIET_MODULES: usize = 4;
|
||||||
|
const PAIR_EC_LEVEL: EcLevel = EcLevel::L;
|
||||||
|
|
||||||
/// Active optical renderer. QFT2/Base45 text uses only QR alphanumeric
|
/// Active optical renderer. QFT2/Base45 text uses only QR alphanumeric
|
||||||
/// characters, allowing the QR encoder to choose a compact alphanumeric data
|
/// characters, allowing the QR encoder to choose a compact alphanumeric data
|
||||||
@@ -16,9 +17,11 @@ pub fn render_qr_fitted(text: &str, target_side: usize) -> Result<ColorImage> {
|
|||||||
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
|
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pairing QR stays static and uses M error correction for first-scan reliability.
|
/// Pairing happens from a clean, static desktop display. QR-L keeps long
|
||||||
|
/// QFTSEND2 payloads several versions smaller than QR-M, giving the camera
|
||||||
|
/// materially more pixels per module; the full quiet zone remains intact.
|
||||||
pub fn render_pair_qr(text: &str, target_side: usize) -> Result<ColorImage> {
|
pub fn render_pair_qr(text: &str, target_side: usize) -> Result<ColorImage> {
|
||||||
let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::M)
|
let code = QrCode::with_error_correction_level(text.as_bytes(), PAIR_EC_LEVEL)
|
||||||
.context("pair QR payload too large")?;
|
.context("pair QR payload too large")?;
|
||||||
let modules = code.width() + QUIET_MODULES * 2;
|
let modules = code.width() + QUIET_MODULES * 2;
|
||||||
let scale = (target_side / modules).max(1);
|
let scale = (target_side / modules).max(1);
|
||||||
@@ -26,6 +29,16 @@ pub fn render_pair_qr(text: &str, target_side: usize) -> Result<ColorImage> {
|
|||||||
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
|
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pairing_qr_uses_low_density_error_correction() {
|
||||||
|
assert_eq!(PAIR_EC_LEVEL, EcLevel::L);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn render_code_gray(code: &QrCode, side: usize) -> Vec<u8> {
|
fn render_code_gray(code: &QrCode, side: usize) -> Vec<u8> {
|
||||||
let qr_width = code.width();
|
let qr_width = code.width();
|
||||||
let modules = qr_width + QUIET_MODULES * 2;
|
let modules = qr_width + QUIET_MODULES * 2;
|
||||||
|
|||||||
Reference in New Issue
Block a user