diff --git a/PLAN.md b/PLAN.md index 9bf2381..4d6201f 100644 --- a/PLAN.md +++ b/PLAN.md @@ -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`) | 项 | 结果 | diff --git a/README.md b/README.md index 3da9603..ba53689 100644 --- a/README.md +++ b/README.md @@ -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 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 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 diff --git a/lib/api/qr_scan.dart b/lib/api/qr_scan.dart index 8531ba6..9a39708 100644 --- a/lib/api/qr_scan.dart +++ b/lib/api/qr_scan.dart @@ -33,11 +33,22 @@ String? decodeQrFrame(QrFrame frame) => decodeQrLuminance( String? decodeQrLuminance( Uint8List luminance, int width, int height, int rowStride) { 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 { - final source = _PlaneLuminanceSource(luminance, width, height, rowStride); 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 { return null; } catch (_) { @@ -77,7 +88,9 @@ class _PlaneLuminanceSource extends LuminanceSource { Int8List getRow(int y, Int8List? row) { final out = (row != null && row.length >= width) ? row : Int8List(width); 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); } return out; @@ -89,7 +102,9 @@ class _PlaneLuminanceSource extends LuminanceSource { for (var y = 0; y < height; y++) { final base = y * rowStride; 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); } } diff --git a/lib/screens/scan_qr_screen.dart b/lib/screens/scan_qr_screen.dart index 784ffb7..044e649 100644 --- a/lib/screens/scan_qr_screen.dart +++ b/lib/screens/scan_qr_screen.dart @@ -34,6 +34,16 @@ class _ScanQrScreenState extends State { bool _found = false; bool _torch = false; 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 void initState() { @@ -44,6 +54,8 @@ class _ScanQrScreenState extends State { @override void dispose() { _hintTimer?.cancel(); + _watchdog?.cancel(); + _slowHint?.cancel(); _closeCamera(); super.dispose(); } @@ -57,55 +69,118 @@ class _ScanQrScreenState extends State { } Future _start() async { + _closeCamera(); + _watchdog?.cancel(); + _hintTimer?.cancel(); + _slowHint?.cancel(); + _frames = 0; + _decodeAttempts = 0; + _decodeErrors = 0; + _loggedFrame = false; + _frameShape = null; setState(() { _error = null; + _hint = null; _found = false; }); + + final List cameras; try { - final cameras = await availableCameras(); - if (cameras.isEmpty) { - if (mounted) setState(() => _error = '没有可用的相机'); - return; - } - CameraDescription pick = cameras.first; - for (final camera in cameras) { - if (camera.lensDirection == CameraLensDirection.back) { - pick = camera; - break; - } + cameras = await availableCameras(); + } on CameraException catch (error) { + if (mounted) setState(() => _error = _cameraError(error)); + return; + } + if (cameras.isEmpty) { + if (mounted) setState(() => _error = '没有可用的相机'); + return; + } + 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( pick, - ResolutionPreset.medium, + preset, enableAudio: false, imageFormatGroup: ImageFormatGroup.yuv420, ); - await controller.initialize(); - if (!mounted) { - await controller.dispose(); + try { + await controller.initialize(); + 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; + } 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) { + _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; final frame = _frameOf(image); if (frame == null) return; _decoding = true; - // Decoding off the UI thread: a 480p frame is cheap, but not free, and - // camera frames arrive at 30/s. + _decodeAttempts += 1; + // 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) { _decoding = false; if (!mounted || text == null || _found) return; @@ -114,8 +189,13 @@ class _ScanQrScreenState extends State { } else { _showHint('这不是 OpenChamber 配对二维码'); } - }).catchError((_) { + }).catchError((Object error) { _decoding = false; + _decodeErrors += 1; + if (_decodeErrors == 1) { + debugPrint('qr: decode failed: $error'); + if (mounted) _showHint('二维码解码出错,请重试'); + } }); } @@ -142,9 +222,10 @@ class _ScanQrScreenState extends State { ); } - void _showHint(String text) { + void _showHint(String text, {bool sticky = false}) { _hintTimer?.cancel(); if (mounted) setState(() => _hint = text); + if (sticky) return; _hintTimer = Timer(const Duration(seconds: 2), () { if (mounted) setState(() => _hint = null); }); @@ -173,7 +254,8 @@ class _ScanQrScreenState extends State { @override Widget build(BuildContext context) { final controller = _controller; - final ready = controller != null && controller.value.isInitialized; + final ready = + controller != null && controller.value.isInitialized && _error == null; return Scaffold( backgroundColor: Colors.black, body: Stack( @@ -242,6 +324,19 @@ class _ScanQrScreenState extends State { textAlign: TextAlign.center, 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()], + ), + ), + ), ], ), ), diff --git a/lib/version.dart b/lib/version.dart index ca89e3b..b536995 100644 --- a/lib/version.dart +++ b/lib/version.dart @@ -1,2 +1,2 @@ /// The app version sent to the server in pairing and relay handshakes. -const appVersion = '0.4.5'; +const appVersion = '0.4.6'; diff --git a/pubspec.yaml b/pubspec.yaml index 21485fb..1a85a31 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: openchamber description: "A lightweight OpenChamber client for phones." publish_to: 'none' -version: 0.4.5+405 +version: 0.4.6+406 environment: sdk: ^3.14.0 diff --git a/test/qr_scan_test.dart b/test/qr_scan_test.dart index a68d52c..39ec564 100644 --- a/test/qr_scan_test.dart +++ b/test/qr_scan_test.dart @@ -80,6 +80,38 @@ void main() { 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', () { final blank = Uint8List(320 * 240)..fillRange(0, 320 * 240, 255); expect(decodeQrLuminance(blank, 320, 240, 320), isNull);