fix: make the pairing QR scanner actually see dense codes

The scanner read frames at 480p, which is thin for the web UI's dense
pairing QR (1024px, low error correction, a two-module quiet zone), and it
rejected a Y plane whose last row has no padding even though some cameras
return exactly rowStride * (height - 1) + width bytes — on those devices
every frame was dropped, so nothing ever reacted.

Frames are now requested at 720p and fall back to 480p only when the device
refuses the higher analysis size; a stream that fails to start reports an
error instead of leaving a silent preview. Decoding runs with zxing's
tryHarder hint and retries an inverted frame for light-on-dark codes.

The screen also reports what it sees: resolution/format and a live
"frames scanned / decode attempts" line, a one-time log of the first frame's
planes, row stride and byte count, a no-frames hint after four seconds, and a
"move closer" hint when frames decode but no QR is found.

0.4.6 (406).
This commit is contained in:
blumia committed 2026-11-23 12:26:16 +08:00
1 parent 8f6fd99103
commit 91bf5e5b81
7 files changed
+194 -39

No files matched your search

+13
View File
@@ -5,6 +5,19 @@
--- ---
## 0.4.6 扫码无反应的修复与诊断(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 原因候选 | 0.4.5 以 480p 取流,配对二维码很密(网页端 1024px、L 级纠错、只有 2 个模块的静区),模块在画面里可能小于 zxing 能识别的尺寸;另外部分设备的 Y 平面最后一帧不含行尾 padding(长度为 `rowStride*(h-1)+w`),旧代码会直接丢弃所有帧 |
| 取流 | 先请求 720p(`ResolutionPreset.high`),失败才退回 480p;取流失败不再静默显示预览,而是显示错误;4 秒没有帧时提示「没有收到相机画面」 |
| 解码 | zxing 加 `tryHarder`;正常解码失败后再用 `InvertedLuminanceSource` 试一次反色(深色卡片上的浅色二维码);Y 平面允许最后一帧缺少 padding |
| 诊断 | 扫描页底部显示「1280×720 yuv420 · 已扫描 N 帧 / 解码 M 次」;首帧通过 `debugPrint` 记录分辨率/planes/rowStride/像素步长/字节数,解码异常也会记录一次 |
| 测试 | `test/qr_scan_test.dart` 增加最后一帧无 padding、反色二维码两项;全部通过 |
| 版本 | **0.4.6(code 406)** |
---
## 0.4.5 扫码配对(分支 `flutter`) ## 0.4.5 扫码配对(分支 `flutter`)
| 项 | 结果 | | 项 | 结果 |
+1 -1
View File
@@ -5,7 +5,7 @@ Android first. This branch (`flutter`) is a framework evaluation: the same
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity. Flutter to compare mobile UI maturity.
Status: 0.4.5 — servers (passwordless / password login, HTTP/HTTPS and Status: 0.4.6 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
over the OpenChamber private relay with end-to-end encryption; the pairing over the OpenChamber private relay with end-to-end encryption; the pairing
link is pasted or scanned with the camera), session list with search and live link is pasted or scanned with the camera), session list with search and live
+20 -5
View File
@@ -33,11 +33,22 @@ String? decodeQrFrame(QrFrame frame) => decodeQrLuminance(
String? decodeQrLuminance( String? decodeQrLuminance(
Uint8List luminance, int width, int height, int rowStride) { Uint8List luminance, int width, int height, int rowStride) {
if (width <= 0 || height <= 0 || rowStride < width) return null; if (width <= 0 || height <= 0 || rowStride < width) return null;
if (luminance.length < rowStride * height) return null; // The camera's Y plane may omit the padding of its last row, so the buffer
// can be one row shorter than rowStride * height.
if (luminance.length < rowStride * (height - 1) + width) return null;
final source = _PlaneLuminanceSource(luminance, width, height, rowStride);
final direct = _read(source);
if (direct != null) return direct;
// A pairing QR drawn light-on-dark (a dark card in the web UI) is still a
// QR: try the inverted frame before giving up on it.
return _read(InvertedLuminanceSource(source));
}
String? _read(LuminanceSource source) {
try { try {
final source = _PlaneLuminanceSource(luminance, width, height, rowStride);
final bitmap = BinaryBitmap(HybridBinarizer(source)); final bitmap = BinaryBitmap(HybridBinarizer(source));
return QRCodeReader().decode(bitmap).text; final hints = DecodeHints()..put(DecodeHintType.tryHarder);
return QRCodeReader().decode(bitmap, hints: hints).text;
} on ReaderException { } on ReaderException {
return null; return null;
} catch (_) { } catch (_) {
@@ -77,7 +88,9 @@ class _PlaneLuminanceSource extends LuminanceSource {
Int8List getRow(int y, Int8List? row) { Int8List getRow(int y, Int8List? row) {
final out = (row != null && row.length >= width) ? row : Int8List(width); final out = (row != null && row.length >= width) ? row : Int8List(width);
final base = y * rowStride; final base = y * rowStride;
for (var x = 0; x < width; x++) { final available = data.length - base;
final count = available < width ? available : width;
for (var x = 0; x < count; x++) {
out[x] = data[base + x].toSigned(8); out[x] = data[base + x].toSigned(8);
} }
return out; return out;
@@ -89,7 +102,9 @@ class _PlaneLuminanceSource extends LuminanceSource {
for (var y = 0; y < height; y++) { for (var y = 0; y < height; y++) {
final base = y * rowStride; final base = y * rowStride;
final target = y * width; final target = y * width;
for (var x = 0; x < width; x++) { final available = data.length - base;
final count = available < width ? available : width;
for (var x = 0; x < count; x++) {
out[target + x] = data[base + x].toSigned(8); out[target + x] = data[base + x].toSigned(8);
} }
} }
+126 -31
View File
@@ -34,6 +34,16 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
bool _found = false; bool _found = false;
bool _torch = false; bool _torch = false;
Timer? _hintTimer; Timer? _hintTimer;
Timer? _watchdog;
Timer? _slowHint;
/// Frame diagnostics: a scanner that silently does nothing is impossible to
/// tell apart from a camera that sends no frames without these.
int _frames = 0;
int _decodeAttempts = 0;
int _decodeErrors = 0;
bool _loggedFrame = false;
String? _frameShape;
@override @override
void initState() { void initState() {
@@ -44,6 +54,8 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
@override @override
void dispose() { void dispose() {
_hintTimer?.cancel(); _hintTimer?.cancel();
_watchdog?.cancel();
_slowHint?.cancel();
_closeCamera(); _closeCamera();
super.dispose(); super.dispose();
} }
@@ -57,55 +69,118 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
} }
Future<void> _start() async { Future<void> _start() async {
_closeCamera();
_watchdog?.cancel();
_hintTimer?.cancel();
_slowHint?.cancel();
_frames = 0;
_decodeAttempts = 0;
_decodeErrors = 0;
_loggedFrame = false;
_frameShape = null;
setState(() { setState(() {
_error = null; _error = null;
_hint = null;
_found = false; _found = false;
}); });
final List<CameraDescription> cameras;
try { try {
final cameras = await availableCameras(); cameras = await availableCameras();
if (cameras.isEmpty) { } on CameraException catch (error) {
if (mounted) setState(() => _error = '没有可用的相机'); if (mounted) setState(() => _error = _cameraError(error));
return; return;
} }
CameraDescription pick = cameras.first; if (cameras.isEmpty) {
for (final camera in cameras) { if (mounted) setState(() => _error = '没有可用的相机');
if (camera.lensDirection == CameraLensDirection.back) { return;
pick = camera; }
break; CameraDescription pick = cameras.first;
} for (final camera in cameras) {
if (camera.lensDirection == CameraLensDirection.back) {
pick = camera;
break;
} }
}
// A dense pairing QR needs pixels: 720p first, then 480p for cameras or
// devices that refuse the higher analysis size.
Object? lastError;
for (final preset in const [ResolutionPreset.high, ResolutionPreset.medium]) {
final controller = CameraController( final controller = CameraController(
pick, pick,
ResolutionPreset.medium, preset,
enableAudio: false, enableAudio: false,
imageFormatGroup: ImageFormatGroup.yuv420, imageFormatGroup: ImageFormatGroup.yuv420,
); );
await controller.initialize(); try {
if (!mounted) { await controller.initialize();
await controller.dispose(); if (!mounted) {
await controller.dispose();
return;
}
setState(() => _controller = controller);
await controller.startImageStream(_onFrame);
_watchdog = Timer(const Duration(seconds: 4), () {
if (!mounted || _frames > 0 || _error != null) return;
setState(() => _hint = '没有收到相机画面,请关闭后重试');
});
_slowHint = Timer(const Duration(seconds: 12), () {
if (!mounted || _found || _frames == 0) return;
_showHint('还没识别到二维码,试着靠近一点或让二维码占满取景框', sticky: true);
});
return; return;
} catch (error) {
lastError = error;
try {
await controller.stopImageStream();
} catch (_) {}
try {
await controller.dispose();
} catch (_) {}
if (mounted && _controller == controller) {
setState(() => _controller = null);
}
} }
setState(() => _controller = controller);
await controller.startImageStream(_onFrame);
} on CameraException catch (error) {
if (!mounted) return;
setState(() {
_error = error.code == 'CameraAccessDenied'
? '需要相机权限才能扫码。请在系统设置里允许 OpenChamber 使用相机。'
: '无法打开相机:${error.description ?? error.code}';
});
} catch (error) {
if (mounted) setState(() => _error = '无法打开相机:$error');
} }
if (mounted) setState(() => _error = _cameraError(lastError));
}
String _cameraError(Object? error) {
if (error is CameraException) {
if (error.code == 'CameraAccessDenied' ||
error.code == 'CameraAccessDeniedWithoutPrompt' ||
error.code == 'CameraAccessRestricted') {
return '需要相机权限才能扫码。请在系统设置里允许 OpenChamber 使用相机。';
}
return '无法打开相机:${error.description ?? error.code}';
}
return '无法打开相机:$error';
} }
void _onFrame(CameraImage image) { void _onFrame(CameraImage image) {
_frames += 1;
if (!_loggedFrame && image.planes.isNotEmpty) {
_loggedFrame = true;
final plane = image.planes.first;
_frameShape =
'${image.width}×${image.height} ${image.format.group.name}';
debugPrint('qr: frame ${image.width}x${image.height} '
'${image.format.group.name} planes=${image.planes.length} '
'row=${plane.bytesPerRow} pixel=${plane.bytesPerPixel} '
'bytes=${plane.bytes.length}');
}
if (mounted && _frames % 10 == 0) {
// Refresh the small diagnostics line without rebuilding 30x a second.
setState(() {});
}
if (_decoding || _found || !mounted) return; if (_decoding || _found || !mounted) return;
final frame = _frameOf(image); final frame = _frameOf(image);
if (frame == null) return; if (frame == null) return;
_decoding = true; _decoding = true;
// Decoding off the UI thread: a 480p frame is cheap, but not free, and _decodeAttempts += 1;
// camera frames arrive at 30/s. // Decoding off the UI thread: frames arrive at 30/s and a decode is not
// free, so only one is in flight at a time.
compute(decodeQrFrame, frame).then((text) { compute(decodeQrFrame, frame).then((text) {
_decoding = false; _decoding = false;
if (!mounted || text == null || _found) return; if (!mounted || text == null || _found) return;
@@ -114,8 +189,13 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
} else { } else {
_showHint('这不是 OpenChamber 配对二维码'); _showHint('这不是 OpenChamber 配对二维码');
} }
}).catchError((_) { }).catchError((Object error) {
_decoding = false; _decoding = false;
_decodeErrors += 1;
if (_decodeErrors == 1) {
debugPrint('qr: decode failed: $error');
if (mounted) _showHint('二维码解码出错,请重试');
}
}); });
} }
@@ -142,9 +222,10 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
); );
} }
void _showHint(String text) { void _showHint(String text, {bool sticky = false}) {
_hintTimer?.cancel(); _hintTimer?.cancel();
if (mounted) setState(() => _hint = text); if (mounted) setState(() => _hint = text);
if (sticky) return;
_hintTimer = Timer(const Duration(seconds: 2), () { _hintTimer = Timer(const Duration(seconds: 2), () {
if (mounted) setState(() => _hint = null); if (mounted) setState(() => _hint = null);
}); });
@@ -173,7 +254,8 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final controller = _controller; final controller = _controller;
final ready = controller != null && controller.value.isInitialized; final ready =
controller != null && controller.value.isInitialized && _error == null;
return Scaffold( return Scaffold(
backgroundColor: Colors.black, backgroundColor: Colors.black,
body: Stack( body: Stack(
@@ -242,6 +324,19 @@ class _ScanQrScreenState extends State<ScanQrScreen> {
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: TextStyle(color: Colors.white60, fontSize: 12), style: TextStyle(color: Colors.white60, fontSize: 12),
), ),
if (ready && _frames > 0)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
'${_frameShape ?? ''} · 已扫描 $_frames 帧 / 解码 $_decodeAttempts 次',
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white38,
fontSize: 11,
fontFeatures: [FontFeature.tabularFigures()],
),
),
),
], ],
), ),
), ),
+1 -1
View File
@@ -1,2 +1,2 @@
/// The app version sent to the server in pairing and relay handshakes. /// The app version sent to the server in pairing and relay handshakes.
const appVersion = '0.4.5'; const appVersion = '0.4.6';
+1 -1
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones." description: "A lightweight OpenChamber client for phones."
publish_to: 'none' publish_to: 'none'
version: 0.4.5+405 version: 0.4.6+406
environment: environment:
sdk: ^3.14.0 sdk: ^3.14.0
+32
View File
@@ -80,6 +80,38 @@ void main() {
expect(decodeQrLuminance(image, size, size, size + pad), link); expect(decodeQrLuminance(image, size, size, size + pad), link);
}); });
test('a last row without its padding still decodes', () {
const scale = 6;
const quiet = 4;
const pad = 12;
final code = QrCode(
payload: QrPayload.fromString(link),
errorCorrectLevel: QrErrorCorrectLevel.medium,
);
final size = (code.moduleCount + quiet * 2) * scale;
final stride = size + pad;
final full = _qrImage(link, scale: scale, quiet: quiet, pad: pad);
// Some cameras return rowStride * (height - 1) + width bytes: the padding
// after the final row is simply not there.
final short = Uint8List(stride * (size - 1) + size)
..setRange(0, stride * (size - 1) + size, full);
expect(decodeQrLuminance(short, size, size, stride), link);
});
test('a light-on-dark QR decodes through the inverted fallback', () {
const scale = 6;
const quiet = 4;
final code = QrCode(
payload: QrPayload.fromString(link),
errorCorrectLevel: QrErrorCorrectLevel.medium,
);
final size = (code.moduleCount + quiet * 2) * scale;
final normal = _qrImage(link, scale: scale, quiet: quiet);
final inverted = Uint8List.fromList(
[for (final value in normal) 255 - value]);
expect(decodeQrLuminance(inverted, size, size, size), link);
});
test('a frame without a QR code yields null', () { test('a frame without a QR code yields null', () {
final blank = Uint8List(320 * 240)..fillRange(0, 320 * 240, 255); final blank = Uint8List(320 * 240)..fillRange(0, 320 * 240, 255);
expect(decodeQrLuminance(blank, 320, 240, 320), isNull); expect(decodeQrLuminance(blank, 320, 240, 320), isNull);