V0.3.0版本优化传输速度和提示

This commit is contained in:
zhy
2026-08-10 15:45:04 +08:00
commit d885259e2b
58 changed files with 10284 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
# Rust
/target
**/target
# Android
.gradle/
**/build/
local.properties
.idea/
*.iml
# OS
.DS_Store
Thumbs.db
+55
View File
@@ -0,0 +1,55 @@
# QFT v0.3.0-rc3 implementation status
## Windows → Android optical
- [x] QFT1 manifest/data/end wire format
- [x] CRC32 per frame + SHA-256 whole file
- [x] 1 QR / 4 QR per page
- [x] Windows target refresh 1~60 FPS
- [x] 4-code default, 900-byte payload
- [x] Rayon background pre-encoding
- [x] reused egui GPU TextureHandle
- [x] positioned source reads; no whole-file mmap
- [x] bounded pre-render cache; 1.1GiB process design ceiling
- [x] Android 4-region concurrent decoder
- [x] CameraX KEEP_ONLY_LATEST
- [x] no whole-frame rotation/copy in hot path
- [x] runtime scan FPS / decoded QR/s status
- [x] synthetic 4/4 visual QR decode test
- [ ] physical 60Hz/120Hz monitor × multiple Android camera hardware matrix
## Android → Windows
- [x] QFTPAIR2 compact pairing QR
- [x] persistent per-PC Direct AP identity + per-session token
- [x] one fast endpoint hint in Direct pairing QR
- [x] Windows Wi-Fi Direct Legacy AP code
- [x] Android 10+ WifiNetworkSpecifier path
- [x] Android 7~9 legacy Wi-Fi path
- [x] wait for actual IPv4/link route before discovery
- [x] UDP QFTDISC2 receiver discovery
- [x] directed broadcast + real gateway discovery
- [x] bounded /24 concurrent subnet fallback
- [x] local cleartext network security config
- [x] private/local IPv4 + session-token validation
- [x] Parallel v2 upload init/chunk/finish
- [x] adaptive 4/8/16 MiB chunk size
- [x] up to 8 Android workers per file
- [x] Windows concurrent positioned writes
- [x] temporary `.qftpart`, final SHA-256 and rename
- [x] legacy single-stream fallback
- [x] loopback UDP + HTTP + 8-worker integration test
- [ ] physical Windows Wi-Fi Direct adapter / driver / firewall matrix
## Android compatibility
- [x] minSdk 24 (Android 7.0)
- [x] legacy WRITE_EXTERNAL_STORAGE path <= Android 9
- [x] MediaStore Downloads >= Android 10
- [x] ACCESS_FINE_LOCATION compatibility <= Android 12
- [x] NEARBY_WIFI_DEVICES >= Android 13
- [x] no `java.util.Base64` dependency in app source
- [x] key Kotlin protocol/pairing/upload/scanner source syntax tests in the build environment
- [ ] APK installation/runtime matrix on Android 7/8/9/10/11/12/13/14/15/16+ physical/emulated devices
See `TEST_REPORT.md` for exact test evidence and limitations.
+131
View File
@@ -0,0 +1,131 @@
# QFT · 超速二维码文件传输 v0.3.0-rc3
Windows + Android 双向候选版。两个方向采用不同链路:
- **Windows → Android:纯光学**。文件数据只经过 Windows 屏幕 → Android 摄像头;不使用 Wi‑Fi、蓝牙、局域网或互联网。
- **Android → Windows:扫码本地直连**。Windows 选择保存目录并启动 QFT Direct 临时 Wi‑Fi/接收服务;Android 扫码后请求配网、自动发现电脑,然后并行分块上传。文件不经过外网。
> rc3 是性能/兼容性候选版。仓库内的协议、二维码、并行上传、UDP 发现、内存预算与 Kotlin 关键源文件测试已通过;真正的 Windows Wi‑Fi Direct 驱动、Windows 防火墙、60Hz 显示器与不同 Android 相机组合仍必须在真实设备上做验收,详见 `TEST_REPORT.md`。
## v0.3.0-rc3 针对性优化
### 1. Windows → Android:最高 60 FPS 显示目标
- Windows UI 支持 `1~60 FPS`,提供 15/30/60 与“极速预设”。
- 默认 **4 QR/页 + 60 FPS**,每次刷新最多承载 4 个独立 QFT1 数据帧。
- 单 QR payload 默认 900 B;理论原始文件载荷约 `900 × 4 × 60 = 216,000 B/s`(约 210.9 KiB/s),实际速度取决于显示器刷新率、Android 相机 FPS、曝光/滚动快门和识别率。
- Android 光学扫描采用 1280×720 分析帧、4 象限并行 ZXing 解码、`KEEP_ONLY_LATEST`、Y 平面直接读取且不再整帧旋转。
- Windows 预编码使用 Rayon 多核并行;GPU 纹理复用,不再每帧创建新的纹理对象。
- UI 动态显示目标 FPS、实际页面 FPS、理论载荷和 Android 实际“相机 FPS / 有效 QR/s”。
### 2. 文件与内存优化
- Windows 光学源文件不做整文件 mmap;使用定位读取,避免大文件被整体映射/触碰进工作集。
- 预编码缓存硬设计目标:整进程约 **≤ 1100 MiB**。
- 4 QR / 960px 模式缓存最多 192 页,估算约 **675 MiB**;另为 UI、WGPU/GPU staging、线程栈、二维码临时对象和系统 I/O 留出余量。
- Android → Windows 每个文件内部最高 **8 路并行**。
- 分块根据文件大小自适应:小文件 4 MiB、中型 8 MiB、大文件 16 MiB;每个 worker 仅使用约 1 MiB 应用层 I/O buffer。
- Windows 端预分配 `.qftpart`,多个独立文件句柄按 offset 写入,完成后 SHA-256 校验并原子改名。
### 3. Android → Windows:连接速度/稳定性
扫码二维码升级到更短的 `QFTPAIR2`:
- 短字段 JSON + Base64URL。
- 配对 QR 使用中等级纠错,候选测试为 QR version 10。
- QFT Direct 二维码携带一个快速 endpoint hint,同时保留真实 Wi‑Fi 网关、UDP 发现与当前子网扫描作为 fallback。
- Android 配对扫描分辨率降到 640×480,优先 GlobalHistogram 快速路径;失败才周期性使用 HybridBinarizer。
- Android 连接 Wi‑Fi 后不立即假定网络可用,而是等待真实 IPv4/route。
- 电脑发现顺序:
1. QR endpoint hint;
2. `QFTDISC2` UDP 发现;
3. Android 真实 Wi‑Fi gateway;
4. 常见 Windows Direct 地址;
5. 当前实际子网最多 /24 的并发 fallback 扫描。
- 所有 HTTP 请求绑定到扫码建立的 `Network`,避免手机 4G/5G/其他 Wi‑Fi 抢路由。
- Android Manifest 同时启用 local cleartext network security config;QFTPAIR 解析器仍只允许 literal private/local IPv4 + 本次 session token。
### 4. Android 7 → 最新
- `minSdk = 24`(Android 7.0)。
- Android 10+:`WifiNetworkSpecifier` local-only 配网。
- Android 7~9:`WifiManager/WifiConfiguration` 兼容路径。
- Android 13+:`NEARBY_WIFI_DEVICES`。
- Android 7~12:位置权限兼容。
- Android 7~9 光学保存:`WRITE_EXTERNAL_STORAGE` + `Downloads/QFT`。
- Android 10+ 光学保存:MediaStore Downloads。
## Windows → Android 使用
1. Windows:进入 `电脑 → Android`。
2. 选择文件。
3. 建议先用 `30 FPS / 4 码` 验证,再切 `60 FPS / 4 码`。
4. Android:`电脑 → 手机 → 开始光学接收`。
5. 让 2×2 QR 区域尽量完整占据手机取景框。
6. Android UI 会实时显示相机分析 FPS 和有效 QR/s;若识别偏低,靠近屏幕或把 Windows 降为 30 FPS。
7. 收齐后自动 SHA-256 校验并保存。
## Android → Windows 使用
1. Windows:`Android → 电脑`。
2. 选择接收文件夹。
3. 默认选择 `QFT Direct`。
4. 点击“启动接收并生成二维码”。
5. Windows 保持该页面开启。若 Windows Defender Firewall 首次询问网络访问,请允许 QFT 访问**专用网络**。
6. Android:`手机 → 电脑 → 扫码连接电脑`。
7. 首次连接具体 QFT Direct AP 时,Android 系统可能要求确认该本地 Wi‑Fi。
8. App 自动完成 endpoint/UDP/gateway/subnet 发现,出现“已连接电脑”后选择文件并开始传输。
如果电脑没有可用 Wi‑Fi Direct 适配器,可切换 Windows 的“当前局域网”备用模式。
## 构建
### Windows
需要 Rust stable MSVC + Visual C++ Build Tools / Windows SDK。
```powershell
cd windows
cargo check
cargo build --release
cargo run --release
```
### Android
当前构建栈:compileSdk/targetSdk 35、minSdk 24、JDK 17。
```powershell
cd android
.\gradlew.bat :app:testDebugUnitTest :app:assembleDebug
```
APK:
`android/app/build/outputs/apk/debug/app-debug.apk`
## 字体
Windows UI 优先读取:
`windows/assets/qft-ui.ttf`
也可设置 `QFT_FONT_PATH` 指向支持中文的 TTF。项目不会分发第三方字体文件。
## 验证
开发侧测试:
```bash
python scripts/run_all_selftests.py
python scripts/optical_image_decode_selftest.py
python scripts/local_transfer_integration_selftest.py
```
Windows 真机环境可运行根目录:
```powershell
.\VERIFY_WINDOWS_HOST.ps1
```
详细结果与尚未能在当前生成环境自动验证的硬件项目见 `TEST_REPORT.md`。
+182
View File
@@ -0,0 +1,182 @@
# QFT v0.3.0-rc3 test report
Date: 2026-08-10
This report deliberately separates **tests actually executed in the current build environment** from **hardware acceptance that cannot be truthfully simulated here**.
## Executed and passed
### Optical protocol recovery
Command:
`python scripts/protocol_selftest.py`
Result:
- 2,500,123-byte random file
- 900-byte chunks
- 4 QR/page
- target 60 pages/s model
- synthetic 24% whole-page loss + 14% per-lane QR loss
- reconstructed exact original file in 9 rounds
- final SHA-256 identical
- representative frame: QR v25, ~3 rendered pixels/module at native 960px page
- theoretical raw file payload: ~210.9 KiB/s
**PASS**
### Synthetic visual QR decode
Command:
`python scripts/optical_image_decode_selftest.py`
Result in this environment:
- 4/4 high-density QFT optical QR symbols decoded from one 960×960 synthetic page using libzbar/pyzbar
- QFTPAIR2 QR-M decoded after synthetic 7° rotation plus light Gaussian blur
**PASS**
This proves generated QR geometry/data is decodable under a synthetic image path; it does **not** prove a particular monitor/camera can decode 60 physical refreshes per second.
### QFTPAIR2 size / QR density
Command:
`python scripts/pairing_selftest.py`
Result:
- QFTPAIR2: 207 characters with one Direct-AP endpoint hint
- older QFTPAIR1 comparison: 368 characters
- v2 size: 56.2% of v1
- medium-error-correction QR: version 10
- encode/decode round-trip exact
**PASS**
### Parallel local-file chunk reconstruction
Command:
`python scripts/parallel_upload_selftest.py`
Result:
- ~64 MiB random file
- 8 MiB test chunks
- 8 worker threads
- 1 MiB worker I/O buffers
- out-of-order positioned writes
- final SHA-256 identical
**PASS**
### End-to-end local protocol integration
Command:
`python scripts/local_transfer_integration_selftest.py`
Result:
- QFTDISC2 UDP request/response
- session-token authenticated `/qft/ping`
- Parallel-v2 init
- out-of-order chunk POSTs using 8 workers
- finish
- exact reconstructed file and SHA-256 match
**PASS**
### Standalone UDP discovery
Command:
`python scripts/udp_discovery_selftest.py`
QFTDISC2 / QFTHERE2 token and port round-trip.
**PASS**
### Memory-budget model
Command:
`python scripts/memory_budget_selftest.py`
Result:
- 4QR 960px pre-render page ≈ 3.5156 MiB as Color32
- maximum cache page cap 192 → ≈ 675 MiB
- conservative extra transient test allowance remains below the 1100 MiB design ceiling
- whole source file is no longer memory-mapped
**PASS (design-budget test)**
This is not an OS-level hard RSS limiter. GPU drivers, allocator fragmentation and platform runtime memory vary; the implementation intentionally leaves several hundred MiB headroom instead of allocating a full 1 GiB cache.
### Android compatibility/static guards
Command:
`python scripts/android_compat_selftest.py`
Checked:
- minSdk 24
- API 29 modern/legacy Wi-Fi split
- Android 7~9 storage path
- Android <=12 location permission
- Android 13+ nearby-WiFi permission
- network security config for local HTTP
- gateway/directed-broadcast/subnet discovery fallbacks
- 8-worker upload
- 640×480 pairing scan + 1280×720 optical analysis
- KEEP_ONLY_LATEST
- no full-frame rotate in scanner hot path
- no `java.util.Base64` dependency in main Android source
**PASS**
### Kotlin source checks executed
Using `kotlinc-jvm 1.9.0` plus small Android/JSON stubs where necessary:
- `Base64Url.kt + Protocol.kt` runtime parser test: **PASS**
- `PairingProtocol.kt` syntax/type test: **PASS**
- `UploadClient.kt + PairingProtocol.kt` syntax/type test: **PASS**
- `GrayFrame.kt + QrAnalyzer.kt` syntax/type test: **PASS**
- `WifiConnector.kt` syntax/type test across the modern/legacy branches: **PASS**
These tests caught and fixed an earlier `ExecutorCompletionService.submit<String?>` source error before packaging rc3.
## Not executable in the current Linux build sandbox
The following are hardware/OS-specific and therefore are **not claimed as passed** here:
1. Windows `cargo check/build` against the Windows MSVC/WinRT target.
2. Actual `WiFiDirectAdvertisementPublisher` start on a Windows Wi-Fi adapter.
3. Windows Defender Firewall private-network approval behavior.
4. Android Gradle APK build against a local Android SDK in this sandbox.
5. Android 7/8/9/10/11/12/13/14/15/16+ install/runtime matrix.
6. Real monitor → real camera optical performance at 30/60Hz, different brightness, rolling shutter and autofocus conditions.
7. Real Wi-Fi Direct throughput across different NIC/phone vendors.
For those reasons **v0.3.0-rc3 remains an RC, not a final stable release**.
## Required physical acceptance before marking stable
Run `VERIFY_WINDOWS_HOST.ps1`, then at minimum:
- Windows 10/11 + Android 7/9/10/13/latest available devices.
- Optical files: 10 KiB, 1 MiB, 10 MiB at 30 FPS and 60 FPS.
- Verify Android UI actual camera FPS / QR/s and final SHA-256.
- Android→Windows QFT Direct: first-time pairing, repeat pairing, reconnect after Wi-Fi loss.
- Test with Windows Firewall prompt accepted and with “current LAN” fallback.
- Upload 10 MiB, 500 MiB, and >2 GiB files; verify final SHA-256 and memory usage.
- Observe Windows working set during optical 60 FPS; if host-specific RSS exceeds 1.1 GiB, reduce the pre-encode cache slider (default 384 MiB) and record the device/driver combination.
Only after this matrix is passed should the RC label be removed.
+29
View File
@@ -0,0 +1,29 @@
QFT v0.3.0-rc3 test execution log
UTC 2026-08-10 06:48:06
== protocol_selftest.py ==
PASS optical: 2500123 bytes, 2778 chunks, 4 QR/page @ 60 FPS, 24% page loss + 14% lane loss, recovered in 9 rounds; QR v25, 3px/module, frame chars=1243, theoretical payload=210.9 KiB/s
== pairing_selftest.py ==
PASS pairing: QFTPAIR2=207 chars vs v1=368 chars (56.2%), QR-M version=10
== parallel_upload_selftest.py ==
PASS parallel upload: 67121209 bytes, 8 MiB chunks, 8 workers, 1 MiB worker I/O, SHA-256 identical
== udp_discovery_selftest.py ==
PASS UDP discovery: request/response token+port round-trip from 127.0.0.1
== local_transfer_integration_selftest.py ==
PASS loopback Parallel v2 integration: UDP discovery + HTTP auth + 6 out-of-order chunks / 8 workers; 41955385 bytes SHA-256 identical in 0.22s
== memory_budget_selftest.py ==
PASS memory budget: 4QR cache=192 pages/675.0 MiB; 1QR cache=192 pages/423.0 MiB; hard design ceiling=1100 MiB
== android_compat_selftest.py ==
PASS Android compatibility/static guards: minSdk24, API29 split, legacy storage/location, Android13 nearby-WiFi, cleartext local config, subnet fallback, fast scanner paths
ALL CORE PYTHON SELFTESTS PASSED
PASS synthetic QR decode: 4/4 optical QR v25 decoded from 960px page in 48.3 ms; QFTPAIR2 QR-M v10 decoded after 7deg rotate+blur in 1.7 ms
Kotlin runtime: Base64Url + QFT1
PASS Kotlin Base64Url + QFT1 parser
Kotlin syntax: PairingProtocol + UploadClient
PASS Kotlin syntax: PairingProtocol.kt + UploadClient.kt
Kotlin syntax: GrayFrame + QrAnalyzer
PASS Kotlin syntax: GrayFrame.kt + QrAnalyzer.kt
Kotlin syntax: WifiConnector
PASS Kotlin syntax: WifiConnector.kt
+37
View File
@@ -0,0 +1,37 @@
$ErrorActionPreference = 'Stop'
$Root = Split-Path -Parent $MyInvocation.MyCommand.Path
Write-Host "== QFT v0.3.0-rc3 Windows host verification ==" -ForegroundColor Cyan
if (Get-Command python -ErrorAction SilentlyContinue) {
Write-Host "[1/4] Core protocol/selftests"
& python "$Root\scripts\run_all_selftests.py"
} else {
Write-Warning "python not found; skipping repository Python selftests"
}
Write-Host "[2/4] Windows Rust compile"
Push-Location "$Root\windows"
try {
& cargo check
if ($LASTEXITCODE -ne 0) { throw "cargo check failed" }
& cargo build --release
if ($LASTEXITCODE -ne 0) { throw "cargo build --release failed" }
} finally { Pop-Location }
Write-Host "[3/4] Android unit/build"
Push-Location "$Root\android"
try {
if (!(Test-Path '.\gradle\wrapper\gradle-wrapper.jar')) {
Write-Host "Gradle wrapper jar missing; attempting bootstrap..."
& powershell -ExecutionPolicy Bypass -File '.\bootstrap-wrapper.ps1'
}
& .\gradlew.bat :app:testDebugUnitTest :app:assembleDebug --stacktrace
if ($LASTEXITCODE -ne 0) { throw "Android Gradle verification failed" }
} finally { Pop-Location }
Write-Host "[4/4] Artifact locations" -ForegroundColor Cyan
Write-Host "Windows EXE: $Root\windows\target\release\qft-windows.exe"
Write-Host "Android APK: $Root\android\app\build\outputs\apk\debug\app-debug.apk"
Write-Host "\nHOST BUILD VERIFICATION PASSED" -ForegroundColor Green
Write-Host "Next: perform the physical display/camera and Wi-Fi Direct acceptance matrix in TEST_REPORT.md."
+33
View File
@@ -0,0 +1,33 @@
# Android build fix v0.1.1
This revision intentionally uses the Android 15 / API 35 toolchain for the MVP.
The optical receiver does not use Android 16-only APIs, so API 36 is unnecessary for now.
Pinned stack:
- compileSdk / targetSdk: 35
- Android Gradle Plugin: 8.9.1
- Gradle: 8.11.1
- JDK: 17
- Build Tools: 35.0.0
- Kotlin Gradle Plugin: 2.1.20
- Activity: 1.10.1
- CameraX: 1.4.2
- ZXing core: 3.5.3
The manifest now references the local `@style/QftTheme`; the theme inherits the standard Android Material light no-action-bar theme.
## Windows one-command repair
From the `android` directory:
```powershell
Set-ExecutionPolicy -Scope Process Bypass
.\repair-windows.ps1 -Sdk "E:\SYSTEM\APPDATA\Android_SDK"
```
If your SDK lives elsewhere, change `-Sdk`.
After the script succeeds, the APK should be at:
`app\build\outputs\apk\debug\app-debug.apk`
+20
View File
@@ -0,0 +1,20 @@
# QFT Android v0.2.1 build fix
Fixes Kotlin compile error in `MainActivity.kt` line ~502.
Incorrect:
```kotlin
android.view.Space(this)
```
Correct:
```kotlin
android.widget.Space(this)
```
The accompanying `layoutParams` and type inference errors were cascading errors caused by the unresolved `Space` class.
Rebuild with:
```powershell
.\gradlew.bat :app:assembleDebug
```
+50
View File
@@ -0,0 +1,50 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.qft.optical"
compileSdk = 35
buildToolsVersion = "35.0.0"
defaultConfig {
applicationId = "com.qft.optical"
minSdk = 24
targetSdk = 35
versionCode = 8
versionName = "0.3.0-rc3"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
}
dependencies {
implementation("androidx.activity:activity-ktx:1.10.1")
implementation("androidx.camera:camera-core:1.4.2")
implementation("androidx.camera:camera-camera2:1.4.2")
implementation("androidx.camera:camera-lifecycle:1.4.2")
implementation("androidx.camera:camera-view:1.4.2")
implementation("com.google.zxing:core:3.5.3")
testImplementation("junit:junit:4.13.2")
}
+1
View File
@@ -0,0 +1 @@
# MVP: no custom rules yet.
+32
View File
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="32" />
<uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" android:usesPermissionFlags="neverForLocation" />
<uses-feature android:name="android.hardware.camera.any" android:required="true" />
<uses-feature android:name="android.hardware.wifi" android:required="false" />
<application
android:allowBackup="false"
android:usesCleartextTraffic="true"
android:networkSecurityConfig="@xml/network_security_config"
android:label="QFT"
android:supportsRtl="true"
android:theme="@style/QftTheme">
<activity
android:name=".MainActivity"
android:exported="true"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,60 @@
package com.qft.optical
/** Small URL-safe Base64 codec with no padding; works unchanged on Android 7+ and JVM unit tests. */
object Base64Url {
private const val ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
private val reverse = IntArray(128) { -1 }.also { table ->
ALPHABET.forEachIndexed { index, c -> table[c.code] = index }
}
fun encode(input: ByteArray): String {
if (input.isEmpty()) return ""
val out = StringBuilder((input.size * 4 + 2) / 3)
var i = 0
while (i + 2 < input.size) {
val n = ((input[i].toInt() and 0xff) shl 16) or
((input[i + 1].toInt() and 0xff) shl 8) or
(input[i + 2].toInt() and 0xff)
out.append(ALPHABET[(n ushr 18) and 63])
out.append(ALPHABET[(n ushr 12) and 63])
out.append(ALPHABET[(n ushr 6) and 63])
out.append(ALPHABET[n and 63])
i += 3
}
val remaining = input.size - i
if (remaining == 1) {
val n = (input[i].toInt() and 0xff) shl 16
out.append(ALPHABET[(n ushr 18) and 63])
out.append(ALPHABET[(n ushr 12) and 63])
} else if (remaining == 2) {
val n = ((input[i].toInt() and 0xff) shl 16) or ((input[i + 1].toInt() and 0xff) shl 8)
out.append(ALPHABET[(n ushr 18) and 63])
out.append(ALPHABET[(n ushr 12) and 63])
out.append(ALPHABET[(n ushr 6) and 63])
}
return out.toString()
}
fun decode(text: String): ByteArray? {
if (text.isEmpty()) return ByteArray(0)
if (text.length % 4 == 1) return null
val out = ByteArray((text.length * 6) / 8)
var outIndex = 0
var accumulator = 0
var bits = 0
for (c in text) {
val code = c.code
if (code >= reverse.size) return null
val value = reverse[code]
if (value < 0) return null
accumulator = (accumulator shl 6) or value
bits += 6
if (bits >= 8) {
bits -= 8
if (outIndex >= out.size) return null
out[outIndex++] = ((accumulator ushr bits) and 0xff).toByte()
}
}
return if (outIndex == out.size) out else out.copyOf(outIndex)
}
}
@@ -0,0 +1,43 @@
package com.qft.optical
import androidx.camera.core.ImageProxy
/**
* Copies only the Y plane.
*
* QFT deliberately keeps the camera buffer in sensor orientation. QR finder
* patterns are rotation independent, and the optical 2x2 layout is still a 2x2
* layout after a 90° rotation. Avoiding a second full-frame rotate/copy removes
* almost half of the memory traffic in the scanner hot path on portrait phones.
*/
data class GrayFrame(val width: Int, val height: Int, val luma: ByteArray) {
companion object {
fun from(image: ImageProxy): GrayFrame {
val plane = image.planes[0]
val src = plane.buffer.duplicate()
val rowStride = plane.rowStride
val pixelStride = plane.pixelStride
val w = image.width
val h = image.height
val raw = ByteArray(w * h)
if (pixelStride == 1 && rowStride == w) {
src.position(0)
src.get(raw, 0, raw.size)
} else if (pixelStride == 1) {
for (y in 0 until h) {
src.position(y * rowStride)
src.get(raw, y * w, w)
}
} else {
for (y in 0 until h) {
val rowStart = y * rowStride
for (x in 0 until w) {
raw[y * w + x] = src.get(rowStart + x * pixelStride)
}
}
}
return GrayFrame(w, h, raw)
}
}
}
@@ -0,0 +1,618 @@
package com.qft.optical
import android.Manifest
import android.content.pm.PackageManager
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.net.Network
import android.os.Build
import android.os.Bundle
import android.util.Size
import android.view.Gravity
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.ScrollView
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
import androidx.camera.core.CameraSelector
import androidx.camera.core.FocusMeteringAction
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
class MainActivity : ComponentActivity() {
private enum class ScannerMode { NONE, OPTICAL, PAIR }
private val receiverDeviceLabel: String by lazy { localDeviceLabel() }
private val cameraExecutor = Executors.newSingleThreadExecutor()
private val transferExecutor = Executors.newSingleThreadExecutor()
private val wifiConnector by lazy { WifiConnector(this) }
private lateinit var assembler: SessionAssembler
private var cameraProvider: ProcessCameraProvider? = null
private var currentAnalyzer: QrAnalyzer? = null
private var scannerStatsText: TextView? = null
private var scannerMode = ScannerMode.NONE
private var pendingScannerMode = ScannerMode.NONE
private val pairConsumed = AtomicBoolean(false)
private lateinit var previewView: PreviewView
private lateinit var titleText: TextView
private lateinit var deviceText: TextView
private lateinit var statusText: TextView
private lateinit var progress: ProgressBar
private var pendingPair: PairingPayload? = null
private var connectedNetwork: Network? = null
private var connectedBaseUrl: String? = null
private val selectedFiles = mutableListOf<SelectedFile>()
private var sendStatusText: TextView? = null
private var sendFilesText: TextView? = null
private var sendProgress: ProgressBar? = null
private var sendButton: Button? = null
private var connectingStatusText: TextView? = null
private val requestCamera = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) startScanner(pendingScannerMode) else showHome("需要相机权限才能扫描 QFT 二维码")
}
private val requestLegacyStorage = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) requestScanner(pendingScannerMode) else showHome("Android 7~9 需要存储权限才能把光学接收文件保存到 Downloads/QFT")
}
private val requestWifiPermissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
val denied = result.filterValues { !it }.keys
val pair = pendingPair
if (denied.isEmpty() && pair != null) {
connectPair(pair)
} else {
showPairError(pair, "需要附近 Wi-Fi/位置权限才能完成扫码配网")
}
}
private val pickFiles = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
selectedFiles.clear()
var unknown = 0
for (uri in uris) {
val file = UploadClient.describeFile(contentResolver, uri)
if (file != null) selectedFiles += file else unknown++
}
renderSelectedFiles()
if (unknown > 0) {
sendStatusText?.text = "有 $unknown 个文件无法确定大小,已跳过"
} else if (selectedFiles.isNotEmpty()) {
sendStatusText?.text = "已选择 ${selectedFiles.size} 个文件,点击“开始传输”"
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
window.statusBarColor = BG
window.navigationBarColor = BG
assembler = SessionAssembler(this) { event -> runOnUiThread { renderOpticalEvent(event) } }
showHome()
}
private fun showHome(message: String? = null) {
stopCamera()
scannerMode = ScannerMode.NONE
pairConsumed.set(false)
wifiConnector.release()
pendingPair = null
connectedNetwork = null
connectedBaseUrl = null
selectedFiles.clear()
val root = pageColumn()
root.addView(text("QFT", 30f, Color.WHITE, true))
root.addView(text("超速二维码文件传输", 16f, MUTED))
root.addView(space(26))
message?.let {
val banner = text(it, 14f, WARNING)
banner.setPadding(dp(14), dp(12), dp(14), dp(12))
banner.background = rounded(0xFF2B2112.toInt(), 14)
root.addView(banner, matchWrap(top = 0, bottom = 18))
}
root.addView(modeCard(
title = "电脑 → 手机",
badge = "光学零网络 · 4码并行 · 60FPS显示",
body = "手机摄像头连续读取电脑动态二维码。Wi-Fi、蓝牙、局域网和互联网都不参与文件数据传输。",
buttonLabel = "开始光学接收",
) { requestScanner(ScannerMode.OPTICAL) })
root.addView(space(16))
root.addView(modeCard(
title = "手机 → 电脑",
badge = "扫码直连 · 快速发现 · 8路并行",
body = "扫描电脑上的接收二维码,自动请求连接 QFT 临时 Wi-Fi,然后把文件直接上传到电脑指定文件夹。",
buttonLabel = "扫码连接电脑",
) { 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))
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
private fun requestScanner(mode: ScannerMode) {
pendingScannerMode = mode
if (mode == ScannerMode.OPTICAL && Build.VERSION.SDK_INT <= 28 &&
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
) {
requestLegacyStorage.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
return
}
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
startScanner(mode)
} else {
requestCamera.launch(Manifest.permission.CAMERA)
}
}
private fun startScanner(mode: ScannerMode) {
scannerMode = mode
pairConsumed.set(false)
setContentView(buildCameraUi(mode))
val future = ProcessCameraProvider.getInstance(this)
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
currentAnalyzer?.close()
val analyzer = QrAnalyzer(
profile = profile,
onTexts = { values ->
when (scannerMode) {
ScannerMode.OPTICAL -> values.forEach(assembler::acceptText)
ScannerMode.PAIR -> values.firstOrNull { PairingProtocol.isPairingText(it) }?.let(::acceptPairCode)
ScannerMode.NONE -> Unit
}
},
onStats = { cameraFps, decodedFps ->
runOnUiThread {
val quality = when (mode) {
ScannerMode.PAIR -> when {
decodedFps >= 1.0 -> "识别稳定" to SUCCESS
cameraFps >= 18.0 -> "正在锁定二维码" to ACCENT
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
}
ScannerMode.NONE -> "空闲" to MUTED
}
scannerStatsText?.text = "%s · 相机 %.1f FPS · 有效 QR %.1f/s".format(quality.first, cameraFps, decodedFps)
scannerStatsText?.setTextColor(quality.second)
}
},
)
currentAnalyzer = analyzer
val targetSize = if (mode == ScannerMode.PAIR) Size(640, 480) else Size(1280, 720)
val analysis = ImageAnalysis.Builder()
.setTargetResolution(targetSize)
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.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) {}
}, mainExecutor)
}
private fun buildCameraUi(mode: ScannerMode): FrameLayout {
val root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
previewView = PreviewView(this).apply {
implementationMode = PreviewView.ImplementationMode.PERFORMANCE
scaleType = PreviewView.ScaleType.FILL_CENTER
}
root.addView(previewView, FrameLayout.LayoutParams(-1, -1))
val top = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
setPadding(dp(14), dp(12), dp(14), dp(12))
setBackgroundColor(0xB80C0E12.toInt())
}
val back = button("‹ 返回").apply { setOnClickListener { showHome() } }
top.addView(back)
titleText = text(if (mode == ScannerMode.OPTICAL) "电脑 → 手机" else "扫码连接电脑", 19f, Color.WHITE, true)
top.addView(titleText, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(10) })
root.addView(top, FrameLayout.LayoutParams(-1, -2, Gravity.TOP))
val panel = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(dp(16), dp(14), dp(16), dp(16))
background = rounded(0xE80C0E12.toInt(), 18)
}
deviceText = text(
if (mode == ScannerMode.OPTICAL) "接收设备:$receiverDeviceLabel\n发送设备:等待 QFT1 MANIFEST…"
else "目标:等待 QFTPAIR2 配对二维码",
14f, Color.WHITE
)
statusText = text(
if (mode == ScannerMode.OPTICAL) "把电脑动态二维码完整放进取景框"
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))
scannerStatsText = text("相机分析:等待首帧…", 12f, ACCENT)
panel.addView(scannerStatsText, matchWrap(top = 6))
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)
})
return root
}
private fun acceptPairCode(text: String) {
if (!PairingProtocol.isPairingText(text)) return
if (!pairConsumed.compareAndSet(false, true)) return
val pair = PairingProtocol.parse(text)
if (pair == null) {
pairConsumed.set(false)
runOnUiThread { statusText.text = "配对二维码格式无效,请重新对准" }
return
}
pendingPair = pair
runOnUiThread {
stopCamera()
showConnecting(pair, "二维码已识别,正在准备本地连接…")
ensureWifiPermissionThenConnect(pair)
}
}
private fun ensureWifiPermissionThenConnect(pair: PairingPayload) {
if (pair.wifi == null) {
connectPair(pair)
return
}
val required = when {
Build.VERSION.SDK_INT >= 33 -> arrayOf(Manifest.permission.NEARBY_WIFI_DEVICES)
else -> arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
}
val missing = required.filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
if (missing.isEmpty()) connectPair(pair) else requestWifiPermissions.launch(missing.toTypedArray())
}
private fun connectPair(pair: PairingPayload) {
showConnecting(pair, pair.wifi?.let { "正在请求连接 ${it.ssid}…" } ?: "正在使用当前局域网探测电脑…")
wifiConnector.connect(
pairing = pair,
onStatus = { message -> runOnUiThread { updateConnectingStatus(message) } },
onAvailable = { network ->
connectedNetwork = network
transferExecutor.execute {
runOnUiThread { updateConnectingStatus("网络路由已就绪 · 正在 UDP 快速发现电脑…") }
val discovered = UploadClient.discoverUdp(
network = network,
pairing = pair,
hosts = wifiConnector.discoveryHosts(network),
)
runOnUiThread {
updateConnectingStatus(
if (discovered != null) "已通过 UDP 找到电脑 · 正在验证接收服务…"
else "UDP 未响应 · 正在并行探测网关与本地 IP…"
)
}
val gateways = wifiConnector.gatewayEndpoints(network, pair.port)
val subnet = wifiConnector.subnetEndpoints(network, pair.port)
if (discovered == null) {
runOnUiThread {
updateConnectingStatus("正在并行探测网关;必要时自动扫描当前 QFT 子网…")
}
}
val base = UploadClient.probeRobust(
network = network,
pairing = pair,
deviceName = receiverDeviceLabel,
preferredEndpoints = gateways,
discoveredEndpoint = discovered,
subnetEndpoints = subnet,
)
runOnUiThread {
if (base == null) {
showPairError(pair, "Wi-Fi 已连接,但快速发现、网关探测和当前子网扫描都未找到 QFT 接收服务。请保持 Windows 接收页开启,并在 Windows 防火墙首次弹窗时允许 QFT 访问专用网络。")
} else {
connectedBaseUrl = base
showSendReady(pair, base)
}
}
}
},
onUnavailable = { message -> runOnUiThread { showPairError(pair, message) } },
)
}
private fun showConnecting(pair: PairingPayload, message: String) {
val root = pageColumn()
root.addView(text("正在连接电脑", 28f, Color.WHITE, true))
root.addView(text(pair.pcName, 18f, ACCENT))
root.addView(space(22))
root.addView(card().apply {
addView(text("配对信息", 15f, MUTED))
addView(text("电脑:${pair.pcName}", 16f, Color.WHITE), matchWrap(top = 8))
addView(text("网络:${pair.wifi?.ssid ?: "当前局域网"}", 14f, Color.WHITE), matchWrap(top = 5))
addView(text("会话:${pair.session.take(10)}…", 12f, MUTED), matchWrap(top = 5))
})
root.addView(space(18))
val spinner = ProgressBar(this)
root.addView(spinner, LinearLayout.LayoutParams(dp(48), dp(48)).apply { gravity = Gravity.CENTER_HORIZONTAL })
connectingStatusText = text(message, 14f, MUTED).apply { gravity = Gravity.CENTER }
root.addView(connectingStatusText, matchWrap(top = 12))
root.addView(space(20))
root.addView(button("取消").apply { setOnClickListener { showHome() } })
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
private fun updateConnectingStatus(message: String) {
connectingStatusText?.text = message
}
private fun showPairError(pair: PairingPayload?, message: String) {
val root = pageColumn()
root.addView(text("连接未完成", 28f, Color.WHITE, true))
root.addView(text(message, 15f, WARNING), matchWrap(top = 12))
root.addView(space(24))
if (pair != null) {
root.addView(button("重试连接").apply { setOnClickListener { ensureWifiPermissionThenConnect(pair) } })
root.addView(space(10))
}
root.addView(button("重新扫码").apply { setOnClickListener { requestScanner(ScannerMode.PAIR) } })
root.addView(space(10))
root.addView(button("返回首页").apply { setOnClickListener { showHome() } })
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
}
private fun showSendReady(pair: PairingPayload, baseUrl: String) {
val root = pageColumn()
root.addView(text("已连接电脑", 28f, Color.WHITE, true))
root.addView(text("${receiverDeviceLabel} → ${pair.pcName}", 16f, ACCENT))
root.addView(space(18))
root.addView(card().apply {
addView(text("连接状态", 14f, MUTED))
addView(text("● 本地直连已就绪", 17f, SUCCESS, true), matchWrap(top = 8))
addView(text(if (pair.version >= 2) "Parallel v2 · 自适应最高 8 路并发 · 4/8/16 MiB 自适应分块" else "兼容单流模式", 13f, ACCENT), matchWrap(top = 5))
addView(text("目标:$baseUrl", 12f, MUTED), matchWrap(top = 6))
pair.wifi?.let { addView(text("QFT 临时网络:${it.ssid}", 12f, MUTED), matchWrap(top = 4)) }
})
root.addView(space(14))
root.addView(card().apply {
addView(text("选择文件", 17f, Color.WHITE, true))
sendFilesText = text("尚未选择文件", 14f, MUTED)
addView(sendFilesText, matchWrap(top = 8))
addView(button("选择文件(可多选)").apply {
setOnClickListener { pickFiles.launch(arrayOf("*/*")) }
}, matchWrap(top = 12))
})
root.addView(space(14))
root.addView(card().apply {
addView(text("传输进度", 17f, Color.WHITE, true))
sendStatusText = text("选择文件后点击开始传输", 14f, MUTED)
addView(sendStatusText, matchWrap(top = 8))
sendProgress = ProgressBar(this@MainActivity, null, android.R.attr.progressBarStyleHorizontal).apply { max = 1000; progress = 0 }
addView(sendProgress, LinearLayout.LayoutParams(-1, dp(9)).apply { topMargin = dp(12) })
sendButton = button("开始传输").apply {
isEnabled = selectedFiles.isNotEmpty()
setOnClickListener { startUploads(pair, baseUrl) }
}
addView(sendButton, matchWrap(top = 14))
})
root.addView(space(14))
root.addView(button("断开并返回首页").apply { setOnClickListener { showHome() } })
setContentView(ScrollView(this).apply { setBackgroundColor(BG); addView(root) })
renderSelectedFiles()
}
private fun renderSelectedFiles() {
val total = selectedFiles.sumOf { it.size }
sendFilesText?.text = if (selectedFiles.isEmpty()) {
"尚未选择文件"
} else {
buildString {
selectedFiles.take(8).forEach { append("• ${it.name} ${humanBytes(it.size)}\n") }
if (selectedFiles.size > 8) append("…另外 ${selectedFiles.size - 8} 个文件\n")
append("共 ${selectedFiles.size} 个 · ${humanBytes(total)}")
}.trim()
}
sendButton?.isEnabled = selectedFiles.isNotEmpty() && connectedBaseUrl != null
}
private fun startUploads(pair: PairingPayload, baseUrl: String) {
if (selectedFiles.isEmpty()) return
val files = selectedFiles.toList()
sendButton?.isEnabled = false
transferExecutor.execute {
try {
files.forEachIndexed { index, file ->
val startedAt = android.os.SystemClock.elapsedRealtime()
runOnUiThread {
sendProgress?.progress = 0
sendStatusText?.text = "${index + 1}/${files.size} · 正在发送 ${file.name}"
}
UploadClient.upload(
resolver = contentResolver,
network = connectedNetwork,
baseUrl = baseUrl,
pairing = pair,
deviceName = receiverDeviceLabel,
file = file,
) { sent, total ->
runOnUiThread {
val p = if (total == 0L) 1000 else ((sent.toDouble() / total) * 1000).toInt().coerceIn(0, 1000)
val elapsedMs = (android.os.SystemClock.elapsedRealtime() - startedAt).coerceAtLeast(1L)
val bytesPerSecond = sent * 1000.0 / elapsedMs
val etaSeconds = if (bytesPerSecond > 1.0 && total > sent) (total - sent) / bytesPerSecond else 0.0
sendProgress?.progress = p
sendStatusText?.text = buildString {
append("${index + 1}/${files.size} · ${file.name}\n")
append("${humanBytes(sent)} / ${humanBytes(total)} · ${humanBytes(bytesPerSecond.toLong())}/s")
if (etaSeconds > 0.5) append(" · 剩余 ${humanDuration(etaSeconds)}")
}
}
}
}
runOnUiThread {
sendProgress?.progress = 1000
sendStatusText?.text = "全部完成 · 已发送 ${files.size} 个文件"
sendButton?.isEnabled = true
}
} catch (e: Exception) {
runOnUiThread {
sendStatusText?.text = "传输失败:${e.message}"
sendButton?.isEnabled = true
}
}
}
}
private fun renderOpticalEvent(event: ReceiveEvent) {
if (scannerMode != ScannerMode.OPTICAL) return
when (event) {
is ReceiveEvent.Started -> {
titleText.text = event.manifest.fileName
deviceText.text = "传输设备:${event.manifest.senderDevice} → $receiverDeviceLabel"
statusText.text = "已锁定会话,等待数据块…"
progress.progress = 0
}
is ReceiveEvent.Progress -> {
val total = event.total.coerceAtLeast(1)
val p = event.received.toDouble() / total.toDouble()
progress.progress = (p * 1000).toInt().coerceIn(0, 1000)
statusText.text = "已收到 ${event.received}/${event.total} · ${(p * 100).toInt()}% · 漏帧会在下一轮补齐"
}
is ReceiveEvent.Completed -> {
progress.progress = 1000
deviceText.text = "传输完成:${event.manifest.senderDevice} → $receiverDeviceLabel"
statusText.text = "完成:已保存到 Downloads/QFT/${event.savedName}"
}
is ReceiveEvent.Error -> statusText.text = event.message
}
}
private fun stopCamera() {
try { cameraProvider?.unbindAll() } catch (_: Exception) {}
cameraProvider = null
currentAnalyzer?.close()
currentAnalyzer = null
scannerStatsText = null
scannerMode = ScannerMode.NONE
}
private fun localDeviceLabel(): String {
val manufacturer = Build.MANUFACTURER.orEmpty().trim()
val model = Build.MODEL.orEmpty().trim()
return when {
model.isBlank() -> "Android"
manufacturer.isBlank() -> model
model.startsWith(manufacturer, ignoreCase = true) -> model
else -> "$manufacturer $model"
}
}
private fun pageColumn(): LinearLayout = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(dp(20), dp(28), dp(20), dp(28))
setBackgroundColor(BG)
}
private fun modeCard(title: String, badge: String, body: String, buttonLabel: String, onClick: () -> Unit): LinearLayout = card().apply {
addView(text(title, 23f, Color.WHITE, true))
addView(text(badge, 13f, ACCENT, true), matchWrap(top = 5))
addView(text(body, 14f, MUTED), matchWrap(top = 12))
addView(button(buttonLabel).apply { setOnClickListener { onClick() } }, matchWrap(top = 18))
}
private fun card(): LinearLayout = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(dp(18), dp(18), dp(18), dp(18))
background = rounded(CARD, 18)
}
private fun text(value: String, size: Float, color: Int, bold: Boolean = false): TextView = TextView(this).apply {
text = value
textSize = size
setTextColor(color)
if (bold) setTypeface(typeface, android.graphics.Typeface.BOLD)
setLineSpacing(0f, 1.12f)
}
private fun button(label: String): Button = Button(this).apply {
text = label
isAllCaps = false
setTextColor(Color.WHITE)
backgroundTintList = ColorStateList.valueOf(0xFF2667FF.toInt())
minHeight = dp(48)
}
private fun rounded(color: Int, radiusDp: Int): GradientDrawable = GradientDrawable().apply {
shape = GradientDrawable.RECTANGLE
setColor(color)
cornerRadius = dp(radiusDp).toFloat()
}
private fun space(heightDp: Int) = android.widget.Space(this).apply {
layoutParams = LinearLayout.LayoutParams(1, dp(heightDp))
}
private fun matchWrap(top: Int = 0, bottom: Int = 0) = LinearLayout.LayoutParams(-1, -2).apply {
topMargin = dp(top); bottomMargin = dp(bottom)
}
private fun dp(v: Int): Int = (v * resources.displayMetrics.density).toInt()
private fun humanDuration(seconds: Double): String {
if (!seconds.isFinite() || seconds <= 0.5) return "<1 秒"
val total = kotlin.math.ceil(seconds).toLong()
val minutes = total / 60
val secs = total % 60
return if (minutes > 0) "${minutes}分${secs}秒" else "${secs}秒"
}
private fun humanBytes(v: Long): String {
val units = arrayOf("B", "KB", "MB", "GB", "TB")
var n = v.toDouble()
var i = 0
while (n >= 1024.0 && i < units.lastIndex) { n /= 1024.0; i++ }
return if (i == 0) "$v ${units[i]}" else "%.2f %s".format(n, units[i])
}
override fun onDestroy() {
assembler.reset()
wifiConnector.release()
stopCamera()
cameraExecutor.shutdownNow()
transferExecutor.shutdownNow()
super.onDestroy()
}
companion object {
private const val BG = 0xFF0B0E13.toInt()
private const val CARD = 0xFF151A22.toInt()
private const val MUTED = 0xFF9AA4B2.toInt()
private const val ACCENT = 0xFF6EA8FF.toInt()
private const val SUCCESS = 0xFF69D38B.toInt()
private const val WARNING = 0xFFFFC56D.toInt()
}
}
@@ -0,0 +1,158 @@
package com.qft.optical
import org.json.JSONObject
import java.net.URI
data class WifiCredentials(
val ssid: String,
val passphrase: String,
val security: String,
)
data class PairingPayload(
val version: Int,
val session: String,
val pcName: String,
val transport: String,
val port: Int,
val endpoints: List<String>,
val wifi: WifiCredentials?,
)
object PairingProtocol {
const val PREFIX_V2 = "QFTPAIR2:"
const val PREFIX_V1 = "QFTPAIR1:"
fun isPairingText(text: String): Boolean = text.startsWith(PREFIX_V2) || text.startsWith(PREFIX_V1)
fun parse(text: String): PairingPayload? {
if (text.length > 4096) return null
return when {
text.startsWith(PREFIX_V2) -> parseV2(text.substring(PREFIX_V2.length))
text.startsWith(PREFIX_V1) -> parseV1(text.substring(PREFIX_V1.length))
else -> null
}
}
private fun parseV2(encoded: String): PairingPayload? {
return try {
val jsonBytes = decodeUrlBase64(encoded) ?: return null
if (jsonBytes.size > 2048) return null
val obj = JSONObject(jsonBytes.toString(Charsets.UTF_8))
if (obj.optInt("v", 0) != 2) return null
val session = obj.getString("s")
if (!validSession(session)) return null
val port = obj.getInt("p")
if (port !in 1..65535) return null
val wifiArray = obj.optJSONArray("w")
val wifi = if (wifiArray != null && wifiArray.length() >= 2) {
val ssid = wifiArray.optString(0)
val passphrase = wifiArray.optString(1)
if (!validWifi(ssid, passphrase)) return null
WifiCredentials(ssid, passphrase, "WPA2")
} else null
val endpoints = mutableListOf<String>()
obj.optJSONArray("e")?.let { arr ->
for (i in 0 until arr.length()) {
val value = arr.optString(i).trim().removeSuffix("/")
if (isAllowedLocalHttpEndpoint(value, port) && value !in endpoints) endpoints += value
}
}
// QFT Direct v2 can work with no QR-carried endpoint because UDP discovery
// and the actual Wi-Fi gateway are probed after Android obtains an IP.
if (wifi == null && endpoints.isEmpty()) return null
PairingPayload(
version = 2,
session = session,
pcName = obj.optString("n", "Windows-PC").take(80),
transport = "http-parallel-v2",
port = port,
endpoints = endpoints,
wifi = wifi,
)
} catch (_: Exception) {
null
}
}
private fun parseV1(encoded: String): PairingPayload? {
return try {
val jsonBytes = decodeUrlBase64(encoded) ?: return null
if (jsonBytes.size > 3072) return null
val obj = JSONObject(jsonBytes.toString(Charsets.UTF_8))
if (obj.optInt("v", 0) != 1) return null
val session = obj.getString("session")
if (!validSession(session)) return null
val transport = obj.optString("transport", "")
if (transport != "http-stream-v1") return null
val port = obj.getInt("port")
if (port !in 1..65535) return null
val endpoints = mutableListOf<String>()
val endpointsJson = obj.getJSONArray("endpoints")
for (i in 0 until endpointsJson.length()) {
val value = endpointsJson.optString(i).trim().removeSuffix("/")
if (isAllowedLocalHttpEndpoint(value, port) && value !in endpoints) endpoints += value
}
if (endpoints.isEmpty()) return null
val wifiObj = obj.optJSONObject("wifi")
val wifi = wifiObj?.let {
val ssid = it.getString("ssid")
val passphrase = it.getString("passphrase")
val security = it.optString("security", "WPA2")
if (!validWifi(ssid, passphrase) || security != "WPA2") return null
WifiCredentials(ssid, passphrase, security)
}
PairingPayload(
version = 1,
session = session,
pcName = obj.optString("pc_name", "Windows-PC").take(80),
transport = transport,
port = port,
endpoints = endpoints,
wifi = wifi,
)
} catch (_: Exception) {
null
}
}
private fun decodeUrlBase64(encoded: String): ByteArray? = Base64Url.decode(encoded)
private fun validSession(session: String): Boolean = session.matches(Regex("^[A-Za-z0-9_-]{20,64}$"))
private fun validWifi(ssid: String, passphrase: String): Boolean {
return ssid.isNotBlank() && ssid.toByteArray(Charsets.UTF_8).size <= 32 && passphrase.length in 8..63
}
/**
* Pairing QR is treated as untrusted input. QFT only probes literal local
* IPv4 addresses on the exact advertised port; public hosts and DNS names
* are rejected even though the app permits cleartext HTTP for local QFT.
*/
fun isAllowedLocalHttpEndpoint(value: String, expectedPort: Int): Boolean {
val uri = try { URI(value) } catch (_: Exception) { return false }
if (uri.scheme != "http" || uri.userInfo != null || uri.query != null || uri.fragment != null) return false
if (uri.port != expectedPort) return false
val host = uri.host ?: return false
val octets = host.split('.').map { it.toIntOrNull() ?: return false }
if (octets.size != 4 || octets.any { it !in 0..255 }) return false
val a = octets[0]
val b = octets[1]
return when {
a == 10 -> true
a == 127 -> true
a == 169 && b == 254 -> true
a == 172 && b in 16..31 -> true
a == 192 && b == 168 -> true
else -> false
}
}
}
@@ -0,0 +1,108 @@
package com.qft.optical
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.zip.CRC32
enum class FrameKind(val wire: Int) {
MANIFEST(1), DATA(2), END(3);
companion object {
fun fromWire(v: Int): FrameKind = entries.firstOrNull { it.wire == v }
?: error("unknown frame kind: $v")
}
}
data class QftFrame(
val kind: FrameKind,
val sessionId: Long,
val seq: Long,
val totalChunks: Long,
val payload: ByteArray,
)
data class Manifest(
val sessionId: Long,
val senderDevice: String,
val fileName: String,
val fileSize: Long,
val chunkSize: Int,
val totalChunks: Long,
val sha256: ByteArray,
)
object QftProtocol {
const val PREFIX = "QFT1:"
private const val VERSION = 1
fun parseText(text: String): QftFrame? {
if (!text.startsWith(PREFIX)) return null
val binary = try {
Base64Url.decode(text.substring(PREFIX.length)) ?: return null
} catch (_: IllegalArgumentException) {
return null
}
if (binary.size < 28) return null
val bodySize = binary.size - 4
val expectedCrc = ByteBuffer.wrap(binary, bodySize, 4)
.order(ByteOrder.BIG_ENDIAN)
.int.toLong() and 0xffff_ffffL
val crc = CRC32().apply { update(binary, 0, bodySize) }.value
if (crc != expectedCrc) return null
val bb = ByteBuffer.wrap(binary, 0, bodySize).order(ByteOrder.BIG_ENDIAN)
val magic = ByteArray(4).also(bb::get)
if (!magic.contentEquals(byteArrayOf('Q'.code.toByte(), 'F'.code.toByte(), 'T'.code.toByte(), '1'.code.toByte()))) {
return null
}
val version = bb.get().toInt() and 0xff
if (version != VERSION) return null
val kind = try { FrameKind.fromWire(bb.get().toInt() and 0xff) } catch (_: Exception) { return null }
val sessionId = bb.long
val seq = bb.int.toLong() and 0xffff_ffffL
val totalChunks = bb.int.toLong() and 0xffff_ffffL
val payloadLen = bb.short.toInt() and 0xffff
if (payloadLen != bb.remaining()) return null
val payload = ByteArray(payloadLen).also(bb::get)
return QftFrame(kind, sessionId, seq, totalChunks, payload)
}
fun parseManifest(frame: QftFrame): Manifest? {
if (frame.kind != FrameKind.MANIFEST || frame.payload.size < 44) return null
val bb = ByteBuffer.wrap(frame.payload).order(ByteOrder.BIG_ENDIAN)
val fileSize = bb.long
val chunkSize = bb.short.toInt() and 0xffff
val sha = ByteArray(32).also(bb::get)
val nameLen = bb.short.toInt() and 0xffff
if (nameLen > bb.remaining()) return null
val nameBytes = ByteArray(nameLen).also(bb::get)
val name = nameBytes.toString(Charsets.UTF_8)
.replace(Regex("[\\/:*?\"<>|]"), "_")
.ifBlank { "qft.bin" }
val senderDevice = if (bb.remaining() >= 2) {
val deviceLen = bb.short.toInt() and 0xffff
if (deviceLen > bb.remaining()) return null
ByteArray(deviceLen).also(bb::get)
.toString(Charsets.UTF_8)
.replace(Regex("[\u0000-\u001F\u007F]"), "")
.trim()
.ifBlank { "Windows-PC" }
} else {
// Backward compatibility with v0.1/v0.1.2 manifests.
"Windows-PC"
}
if (chunkSize <= 0) return null
return Manifest(
sessionId = frame.sessionId,
senderDevice = senderDevice,
fileName = name,
fileSize = fileSize,
chunkSize = chunkSize,
totalChunks = frame.totalChunks,
sha256 = sha,
)
}
}
@@ -0,0 +1,162 @@
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",
)
)
}
}
}
@@ -0,0 +1,192 @@
package com.qft.optical
import android.content.ContentValues
import android.content.Context
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import java.io.File
import java.io.FileInputStream
import java.io.RandomAccessFile
import java.security.MessageDigest
sealed interface ReceiveEvent {
data class Started(val manifest: Manifest) : ReceiveEvent
data class Progress(val manifest: Manifest, val received: Int, val total: Int) : ReceiveEvent
data class Completed(val manifest: Manifest, val savedName: String) : ReceiveEvent
data class Error(val message: String) : ReceiveEvent
}
class SessionAssembler(
private val context: Context,
private val onEvent: (ReceiveEvent) -> Unit,
) {
private var manifest: Manifest? = null
private var received: BooleanArray? = null
private var receivedCount = 0
private var tempFile: File? = null
private var raf: RandomAccessFile? = null
private var completedSession: Long? = null
@Synchronized
fun acceptText(text: String) {
val frame = QftProtocol.parseText(text) ?: return
if (completedSession == frame.sessionId) return
when (frame.kind) {
FrameKind.MANIFEST -> acceptManifest(frame)
FrameKind.DATA -> acceptData(frame)
FrameKind.END -> Unit
}
}
private fun acceptManifest(frame: QftFrame) {
val incoming = QftProtocol.parseManifest(frame) ?: return
val current = manifest
if (current?.sessionId == incoming.sessionId) return
reset()
if (incoming.totalChunks > Int.MAX_VALUE) {
onEvent(ReceiveEvent.Error("文件分片数过大"))
return
}
manifest = incoming
received = BooleanArray(incoming.totalChunks.toInt())
tempFile = File(context.cacheDir, "qft-${incoming.sessionId}.part")
raf = RandomAccessFile(tempFile!!, "rw").apply { setLength(incoming.fileSize) }
onEvent(ReceiveEvent.Started(incoming))
if (incoming.totalChunks == 0L) finalizeIfComplete()
}
private fun acceptData(frame: QftFrame) {
val m = manifest ?: return
if (frame.sessionId != m.sessionId) return
if (frame.totalChunks != m.totalChunks) return
if (frame.seq >= m.totalChunks) return
if (frame.payload.size > m.chunkSize) return
val expectedOffset = frame.seq * m.chunkSize.toLong()
val remaining = m.fileSize - expectedOffset
if (remaining < 0) return
val expectedLen = minOf(m.chunkSize.toLong(), remaining).toInt()
if (frame.payload.size != expectedLen) return
val flags = received ?: return
val index = frame.seq.toInt()
if (flags[index]) return
raf?.seek(expectedOffset)
raf?.write(frame.payload)
flags[index] = true
receivedCount++
onEvent(ReceiveEvent.Progress(m, receivedCount, flags.size))
finalizeIfComplete()
}
private fun finalizeIfComplete() {
val m = manifest ?: return
val flags = received ?: return
if (receivedCount != flags.size) return
raf?.fd?.sync()
raf?.close()
raf = null
val file = tempFile ?: return
val actual = sha256(file)
if (!actual.contentEquals(m.sha256)) {
onEvent(ReceiveEvent.Error("SHA-256 校验失败,等待下一会话重新发送"))
reset()
return
}
try {
saveToDownloads(file, m.fileName)
completedSession = m.sessionId
onEvent(ReceiveEvent.Completed(m, m.fileName))
reset(keepCompleted = true)
} catch (e: Exception) {
onEvent(ReceiveEvent.Error("保存失败:${e.message}"))
}
}
private fun sha256(file: File): ByteArray {
val digest = MessageDigest.getInstance("SHA-256")
FileInputStream(file).use { input ->
val buf = ByteArray(1024 * 1024)
while (true) {
val n = input.read(buf)
if (n <= 0) break
digest.update(buf, 0, n)
}
}
return digest.digest()
}
private fun saveToDownloads(source: File, name: String) {
if (Build.VERSION.SDK_INT >= 29) {
saveModern(source, name)
} else {
saveLegacy(source, name)
}
}
@android.annotation.TargetApi(29)
private fun saveModern(source: File, name: String) {
val values = ContentValues().apply {
put(MediaStore.Downloads.DISPLAY_NAME, name)
put(MediaStore.Downloads.MIME_TYPE, "application/octet-stream")
put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + "/QFT")
put(MediaStore.Downloads.IS_PENDING, 1)
}
val resolver = context.contentResolver
val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
?: error("MediaStore insert failed")
try {
resolver.openOutputStream(uri, "w")!!.use { out ->
source.inputStream().use { input -> input.copyTo(out, 1024 * 1024) }
}
values.clear()
values.put(MediaStore.Downloads.IS_PENDING, 0)
resolver.update(uri, values, null, null)
} catch (e: Exception) {
resolver.delete(uri, null, null)
throw e
}
}
@Suppress("DEPRECATION")
private fun saveLegacy(source: File, name: String) {
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "QFT")
if (!dir.exists() && !dir.mkdirs()) error("无法创建 Downloads/QFT")
val target = uniqueLegacyFile(dir, name)
source.inputStream().use { input ->
target.outputStream().use { output -> input.copyTo(output, 1024 * 1024) }
}
}
private fun uniqueLegacyFile(dir: File, original: String): File {
var candidate = File(dir, original)
if (!candidate.exists()) return candidate
val dot = original.lastIndexOf('.')
val stem = if (dot > 0) original.substring(0, dot) else original
val ext = if (dot > 0) original.substring(dot) else ""
var n = 1
while (candidate.exists()) {
candidate = File(dir, "$stem ($n)$ext")
n++
}
return candidate
}
@Synchronized
fun reset(keepCompleted: Boolean = false) {
try { raf?.close() } catch (_: Exception) {}
raf = null
tempFile?.delete()
tempFile = null
manifest = null
received = null
receivedCount = 0
if (!keepCompleted) completedSession = null
}
}
@@ -0,0 +1,473 @@
package com.qft.optical
import android.content.ContentResolver
import android.database.Cursor
import android.net.Network
import android.net.Uri
import android.provider.OpenableColumns
import org.json.JSONObject
import java.io.FileInputStream
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.HttpURLConnection
import java.net.InetAddress
import java.net.URL
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.util.concurrent.ExecutorCompletionService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
data class SelectedFile(
val uri: Uri,
val name: String,
val size: Long,
)
object UploadClient {
private const val DISCOVERY_PORT = 39392
private const val CHUNK_SMALL = 4L * 1024L * 1024L
private const val CHUNK_DEFAULT = 8L * 1024L * 1024L
private const val CHUNK_LARGE = 16L * 1024L * 1024L
private const val MAX_WORKERS = 8
private const val STREAM_BUFFER = 1024 * 1024
fun describeFile(resolver: ContentResolver, uri: Uri): SelectedFile? {
var name = "qft-upload.bin"
var size = -1L
var cursor: Cursor? = null
try {
cursor = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)
if (cursor?.moveToFirst() == true) {
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
if (nameIndex >= 0) name = cursor.getString(nameIndex) ?: name
if (sizeIndex >= 0 && !cursor.isNull(sizeIndex)) size = cursor.getLong(sizeIndex)
}
} finally {
cursor?.close()
}
if (size < 0) {
size = try { resolver.openAssetFileDescriptor(uri, "r")?.use { it.length } ?: -1L } catch (_: Exception) { -1L }
}
if (size < 0) return null
return SelectedFile(uri, name, size)
}
/** Fast path: ask the PC directly over UDP on the newly connected QFT Wi-Fi. */
fun discoverUdp(
network: Network?,
pairing: PairingPayload,
hosts: List<InetAddress>,
): String? {
if (hosts.isEmpty()) return null
val socket = DatagramSocket()
return try {
network?.bindSocket(socket)
socket.broadcast = true
socket.soTimeout = 220
val request = "QFTDISC2:${pairing.session}".toByteArray(Charsets.US_ASCII)
repeat(3) {
for (host in hosts) {
try { socket.send(DatagramPacket(request, request.size, host, DISCOVERY_PORT)) } catch (_: Exception) {}
}
val deadline = android.os.SystemClock.elapsedRealtime() + 320
while (android.os.SystemClock.elapsedRealtime() < deadline) {
val buf = ByteArray(512)
val packet = DatagramPacket(buf, buf.size)
try {
socket.receive(packet)
} catch (_: Exception) {
break
}
val text = String(packet.data, packet.offset, packet.length, Charsets.US_ASCII)
val prefix = "QFTHERE2:${pairing.session}:"
if (!text.startsWith(prefix)) continue
val port = text.substring(prefix.length).toIntOrNull() ?: continue
if (port != pairing.port) continue
val base = "http://${packet.address.hostAddress}:$port"
if (PairingProtocol.isAllowedLocalHttpEndpoint(base, pairing.port)) return base
}
}
null
} catch (_: Exception) {
null
} finally {
socket.close()
}
}
fun probeRobust(
network: Network?,
pairing: PairingPayload,
deviceName: String,
preferredEndpoints: List<String> = emptyList(),
discoveredEndpoint: String? = null,
subnetEndpoints: List<String> = emptyList(),
): String? {
val common = listOf(
"http://192.168.137.1:${pairing.port}",
"http://192.168.49.1:${pairing.port}",
)
val fast = (listOfNotNull(discoveredEndpoint) + preferredEndpoints + pairing.endpoints + common)
.map { it.trim().removeSuffix("/") }
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
.distinct()
// Stage 1: expected gateway/QR addresses. Repeat quickly because a Wi-Fi
// callback can precede ARP/firewall classification by a few hundred ms.
val fastDeadline = android.os.SystemClock.elapsedRealtime() + 2_400
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < fastDeadline) {
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 8, connectMs = 320, readMs = 380)
?.let { return it }
try { Thread.sleep(90) } catch (_: InterruptedException) { return null }
}
// Stage 2: actual connected subnet fallback. This specifically fixes the
// case where Windows Wi-Fi Direct is up but uses an unexpected gateway
// address. Up to /24 is scanned concurrently and still session-authenticated.
val scan = subnetEndpoints
.map { it.trim().removeSuffix("/") }
.filter { PairingProtocol.isAllowedLocalHttpEndpoint(it, pairing.port) }
.filterNot { it in fast }
.distinct()
if (scan.isNotEmpty()) {
probeCandidatesParallel(network, pairing, deviceName, scan, workers = 24, connectMs = 240, readMs = 300)
?.let { return it }
}
// Final short retry for the expected addresses after the subnet scan.
val deadline = android.os.SystemClock.elapsedRealtime() + 2_000
while (fast.isNotEmpty() && android.os.SystemClock.elapsedRealtime() < deadline) {
probeCandidatesParallel(network, pairing, deviceName, fast, workers = 8, connectMs = 450, readMs = 500)
?.let { return it }
try { Thread.sleep(120) } catch (_: InterruptedException) { return null }
}
return null
}
private fun probeCandidatesParallel(
network: Network?,
pairing: PairingPayload,
deviceName: String,
candidates: List<String>,
workers: Int,
connectMs: Int,
readMs: Int,
): String? {
if (candidates.isEmpty()) return null
val pool = Executors.newFixedThreadPool(candidates.size.coerceAtMost(workers).coerceAtLeast(1))
val completion = ExecutorCompletionService<String?>(pool)
candidates.forEach { base ->
completion.submit(java.util.concurrent.Callable<String?> {
if (probeOne(network, pairing, deviceName, base, connectMs, readMs)) base else null
})
}
return try {
val overallMs = (connectMs + readMs + 150).toLong() *
((candidates.size + workers - 1) / workers).coerceAtLeast(1)
val deadline = android.os.SystemClock.elapsedRealtime() + overallMs.coerceAtMost(4_500L)
repeat(candidates.size) {
val remaining = deadline - android.os.SystemClock.elapsedRealtime()
if (remaining <= 0) return null
val future = completion.poll(remaining.coerceAtMost(350L), TimeUnit.MILLISECONDS) ?: return@repeat
val result = future.get()
if (result != null) return result
}
null
} catch (_: Exception) {
null
} finally {
pool.shutdownNow()
}
}
private fun probeOne(
network: Network?, pairing: PairingPayload, deviceName: String, base: String,
connectMs: Int, readMs: Int,
): Boolean {
var conn: HttpURLConnection? = null
return try {
conn = open(network, URL("$base/qft/ping"))
conn.requestMethod = "GET"
conn.connectTimeout = connectMs
conn.readTimeout = readMs
conn.useCaches = false
conn.setRequestProperty("X-QFT-Token", pairing.session)
conn.setRequestProperty("X-QFT-Device", b64(deviceName))
conn.responseCode == 200
} catch (_: Exception) {
false
} finally {
conn?.disconnect()
}
}
fun upload(
resolver: ContentResolver,
network: Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
file: SelectedFile,
onProgress: (sent: Long, total: Long) -> Unit,
) {
if (pairing.version >= 2 && isSeekable(resolver, file)) {
try {
uploadParallel(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
return
} catch (e: Exception) {
// If the provider cannot sustain random access or the v2 endpoint
// is unavailable, preserve compatibility with the v1 stream path.
if (e is SecurityException) throw e
}
}
uploadLegacy(resolver, network, baseUrl, pairing, deviceName, file, onProgress)
}
private data class InitReply(val uploadId: String, val chunkSize: Long, val totalChunks: Int)
private fun uploadParallel(
resolver: ContentResolver,
network: Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
file: SelectedFile,
onProgress: (sent: Long, total: Long) -> Unit,
) {
val init = initUpload(network, baseUrl, pairing, deviceName, file)
if (init.totalChunks == 0) {
finishUpload(network, baseUrl, pairing, deviceName, init.uploadId)
onProgress(0, 0)
return
}
val cpuWorkers = Runtime.getRuntime().availableProcessors().coerceIn(2, MAX_WORKERS)
val workerCount = init.totalChunks.coerceAtMost(cpuWorkers).coerceAtLeast(1)
val pool = Executors.newFixedThreadPool(workerCount)
val next = AtomicInteger(0)
val sent = AtomicLong(0)
val lastReport = AtomicLong(0)
val failures = mutableListOf<Throwable>()
val futures = (0 until workerCount).map {
pool.submit {
resolver.openFileDescriptor(file.uri, "r")?.use { pfd ->
FileInputStream(pfd.fileDescriptor).use { input ->
val channel = input.channel
val buffer = ByteBuffer.allocate(STREAM_BUFFER)
while (!Thread.currentThread().isInterrupted) {
val index = next.getAndIncrement()
if (index >= init.totalChunks) break
val offset = index.toLong() * init.chunkSize
val length = minOf(init.chunkSize, file.size - offset)
sendChunk(
network, baseUrl, pairing, deviceName,
init.uploadId, index, channel, offset, length, buffer,
)
val totalSent = sent.addAndGet(length)
val now = android.os.SystemClock.elapsedRealtime()
val previous = lastReport.get()
if (now - previous >= 80 && lastReport.compareAndSet(previous, now)) {
onProgress(totalSent.coerceAtMost(file.size), file.size)
}
}
}
} ?: error("无法打开 ${file.name}")
}
}
try {
futures.forEach { future ->
try { future.get() } catch (e: Exception) { failures += (e.cause ?: e) }
}
} finally {
pool.shutdownNow()
}
if (failures.isNotEmpty()) throw failures.first()
finishUpload(network, baseUrl, pairing, deviceName, init.uploadId)
onProgress(file.size, file.size)
}
private fun desiredChunkSize(fileSize: Long): Long = when {
fileSize < 32L * 1024L * 1024L -> CHUNK_SMALL
fileSize >= 512L * 1024L * 1024L -> CHUNK_LARGE
else -> CHUNK_DEFAULT
}
private fun initUpload(
network: Network?, baseUrl: String, pairing: PairingPayload,
deviceName: String, file: SelectedFile,
): InitReply {
val conn = open(network, URL("$baseUrl/qft/upload/init"))
try {
conn.requestMethod = "POST"
conn.doOutput = true
conn.connectTimeout = 3_000
conn.readTimeout = 6_000
conn.setFixedLengthStreamingMode(0)
commonHeaders(conn, pairing, deviceName)
conn.setRequestProperty("X-QFT-Filename", b64(file.name))
conn.setRequestProperty("X-QFT-Size", file.size.toString())
conn.setRequestProperty("X-QFT-Chunk-Size", desiredChunkSize(file.size).toString())
conn.outputStream.close()
val code = conn.responseCode
if (code != 200) error("初始化并行上传失败 HTTP $code")
val body = conn.inputStream.bufferedReader().use { it.readText() }
val obj = JSONObject(body)
return InitReply(
uploadId = obj.getString("upload_id"),
chunkSize = obj.getLong("chunk_size"),
totalChunks = obj.getInt("total_chunks"),
)
} finally {
conn.disconnect()
}
}
private fun sendChunk(
network: Network?, baseUrl: String, pairing: PairingPayload, deviceName: String,
uploadId: String, index: Int, channel: FileChannel, offset: Long, length: Long,
buffer: ByteBuffer,
) {
val conn = open(network, URL("$baseUrl/qft/upload/chunk/$uploadId/$index"))
try {
conn.requestMethod = "POST"
conn.doOutput = true
conn.connectTimeout = 4_000
conn.readTimeout = 15_000
conn.setFixedLengthStreamingMode(length)
conn.setRequestProperty("Content-Type", "application/octet-stream")
commonHeaders(conn, pairing, deviceName)
channel.position(offset)
conn.outputStream.use { output ->
var remaining = length
val array = buffer.array()
while (remaining > 0) {
buffer.clear()
buffer.limit(minOf(array.size.toLong(), remaining).toInt())
val n = channel.read(buffer)
if (n <= 0) error("读取文件分块提前结束")
output.write(array, 0, n)
remaining -= n.toLong()
}
output.flush()
}
val code = conn.responseCode
if (code != 200) {
val message = try { conn.errorStream?.bufferedReader()?.use { it.readText() } } catch (_: Exception) { null }
error("分块 $index 上传失败 HTTP $code${message?.let { ": $it" } ?: ""}")
}
try { conn.inputStream.close() } catch (_: Exception) {}
} finally {
conn.disconnect()
}
}
private fun finishUpload(
network: Network?, baseUrl: String, pairing: PairingPayload,
deviceName: String, uploadId: String,
) {
val conn = open(network, URL("$baseUrl/qft/upload/finish/$uploadId"))
try {
conn.requestMethod = "POST"
conn.doOutput = true
conn.connectTimeout = 4_000
conn.readTimeout = 120_000
conn.setFixedLengthStreamingMode(0)
commonHeaders(conn, pairing, deviceName)
conn.outputStream.close()
val code = conn.responseCode
if (code != 200) {
val message = try { conn.errorStream?.bufferedReader()?.use { it.readText() } } catch (_: Exception) { null }
error("完成上传失败 HTTP $code${message?.let { ": $it" } ?: ""}")
}
conn.inputStream.close()
} finally {
conn.disconnect()
}
}
private fun uploadLegacy(
resolver: ContentResolver,
network: Network?,
baseUrl: String,
pairing: PairingPayload,
deviceName: String,
file: SelectedFile,
onProgress: (sent: Long, total: Long) -> Unit,
) {
val conn = open(network, URL("$baseUrl/qft/upload"))
conn.requestMethod = "POST"
conn.doOutput = true
conn.connectTimeout = 8_000
conn.readTimeout = 30_000
conn.setFixedLengthStreamingMode(file.size)
conn.setRequestProperty("Content-Type", "application/octet-stream")
commonHeaders(conn, pairing, deviceName)
conn.setRequestProperty("X-QFT-Filename", b64(file.name))
conn.setRequestProperty("X-QFT-Size", file.size.toString())
resolver.openInputStream(file.uri).use { input ->
requireNotNull(input) { "无法打开 ${file.name}" }
conn.outputStream.use { output ->
val buf = ByteArray(STREAM_BUFFER)
var sent = 0L
var lastReport = 0L
while (true) {
val n = input.read(buf)
if (n <= 0) break
output.write(buf, 0, n)
sent += n
val now = android.os.SystemClock.elapsedRealtime()
if (now - lastReport >= 100 || sent == file.size) {
onProgress(sent, file.size)
lastReport = now
}
}
output.flush()
}
}
val code = conn.responseCode
if (code != 200) {
val message = try { conn.errorStream?.bufferedReader()?.use { it.readText() } } catch (_: Exception) { null }
conn.disconnect()
error("电脑返回 HTTP $code${message?.let { ": $it" } ?: ""}")
}
conn.inputStream.close()
conn.disconnect()
}
private fun isSeekable(resolver: ContentResolver, file: SelectedFile): Boolean {
if (file.size <= 0) return true
return try {
resolver.openFileDescriptor(file.uri, "r")?.use { pfd ->
FileInputStream(pfd.fileDescriptor).use { input ->
val channel = input.channel
val target = minOf(file.size - 1, 4096L).coerceAtLeast(0)
channel.position(target)
channel.position() == target
}
} ?: false
} catch (_: Exception) {
false
}
}
private fun commonHeaders(conn: HttpURLConnection, pairing: PairingPayload, deviceName: String) {
conn.useCaches = false
conn.setRequestProperty("Connection", "close")
conn.setRequestProperty("X-QFT-Token", pairing.session)
conn.setRequestProperty("X-QFT-Device", b64(deviceName))
}
private fun open(network: Network?, url: URL): HttpURLConnection {
return (network?.openConnection(url) ?: url.openConnection()) as HttpURLConnection
}
private fun b64(value: String): String = Base64Url.encode(value.toByteArray(Charsets.UTF_8))
}
@@ -0,0 +1,310 @@
package com.qft.optical
import android.content.Context
import android.net.ConnectivityManager
import android.net.LinkProperties
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.net.wifi.WifiNetworkSpecifier
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import java.net.Inet4Address
import java.net.InetAddress
class WifiConnector(context: Context) {
private val appContext = context.applicationContext
private val connectivity = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private val wifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
private val handler = Handler(Looper.getMainLooper())
private var callback: ConnectivityManager.NetworkCallback? = null
private var generation = 0
private var legacyPreviousNetworkId: Int? = null
private var legacyTargetNetworkId: Int? = null
fun connect(
pairing: PairingPayload,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
release(restoreLegacy = false)
generation++
val run = generation
val wifi = pairing.wifi
if (wifi == null) {
onStatus("正在使用当前局域网发现电脑…")
val wifiNetwork = bestWifiNetwork()
onAvailable(wifiNetwork ?: connectivity.activeNetwork)
return
}
if (Build.VERSION.SDK_INT >= 29) {
connectModern(run, wifi, onStatus, onAvailable, onUnavailable)
} else {
connectLegacy(run, wifi, onStatus, onAvailable, onUnavailable)
}
}
private fun connectModern(
run: Int,
wifi: WifiCredentials,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
onStatus("正在请求连接 ${wifi.ssid}…")
val specifier = try {
WifiNetworkSpecifier.Builder()
.setSsid(wifi.ssid)
.setWpa2Passphrase(wifi.passphrase)
.build()
} catch (e: Exception) {
onUnavailable("配网参数无效:${e.message}")
return
}
val request = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.setNetworkSpecifier(specifier)
.build()
val delivered = booleanArrayOf(false)
val cb = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
if (run != generation) return
onStatus("Wi-Fi 已关联,正在等待本地 IP/路由…")
waitUntilUsable(run, network, onStatus) {
if (!delivered[0] && run == generation) {
delivered[0] = true
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
onAvailable(network)
}
}
}
override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
if (run != generation || delivered[0]) return
if (hasIpv4(linkProperties)) {
delivered[0] = true
onStatus("QFT 本地网络已就绪,正在快速发现电脑…")
onAvailable(network)
}
}
override fun onUnavailable() {
if (run == generation) onUnavailable("未能连接 QFT 临时网络。请确认 Wi-Fi 已开启并批准系统连接请求。")
}
override fun onLost(network: Network) {
if (run == generation && delivered[0]) onUnavailable("QFT 临时网络已断开")
}
}
callback = cb
try {
connectivity.requestNetwork(request, cb, 15_000)
handler.postDelayed({
if (run == generation && !delivered[0]) {
onStatus("仍在等待系统完成配网…")
}
}, 8_000)
} catch (e: Exception) {
callback = null
onUnavailable("系统配网请求失败:${e.message}")
}
}
@Suppress("DEPRECATION")
private fun connectLegacy(
run: Int,
wifi: WifiCredentials,
onStatus: (String) -> Unit,
onAvailable: (Network?) -> Unit,
onUnavailable: (String) -> Unit,
) {
onStatus("Android ${Build.VERSION.RELEASE} 兼容配网:正在连接 ${wifi.ssid}…")
try {
if (!wifiManager.isWifiEnabled) {
wifiManager.isWifiEnabled = true
}
legacyPreviousNetworkId = wifiManager.connectionInfo?.networkId?.takeIf { it >= 0 }
val quoted = "\"${wifi.ssid}\""
val existing = try { wifiManager.configuredNetworks?.firstOrNull { it.SSID == quoted } } catch (_: Exception) { null }
val targetId = if (existing != null) {
existing.networkId
} else {
val config = WifiConfiguration().apply {
SSID = quoted
preSharedKey = "\"${wifi.passphrase}\""
allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK)
}
wifiManager.addNetwork(config)
}
if (targetId < 0) {
onUnavailable("Android 7~9 无法写入 QFT Wi-Fi 配置;请确认已授予位置权限。")
return
}
legacyTargetNetworkId = targetId
wifiManager.disconnect()
if (!wifiManager.enableNetwork(targetId, true)) {
onUnavailable("系统拒绝启用 QFT Wi-Fi 网络")
return
}
wifiManager.reconnect()
val started = SystemClock.elapsedRealtime()
fun poll() {
if (run != generation) return
val info = wifiManager.connectionInfo
val matches = info != null && (info.networkId == targetId || normalizeSsid(info.ssid) == wifi.ssid)
if (matches) {
val network = bestWifiNetwork()
if (network != null && hasIpv4(connectivity.getLinkProperties(network))) {
onStatus("QFT Wi-Fi 已连接,正在快速发现电脑…")
onAvailable(network)
return
}
}
if (SystemClock.elapsedRealtime() - started > 15_000) {
onUnavailable("连接 QFT Wi-Fi 超时。请确认电脑热点仍在运行。")
} else {
handler.postDelayed({ poll() }, 250)
}
}
handler.postDelayed({ poll() }, 250)
} catch (e: Exception) {
onUnavailable("Android 7~9 配网失败:${e.message}")
}
}
private fun waitUntilUsable(run: Int, network: Network, onStatus: (String) -> Unit, done: () -> Unit) {
val started = SystemClock.elapsedRealtime()
fun poll() {
if (run != generation) return
if (hasIpv4(connectivity.getLinkProperties(network))) {
done()
return
}
if (SystemClock.elapsedRealtime() - started > 6_000) {
onStatus("网络已连接但路由仍未就绪,继续尝试电脑发现…")
done()
} else {
handler.postDelayed({ poll() }, 120)
}
}
poll()
}
private fun bestWifiNetwork(): Network? = connectivity.allNetworks.firstOrNull { network ->
val caps = connectivity.getNetworkCapabilities(network)
caps?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true && hasIpv4(connectivity.getLinkProperties(network))
}
private fun hasIpv4(props: LinkProperties?): Boolean = props?.linkAddresses?.any { it.address is Inet4Address } == true
fun gatewayEndpoints(network: Network?, port: Int): List<String> {
if (network == null) return emptyList()
val props = connectivity.getLinkProperties(network) ?: return emptyList()
return props.routes
.asSequence()
.mapNotNull { it.gateway as? Inet4Address }
.map { "http://${it.hostAddress}:$port" }
.distinct()
.toList()
}
fun discoveryHosts(network: Network?): List<InetAddress> {
val out = mutableListOf<InetAddress>()
if (network != null) {
val props = connectivity.getLinkProperties(network)
props?.routes
?.mapNotNull { it.gateway as? Inet4Address }
?.forEach { if (it !in out) out += it }
// Directed broadcast is more reliable than 255.255.255.255 on some
// Wi-Fi drivers/local-only networks. Derive it from the actual link.
props?.linkAddresses
?.filter { it.address is Inet4Address }
?.mapNotNull { directedBroadcast(it.address as Inet4Address, it.prefixLength) }
?.forEach { if (it !in out) out += it }
}
try {
val broadcast = InetAddress.getByName("255.255.255.255")
if (broadcast !in out) out += broadcast
} catch (_: Exception) {}
return out
}
/**
* Last-resort receiver discovery. Enumerates at most one /24 around the
* phone's actual QFT Wi-Fi address (<=254 hosts) so a nonstandard Windows
* Direct-AP gateway can still be found without guessing 192.168.137.1.
*/
fun subnetEndpoints(network: Network?, port: Int): List<String> {
if (network == null) return emptyList()
val props = connectivity.getLinkProperties(network) ?: return emptyList()
val out = LinkedHashSet<String>()
for (link in props.linkAddresses) {
val addr = link.address as? Inet4Address ?: continue
val octets = addr.address.map { it.toInt() and 0xFF }
// Never scan more than /24. For a narrower real subnet (/25 etc),
// respect its prefix and enumerate fewer hosts.
val prefix = link.prefixLength.coerceIn(24, 30)
val ip = (octets[0] shl 24) or (octets[1] shl 16) or (octets[2] shl 8) or octets[3]
val mask = if (prefix == 0) 0 else (-1 shl (32 - prefix))
val networkInt = ip and mask
val broadcastInt = networkInt or mask.inv()
for (candidate in (networkInt + 1) until broadcastInt) {
if (candidate == ip) continue
val host = "%d.%d.%d.%d".format(
(candidate ushr 24) and 0xFF,
(candidate ushr 16) and 0xFF,
(candidate ushr 8) and 0xFF,
candidate and 0xFF,
)
out += "http://$host:$port"
}
}
return out.toList()
}
private fun directedBroadcast(address: Inet4Address, prefixLength: Int): InetAddress? {
if (prefixLength !in 1..30) return null
val b = address.address.map { it.toInt() and 0xFF }
val ip = (b[0] shl 24) or (b[1] shl 16) or (b[2] shl 8) or b[3]
val mask = -1 shl (32 - prefixLength)
val broadcast = (ip and mask) or mask.inv()
val bytes = byteArrayOf(
((broadcast ushr 24) and 0xFF).toByte(),
((broadcast ushr 16) and 0xFF).toByte(),
((broadcast ushr 8) and 0xFF).toByte(),
(broadcast and 0xFF).toByte(),
)
return try { InetAddress.getByAddress(bytes) } catch (_: Exception) { null }
}
@Suppress("DEPRECATION")
fun release(restoreLegacy: Boolean = true) {
generation++
callback?.let {
try { connectivity.unregisterNetworkCallback(it) } catch (_: Exception) {}
}
callback = null
handler.removeCallbacksAndMessages(null)
if (restoreLegacy && Build.VERSION.SDK_INT < 29) {
val previous = legacyPreviousNetworkId
if (previous != null && previous >= 0) {
try {
wifiManager.enableNetwork(previous, true)
wifiManager.reconnect()
} catch (_: Exception) {}
}
}
legacyPreviousNetworkId = null
legacyTargetNetworkId = null
}
private fun normalizeSsid(value: String?): String = value.orEmpty().removePrefix("\"").removeSuffix("\"")
}
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="QftTheme" parent="android:style/Theme.Material.Light.NoActionBar">
<item name="android:windowActionModeOverlay">true</item>
<item name="android:windowBackground">@android:color/black</item>
<item name="android:navigationBarColor">@android:color/black</item>
<item name="android:statusBarColor">@android:color/black</item>
</style>
</resources>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<!-- QFTPAIR validation only permits literal private/local IPv4 endpoints.
Local HTTP is intentionally enabled because the direct PC hotspot has no
public DNS/certificate infrastructure. The per-session token still
authenticates every request. -->
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
@@ -0,0 +1,75 @@
package com.qft.optical
import org.junit.Assert.*
import org.junit.Test
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.Base64
import java.util.zip.CRC32
class ProtocolTest {
@Test
fun parsesDataFrameAndRejectsCorruption() {
val payload = byteArrayOf(1, 2, 3, 4, 5)
val text = encode(kind = 2, session = 7L, seq = 9, total = 11, payload = payload)
val f = QftProtocol.parseText(text)!!
assertEquals(FrameKind.DATA, f.kind)
assertEquals(7L, f.sessionId)
assertEquals(9L, f.seq)
assertArrayEquals(payload, f.payload)
val corrupted = text.dropLast(1) + if (text.last() == 'A') "B" else "A"
assertNull(QftProtocol.parseText(corrupted))
}
@Test
fun parsesCrossLanguageKnownVector() {
val text = "QFT1:UUZUMQECAQIDBAUGBwgAAAADAAAACgAJaGVsbG8tcWZ0XhNTAg"
val f = QftProtocol.parseText(text)!!
assertEquals(FrameKind.DATA, f.kind)
assertEquals(0x0102030405060708L, f.sessionId)
assertEquals(3L, f.seq)
assertEquals(10L, f.totalChunks)
assertEquals("hello-qft", f.payload.toString(Charsets.UTF_8))
}
@Test
fun parsesManifestSenderDevice() {
val name = "test.txt".toByteArray()
val device = "DESKTOP-ZHY".toByteArray()
val sha = ByteArray(32) { it.toByte() }
val payload = ByteBuffer.allocate(8 + 2 + 32 + 2 + name.size + 2 + device.size)
.order(ByteOrder.BIG_ENDIAN)
.putLong(1234L)
.putShort(700.toShort())
.put(sha)
.putShort(name.size.toShort())
.put(name)
.putShort(device.size.toShort())
.put(device)
.array()
val text = encode(kind = 1, session = 77L, seq = 0, total = 2, payload = payload)
val frame = QftProtocol.parseText(text)!!
val manifest = QftProtocol.parseManifest(frame)!!
assertEquals("DESKTOP-ZHY", manifest.senderDevice)
assertEquals("test.txt", manifest.fileName)
assertEquals(1234L, manifest.fileSize)
assertEquals(700, manifest.chunkSize)
}
private fun encode(kind: Int, session: Long, seq: Int, total: Int, payload: ByteArray): String {
val bb = ByteBuffer.allocate(24 + payload.size + 4).order(ByteOrder.BIG_ENDIAN)
bb.put("QFT1".toByteArray())
bb.put(1)
bb.put(kind.toByte())
bb.putLong(session)
bb.putInt(seq)
bb.putInt(total)
bb.putShort(payload.size.toShort())
bb.put(payload)
val bodyLen = bb.position()
val crc = CRC32().apply { update(bb.array(), 0, bodyLen) }.value
bb.putInt(crc.toInt())
return "QFT1:" + Base64.getUrlEncoder().withoutPadding().encodeToString(bb.array())
}
}
+8
View File
@@ -0,0 +1,8 @@
$ErrorActionPreference = "Stop"
$jar = Join-Path $PSScriptRoot "gradle\wrapper\gradle-wrapper.jar"
$url = "https://raw.githubusercontent.com/gradle/gradle/v8.11.1/gradle/wrapper/gradle-wrapper.jar"
if (-not (Test-Path $jar)) {
Write-Host "Downloading Gradle wrapper jar..."
Invoke-WebRequest -Uri $url -OutFile $jar
}
Write-Host "Gradle wrapper ready: $jar"
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env sh
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
JAR="$ROOT/gradle/wrapper/gradle-wrapper.jar"
URL="https://raw.githubusercontent.com/gradle/gradle/v8.11.1/gradle/wrapper/gradle-wrapper.jar"
if [ ! -f "$JAR" ]; then
echo "Downloading Gradle wrapper jar..."
if command -v curl >/dev/null 2>&1; then
curl -fL "$URL" -o "$JAR"
elif command -v wget >/dev/null 2>&1; then
wget -O "$JAR" "$URL"
else
echo "Need curl or wget" >&2
exit 1
fi
fi
echo "Gradle wrapper ready: $JAR"
+4
View File
@@ -0,0 +1,4 @@
plugins {
id("com.android.application") version "8.9.1" apply false
id("org.jetbrains.kotlin.android") version "2.1.20" apply false
}
+2
View File
@@ -0,0 +1,2 @@
org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8
android.useAndroidX=true
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
APP_HOME=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
exec java -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
+3
View File
@@ -0,0 +1,3 @@
@echo off
set APP_HOME=%~dp0
java -classpath "%APP_HOME%gradle\wrapper\gradle-wrapper.jar" org.gradle.wrapper.GradleWrapperMain %*
+3
View File
@@ -0,0 +1,3 @@
# Copy this file to local.properties and point it to your Android SDK.
# Forward slashes avoid escaping problems on Windows.
sdk.dir=E:/SYSTEM/APPDATA/Android_SDK
+68
View File
@@ -0,0 +1,68 @@
param(
[string]$Sdk = "E:\SYSTEM\APPDATA\Android_SDK"
)
$ErrorActionPreference = "Stop"
$Project = $PSScriptRoot
$SdkManager = Join-Path $Sdk "cmdline-tools\latest\bin\sdkmanager.bat"
Write-Host "QFT Android build repair" -ForegroundColor Cyan
Write-Host "Project: $Project"
Write-Host "SDK: $Sdk"
if (-not (Test-Path $Sdk)) {
throw "Android SDK not found: $Sdk"
}
if (-not (Test-Path $SdkManager)) {
throw "sdkmanager not found: $SdkManager`nInstall Android SDK Command-line Tools (latest) from Android Studio > SDK Manager > SDK Tools."
}
$javaVersion = (& java -version 2>&1 | Select-Object -First 1)
Write-Host "Java: $javaVersion"
if (-not (Get-Command javac -ErrorAction SilentlyContinue)) {
throw "javac was not found. Configure Android Studio Gradle JDK to JDK 17 (full JDK, not a JRE)."
}
# Force Gradle and Android Studio project import to use the same SDK.
$SdkForProperties = $Sdk -replace '\\','/'
"sdk.dir=$SdkForProperties" | Set-Content -Encoding ASCII (Join-Path $Project "local.properties")
Write-Host "Installing/repairing API 35 platform and Build Tools 35.0.0..." -ForegroundColor Yellow
& $SdkManager --install "platforms;android-35" "build-tools;35.0.0" "platform-tools"
if ($LASTEXITCODE -ne 0) { throw "sdkmanager failed with exit code $LASTEXITCODE" }
$AndroidJar = Join-Path $Sdk "platforms\android-35\android.jar"
if (-not (Test-Path $AndroidJar)) {
throw "android-35/android.jar is still missing after installation: $AndroidJar"
}
Write-Host "Stopping Gradle daemons..."
Push-Location $Project
try {
if (-not (Test-Path (Join-Path $Project "gradle\wrapper\gradle-wrapper.jar"))) {
& (Join-Path $Project "bootstrap-wrapper.ps1")
}
& .\gradlew.bat --stop
Write-Host "Clearing project Gradle state..."
Remove-Item (Join-Path $Project ".gradle") -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item (Join-Path $Project "app\build") -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "Gradle environment:" -ForegroundColor Cyan
& .\gradlew.bat --version
Write-Host "Building debug APK..." -ForegroundColor Green
& .\gradlew.bat clean :app:assembleDebug --stacktrace
if ($LASTEXITCODE -ne 0) { throw "Gradle build failed with exit code $LASTEXITCODE" }
$Apk = Join-Path $Project "app\build\outputs\apk\debug\app-debug.apk"
if (Test-Path $Apk) {
Write-Host "SUCCESS: $Apk" -ForegroundColor Green
} else {
Write-Warning "Build completed but APK was not found at the expected path: $Apk"
}
}
finally {
Pop-Location
}
+18
View File
@@ -0,0 +1,18 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "QftOpticalAndroid"
include(":app")
+86
View File
@@ -0,0 +1,86 @@
# QFT protocol overview · v0.3.0-rc3
## QFT1 — Windows → Android optical stream
Wire text:
`QFT1:<base64url(binary frame)>`
Binary frame fields:
- magic `QFT1`
- protocol version
- frame kind: MANIFEST / DATA / END
- session id
- sequence index
- total chunks
- payload length
- payload
- CRC32
MANIFEST contains file name, file size, chunk size, total chunks, SHA-256 and Windows sender-device name. DATA frames are replayed cyclically; Android de-duplicates chunks and waits for missing chunks in later rounds. No Android→Windows feedback channel is used in optical mode.
v0.3 defaults: 900-byte DATA payload, 4 QR/page, target up to 60 pages/s.
## QFTPAIR2 — Android → Windows pairing
Text:
`QFTPAIR2:<base64url(compact JSON)>`
Compact JSON keys:
- `v`: 2
- `s`: one-time session token
- `n`: Windows device name
- `p`: receiver TCP port
- `e`: local HTTP endpoint hints; Direct AP normally carries one short hint
- `w`: optional `[ssid, passphrase]` for QFT Direct
QFTPAIR1 remains parser-compatible for older QR payloads.
Android treats pairing QR as untrusted. HTTP endpoint hints must be literal private/local IPv4 addresses on the advertised port. Every `/qft/*` request must carry the one-time `X-QFT-Token` session value.
## Receiver discovery
UDP request to port 39392:
`QFTDISC2:<session>`
Windows response:
`QFTHERE2:<session>:<tcp_port>`
Android combines UDP result with QR hint, the actual connected Wi-Fi gateway, common Windows local addresses and a bounded current-subnet fallback scan.
## Parallel v2 upload
### Ping
`GET /qft/ping`
Headers include `X-QFT-Token` and encoded Android device name.
### Init
`POST /qft/upload/init`
Headers include file name, file size and desired chunk size. Android requests 4/8/16 MiB depending on file size; Windows clamps accepted chunks to 1~16 MiB.
Response includes `upload_id`, accepted `chunk_size`, and `total_chunks`.
### Chunk
`POST /qft/upload/chunk/<upload_id>/<index>`
Body is exactly that file range. Up to eight Android workers send distinct chunks concurrently. Windows writes each accepted chunk to the preallocated `.qftpart` file at its deterministic offset.
### Finish
`POST /qft/upload/finish/<upload_id>`
Windows rejects finish while chunks are missing. Once complete it computes SHA-256, renames the temporary file to its final unique name, and returns success.
### Compatibility
`POST /qft/upload` remains the single-stream fallback for old clients or content providers that cannot sustain seekable parallel reads.
+58
View File
@@ -0,0 +1,58 @@
# Roadmap
## V0.1 — 单 QR 无网络链路(当前)
- Windows 选择文件
- 单 QR 动画
- Android CameraX 连续识别
- CRC32
- SHA-256
- 重复帧去重
- 多轮补洞
- 保存 Downloads/QFT
目标不是速度,而是证明:**飞行模式下可稳定完整恢复真实文件**。
## V0.2 — 扫码稳定性
- 自动曝光/对焦锁定
- 只分析中央 ROI
- 720p/1080p 自适应
- 帧序号抖动统计
- 自动 FPS 调节
- QR 版本/纠错级别动态选择
- Android 前台常亮、屏幕方向锁定
## V0.3 — 多 QR
- Windows 2x2 -> 3x3 网格
- Android 一帧多码检测
- 每个位置独立 lane
- lane interleave,避免同一丢帧损失连续数据
## V0.4 — Fountain / RaptorQ
- source block / symbol
- 无需等待指定 seq
- 达到恢复阈值即可完成
- 发送端持续产生 repair symbols
- 删除“整文件循环重播”的尾部等待
## V0.5 — QFT Visual Code
- 固定四角定位
- 自定义二值网格
- BCH/LDPC 内层纠错
- SIMD 二值化与采样
- 60/120 FPS
- 标定显示器刷新率与相机 rolling shutter
## V0.6 — Android -> Windows
这个方向因 PC 可能无摄像头,使用 App P2P:
- 同 LAN
- 临时热点
- Wi-Fi Direct(可用平台)
- QUIC
- 不经过外网/云端
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
from pathlib import Path
import re
ROOT = Path(__file__).resolve().parents[1]
gradle = (ROOT/'android/app/build.gradle.kts').read_text()
manifest = (ROOT/'android/app/src/main/AndroidManifest.xml').read_text()
wifi = (ROOT/'android/app/src/main/java/com/qft/optical/WifiConnector.kt').read_text()
upload = (ROOT/'android/app/src/main/java/com/qft/optical/UploadClient.kt').read_text()
main = (ROOT/'android/app/src/main/java/com/qft/optical/MainActivity.kt').read_text()
gray = (ROOT/'android/app/src/main/java/com/qft/optical/GrayFrame.kt').read_text()
security = (ROOT/'android/app/src/main/res/xml/network_security_config.xml').read_text()
assert re.search(r'minSdk\s*=\s*24', gradle)
assert 'WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28"' in manifest
assert 'ACCESS_FINE_LOCATION" android:maxSdkVersion="32"' in manifest
assert 'NEARBY_WIFI_DEVICES' in manifest
assert 'networkSecurityConfig="@xml/network_security_config"' in manifest
assert 'cleartextTrafficPermitted="true"' in security
assert 'Build.VERSION.SDK_INT >= 29' in wifi and 'connectLegacy' in wifi
assert 'subnetEndpoints' in wifi and 'directedBroadcast' in wifi
assert 'MAX_WORKERS = 8' in upload and 'QFTDISC2:' in upload and 'workers = 24' in upload and 'desiredChunkSize' in upload and 'CHUNK_LARGE' in upload
assert 'Size(640, 480)' in main and 'Size(1280, 720)' in main
assert 'STRATEGY_KEEP_ONLY_LATEST' in main
assert 'rotate90' not in gray and 'image.imageInfo.rotationDegrees' not in gray
all_kotlin = '\n'.join(path.read_text() for path in (ROOT/'android/app/src/main/java/com/qft/optical').glob('*.kt'))
assert 'java.util.Base64' not in all_kotlin
print('PASS Android compatibility/static guards: minSdk24, API29 split, legacy storage/location, Android13 nearby-WiFi, cleartext local config, subnet fallback, fast scanner paths')
@@ -0,0 +1,96 @@
#!/usr/bin/env python3
"""Loopback integration test for QFTDISC2 + Parallel v2 init/chunk/finish semantics."""
import hashlib, http.client, json, os, random, socket, tempfile, threading, time
from concurrent.futures import ThreadPoolExecutor
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
TOKEN = "integration_session_128bit_ABC"
DISCOVERY_MAGIC = f"QFTDISC2:{TOKEN}".encode()
CHUNK = 8 * 1024 * 1024
with tempfile.TemporaryDirectory() as td:
root = Path(td)
source = root / "src.bin"
source.write_bytes(os.urandom(40 * 1024 * 1024 + 12345))
source_sha = hashlib.sha256(source.read_bytes()).hexdigest()
part = root / "recv.qftpart"
part.write_bytes(b"")
part_fp = open(part, "r+b", buffering=0)
part_fp.truncate(source.stat().st_size)
lock = threading.Lock()
received = set()
upload_id = "up_test_01"
total_chunks = (source.stat().st_size + CHUNK - 1) // CHUNK
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_): pass
def _auth(self): return self.headers.get("X-QFT-Token") == TOKEN
def _reply(self, code, body=b"{}"):
self.send_response(code); self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
def do_GET(self):
if not self._auth(): return self._reply(403)
if self.path == "/qft/ping": return self._reply(200, b'{"ok":true,"protocol":2,"parallel":true}')
self._reply(404)
def do_POST(self):
if not self._auth(): return self._reply(403)
if self.path == "/qft/upload/init":
body = json.dumps({"ok":True,"upload_id":upload_id,"chunk_size":CHUNK,"total_chunks":total_chunks}).encode()
return self._reply(200, body)
prefix = f"/qft/upload/chunk/{upload_id}/"
if self.path.startswith(prefix):
idx = int(self.path[len(prefix):]); n = int(self.headers["Content-Length"]); data = self.rfile.read(n)
offset = idx * CHUNK
assert n == min(CHUNK, source.stat().st_size - offset)
with lock:
part_fp.seek(offset); part_fp.write(data); received.add(idx)
return self._reply(200)
if self.path == f"/qft/upload/finish/{upload_id}":
if len(received) != total_chunks: return self._reply(409)
with lock: part_fp.flush(); os.fsync(part_fp.fileno())
return self._reply(200, json.dumps({"ok":True}).encode())
self._reply(404)
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
port = httpd.server_address[1]
threading.Thread(target=httpd.serve_forever, daemon=True).start()
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); udp.bind(("127.0.0.1", 0)); udp_port = udp.getsockname()[1]
stop = threading.Event()
def udp_server():
while not stop.is_set():
udp.settimeout(.2)
try: data, peer = udp.recvfrom(512)
except socket.timeout: continue
except OSError:
if stop.is_set(): break
raise
if data == DISCOVERY_MAGIC: udp.sendto(f"QFTHERE2:{TOKEN}:{port}".encode(), peer)
threading.Thread(target=udp_server, daemon=True).start()
# UDP discovery client.
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); c.settimeout(1); c.sendto(DISCOVERY_MAGIC, ("127.0.0.1", udp_port))
resp, _ = c.recvfrom(512); assert resp == f"QFTHERE2:{TOKEN}:{port}".encode(); c.close()
def request(method, path, body=b"", headers=None):
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
h = {"X-QFT-Token": TOKEN}; h.update(headers or {})
conn.request(method, path, body=body, headers=h); r = conn.getresponse(); payload = r.read(); status = r.status; conn.close(); return status, payload
assert request("GET", "/qft/ping")[0] == 200
status, body = request("POST", "/qft/upload/init", headers={"Content-Length":"0"}); assert status == 200
init = json.loads(body); assert init["chunk_size"] == CHUNK and init["total_chunks"] == total_chunks
indices = list(range(total_chunks)); random.Random(42).shuffle(indices)
def send(idx):
with open(source, "rb") as f:
f.seek(idx * CHUNK); data = f.read(min(CHUNK, source.stat().st_size - idx * CHUNK))
status, _ = request("POST", f"/qft/upload/chunk/{upload_id}/{idx}", data, {"Content-Length":str(len(data))})
assert status == 200
started = time.perf_counter()
with ThreadPoolExecutor(max_workers=8) as ex: list(ex.map(send, indices))
assert request("POST", f"/qft/upload/finish/{upload_id}", headers={"Content-Length":"0"})[0] == 200
elapsed = time.perf_counter() - started
part_fp.close(); recv_sha = hashlib.sha256(part.read_bytes()).hexdigest(); assert recv_sha == source_sha
stop.set(); udp.close(); httpd.shutdown(); httpd.server_close()
print(f"PASS loopback Parallel v2 integration: UDP discovery + HTTP auth + {total_chunks} out-of-order chunks / 8 workers; "
f"{source.stat().st_size} bytes SHA-256 identical in {elapsed:.2f}s")
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
MAX_CACHE_MIB = 768
MAX_PAGES = 192
HARD_MIB = 1100
def calc(side):
bpp = side * side * 4
pages = max(4, min(MAX_PAGES, MAX_CACHE_MIB * 1024 * 1024 // bpp))
managed = pages * bpp / (1024 * 1024)
return pages, managed
p4, m4 = calc(960)
p1, m1 = calc(760)
# Include a conservative 64 MiB transient batch/decoder allowance in this design-level bound.
assert m4 + 64 < HARD_MIB
assert m1 + 64 < HARD_MIB
print(f"PASS memory budget: 4QR cache={p4} pages/{m4:.1f} MiB; 1QR cache={p1} pages/{m1:.1f} MiB; hard design ceiling={HARD_MIB} MiB")
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env python3
"""Synthetic visual-path smoke test for the 4-QR optical page and QFTPAIR2.
Requires: qrcode, numpy, opencv-python, pyzbar/libzbar.
This is intentionally not a substitute for a real display/camera test.
"""
import base64, json, os, time
import cv2
import numpy as np
import qrcode
from pyzbar.pyzbar import decode as zdecode, ZBarSymbol
from qrcode.constants import ERROR_CORRECT_L, ERROR_CORRECT_M
def make_qr(text: str, ec, target: int):
qr = qrcode.QRCode(version=None, error_correction=ec, box_size=1, border=4)
qr.add_data(text); qr.make(fit=True)
mat = np.asarray(qr.get_matrix(), dtype=np.uint8)
scale = max(1, target // mat.shape[0])
return ((1 - np.kron(mat, np.ones((scale, scale), np.uint8))) * 255).astype(np.uint8), qr.version
# Four data QR symbols at the same density used by v0.3 (about 1243 chars/frame).
texts = ["QFT1:" + base64.urlsafe_b64encode(os.urandom(928)).decode().rstrip("=") for _ in range(4)]
canvas = np.full((960, 960), 255, np.uint8)
gutter = 15
cell = (960 - gutter * 3) // 2
for idx, text in enumerate(texts):
img, version = make_qr(text, ERROR_CORRECT_L, cell)
row, col = divmod(idx, 2)
x = gutter + col * (cell + gutter) + (cell - img.shape[1]) // 2
y = gutter + row * (cell + gutter) + (cell - img.shape[0]) // 2
canvas[y:y+img.shape[0], x:x+img.shape[1]] = img
started = time.perf_counter()
found = {r.data.decode() for r in zdecode(canvas, symbols=[ZBarSymbol.QRCODE])}
elapsed = time.perf_counter() - started
assert found == set(texts), (len(found), len(texts))
# Pairing QR: downscale + rotate + slight blur to exercise acquisition margin.
v2 = {
"v":2,"s":"qft_test_session_128bit_XY","n":"DESKTOP-QFT","p":39393,
"e":["http://192.168.137.1:39393"],
"w":["QFT-DESKTOP-abc123","3xamplePassw0rd"],
}
raw = json.dumps(v2, separators=(",", ":"), ensure_ascii=False).encode()
pair_text = "QFTPAIR2:" + base64.urlsafe_b64encode(raw).decode().rstrip("=")
pair, pair_ver = make_qr(pair_text, ERROR_CORRECT_M, 520)
pair = cv2.resize(pair, (260, 260), interpolation=cv2.INTER_NEAREST)
rot = cv2.getRotationMatrix2D((130, 130), 7.0, 1.0)
pair = cv2.warpAffine(pair, rot, (300, 300), borderValue=255)
pair = cv2.GaussianBlur(pair, (3, 3), 0.5)
started2 = time.perf_counter()
pair_found = [r.data.decode() for r in zdecode(pair, symbols=[ZBarSymbol.QRCODE])]
elapsed2 = time.perf_counter() - started2
assert pair_text in pair_found
print(f"PASS synthetic QR decode: 4/4 optical QR v{version} decoded from 960px page in {elapsed*1000:.1f} ms; "
f"QFTPAIR2 QR-M v{pair_ver} decoded after 7deg rotate+blur in {elapsed2*1000:.1f} ms")
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env python3
import base64, json
import qrcode
from qrcode.constants import ERROR_CORRECT_M
session = "qft_test_session_128bit_XY"
ssid = "QFT-DESKTOP-abc123"
password = "3xamplePassw0rd"
v2 = {"v":2,"s":session,"n":"DESKTOP-QFT","p":39393,"e":["http://192.168.137.1:39393"],"w":[ssid,password]}
raw2 = json.dumps(v2, separators=(",", ":"), ensure_ascii=False).encode()
text2 = "QFTPAIR2:" + base64.urlsafe_b64encode(raw2).decode().rstrip("=")
decoded = json.loads(base64.urlsafe_b64decode(text2.split(":",1)[1] + "=" * (-len(text2.split(":",1)[1]) % 4)))
assert decoded == v2
v1 = {
"v":1,"session":session,"pc_name":"DESKTOP-QFT","transport":"http-stream-v1","port":39393,
"endpoints":["http://192.168.137.1:39393","http://192.168.49.1:39393"],
"wifi":{"ssid":ssid,"passphrase":password,"security":"WPA2"},
}
raw1 = json.dumps(v1, separators=(",", ":")).encode()
text1 = "QFTPAIR1:" + base64.urlsafe_b64encode(raw1).decode().rstrip("=")
assert len(text2) < len(text1) * 0.60, (len(text2), len(text1))
qr = qrcode.QRCode(version=None, error_correction=ERROR_CORRECT_M, box_size=1, border=4)
qr.add_data(text2)
qr.make(fit=True)
assert qr.version <= 10, qr.version
print(f"PASS pairing: QFTPAIR2={len(text2)} chars vs v1={len(text1)} chars ({len(text2)/len(text1):.1%}), QR-M version={qr.version}")
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
import hashlib, os, tempfile
from concurrent.futures import ThreadPoolExecutor
SIZE = 64 * 1024 * 1024 + 12345
CHUNK = 8 * 1024 * 1024
WORKERS = 8
IO = 1024 * 1024
def sha(path):
h = hashlib.sha256()
with open(path, "rb", buffering=0) as f:
while True:
b = f.read(4 * 1024 * 1024)
if not b: break
h.update(b)
return h.digest()
def main():
with tempfile.TemporaryDirectory() as d:
src = os.path.join(d, "source.bin")
dst = os.path.join(d, "received.qftpart")
# deterministic 1 MiB pattern, streamed to avoid holding the file in RAM
pattern = bytes((i * 131 + 17) & 0xFF for i in range(IO))
remaining = SIZE
with open(src, "wb", buffering=0) as f:
while remaining:
n = min(remaining, len(pattern))
f.write(pattern[:n]); remaining -= n
with open(dst, "wb") as f: f.truncate(SIZE)
src_fd = os.open(src, os.O_RDONLY)
dst_fd = os.open(dst, os.O_RDWR)
try:
total = (SIZE + CHUNK - 1) // CHUNK
def worker(index):
offset = index * CHUNK
remaining = min(CHUNK, SIZE - offset)
pos = 0
while remaining:
n = min(IO, remaining)
block = os.pread(src_fd, n, offset + pos)
assert len(block) == n
wrote = os.pwrite(dst_fd, block, offset + pos)
assert wrote == n
remaining -= n; pos += n
return index
with ThreadPoolExecutor(max_workers=WORKERS) as pool:
completed = sorted(pool.map(worker, reversed(range(total))))
assert completed == list(range(total))
finally:
os.close(src_fd); os.close(dst_fd)
assert sha(src) == sha(dst)
print(f"PASS parallel upload: {SIZE} bytes, {CHUNK//(1024*1024)} MiB chunks, {WORKERS} workers, 1 MiB worker I/O, SHA-256 identical")
if __name__ == "__main__": main()
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
import base64, binascii, hashlib, math, os, random, struct
import qrcode
from qrcode.constants import ERROR_CORRECT_L
PREFIX = "QFT1:"
CHUNK = 900
LANES = 4
DISPLAY_FPS = 60
def enc(kind, sid, seq, total, payload=b""):
body = b"QFT1" + bytes([1, kind]) + struct.pack(">QIIH", sid, seq, total, len(payload)) + payload
crc = binascii.crc32(body) & 0xFFFFFFFF
return PREFIX + base64.urlsafe_b64encode(body + struct.pack(">I", crc)).decode().rstrip("=")
def dec(text):
assert text.startswith(PREFIX)
b64 = text[len(PREFIX):]
raw = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4))
body, crc_raw = raw[:-4], raw[-4:]
assert (binascii.crc32(body) & 0xFFFFFFFF) == struct.unpack(">I", crc_raw)[0]
assert body[:4] == b"QFT1" and body[4] == 1
kind = body[5]
sid, seq, total, plen = struct.unpack(">QIIH", body[6:24])
payload = body[24:]
assert len(payload) == plen
return kind, sid, seq, total, payload
def test_qr_density(sample):
qr = qrcode.QRCode(version=None, error_correction=ERROR_CORRECT_L, box_size=1, border=4)
qr.add_data(sample)
qr.make(fit=True)
modules_with_quiet = qr.modules_count + 8
canvas = 960
gutter = max(12, min(24, canvas // 64))
cell = (canvas - gutter * 3) // 2
module_px = cell // modules_with_quiet
assert module_px >= 3, (qr.version, qr.modules_count, cell, module_px)
return qr.version, module_px, len(sample)
def main():
random.seed(20260810)
data = os.urandom(2_500_123)
digest = hashlib.sha256(data).digest()
total = math.ceil(len(data) / CHUNK)
sid = 0x1234567890ABCDEF
name = b"sample.bin"
device = b"DESKTOP-QFT"
manifest = (
struct.pack(">QH", len(data), CHUNK)
+ digest
+ struct.pack(">H", len(name)) + name
+ struct.pack(">H", len(device)) + device
)
playlist = [enc(1, sid, 0, total, manifest)]
playlist += [enc(2, sid, i, total, data[i*CHUNK:(i+1)*CHUNK]) for i in range(total)]
playlist += [enc(3, sid, 0, total)]
pages = [playlist[i:i+LANES] for i in range(0, len(playlist), LANES)]
version, module_px, chars = test_qr_density(playlist[min(2, len(playlist)-1)])
got = [None] * total
rounds = 0
manifests = 0
# Model both whole-camera-frame losses and per-lane decode failures.
while any(x is None for x in got):
rounds += 1
for page in pages:
if random.random() < 0.24: # display page/camera frame missed
continue
for text in page:
if random.random() < 0.14: # one quadrant not decoded
continue
kind, rsid, seq, rtotal, payload = dec(text)
assert rsid == sid and rtotal == total
if kind == 1:
manifests += 1
elif kind == 2 and got[seq] is None:
got[seq] = payload
assert rounds < 60
rebuilt = b"".join(got)[:len(data)]
assert rebuilt == data
assert hashlib.sha256(rebuilt).digest() == digest
raw_rate = CHUNK * LANES * DISPLAY_FPS
print(
f"PASS optical: {len(data)} bytes, {total} chunks, {LANES} QR/page @ {DISPLAY_FPS} FPS, "
f"24% page loss + 14% lane loss, recovered in {rounds} rounds; "
f"QR v{version}, {module_px}px/module, frame chars={chars}, theoretical payload={raw_rate/1024:.1f} KiB/s"
)
if __name__ == "__main__":
main()
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
import subprocess, sys
from pathlib import Path
root = Path(__file__).resolve().parent
scripts = [
'protocol_selftest.py',
'pairing_selftest.py',
'parallel_upload_selftest.py',
'udp_discovery_selftest.py',
'local_transfer_integration_selftest.py',
'memory_budget_selftest.py',
'android_compat_selftest.py',
]
for name in scripts:
print(f'== {name} ==', flush=True)
subprocess.run([sys.executable, str(root/name)], check=True)
print('ALL CORE PYTHON SELFTESTS PASSED')
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env python3
import socket, threading, time
TOKEN = "test_session_1234567890AB"
PORT = 39392
TCP = 39393
ready = threading.Event()
def server():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("127.0.0.1", PORT))
s.settimeout(2)
ready.set()
data, peer = s.recvfrom(512)
assert data.decode() == f"QFTDISC2:{TOKEN}"
s.sendto(f"QFTHERE2:{TOKEN}:{TCP}".encode(), peer)
s.close()
def main():
t = threading.Thread(target=server, daemon=True); t.start(); ready.wait(1)
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); c.settimeout(1)
c.sendto(f"QFTDISC2:{TOKEN}".encode(), ("127.0.0.1", PORT))
data, peer = c.recvfrom(512); c.close(); t.join(1)
assert data.decode() == f"QFTHERE2:{TOKEN}:{TCP}"
print(f"PASS UDP discovery: request/response token+port round-trip from {peer[0]}")
if __name__ == "__main__": main()
+34
View File
@@ -0,0 +1,34 @@
# Windows v0.2.0 build / test
```powershell
cd E:\tools\qft_win_android_mvp\windows
cargo check
cargo run --release
```
新增:
- `windows = 0.62.2` / `Devices_WiFiDirect` / `Security_Credentials`
- `serde` / `serde_json`
- `if-addrs`
QFT Direct 真机要求:
- Windows 10/11
- Wi-Fi 已开启
- 适配器/驱动支持 Wi-Fi Direct
- Windows Mobile Hotspot 没有占用 Wi-Fi Direct group-owner 资源
首次使用会在 `%LOCALAPPDATA%\QFT\direct-ap.json` 创建随机 QFT Direct SSID/密码。它用于让 Android 记住同一台电脑的网络身份;每次“启动接收”仍会生成不同的 session token。
如果 QFT Direct 启动失败:
1. 关闭 Windows“移动热点”。
2. 确认 Wi-Fi 开启。
3. 再试一次。
4. 仍失败则在 QFT UI 切到 `当前局域网(备用)`。
如果 Android 已显示连接 QFT Wi-Fi、但无法找到 Windows:
- 允许 qft-windows.exe 通过 Windows Defender Firewall 的**专用网络**。
- Android v0.2.0 会优先探测 QFT Wi-Fi 返回的 gateway,不再依赖固定 Windows IP。
+21
View File
@@ -0,0 +1,21 @@
# Windows build fix v0.1.2
This patch updates the Windows sender for `eframe = 0.35.0` / `egui = 0.35.0`.
Changes:
- `eframe::App::update(ctx, frame)` -> `eframe::App::ui(ui, frame)`
- clone `egui::Context` from `ui.ctx()` for texture/repaint operations
- `egui::TopBottomPanel::top(...)` -> `egui::Panel::top(...)`
- `CentralPanel::show(ctx, ...)` -> `CentralPanel::show(ui, ...)`
- project `rust-version` corrected to `1.95` for egui/eframe 0.35 compatibility
No QFT protocol, QR framing, file chunking, or Android code was changed.
Verify on Windows:
```powershell
cd windows
cargo check
cargo run --release
```
+56
View File
@@ -0,0 +1,56 @@
# Windows UI / device identity update — v0.1.3
## 1. Chinese UI font
The Windows sender no longer relies on egui's default font for Chinese text.
It loads a TrueType font (`.ttf`) at runtime and installs it as the first
Proportional and Monospace font fallback.
Lookup order:
1. `QFT_FONT_PATH`
2. `qft-ui.ttf` next to the executable
3. `assets/qft-ui.ttf` next to the executable
4. `./assets/qft-ui.ttf` from the current working directory
5. common Windows Chinese `.ttf` files
For development, the most deterministic setup is to put your own Chinese-capable
TTF at:
```text
windows/assets/qft-ui.ttf
```
No font file is bundled by this project.
## 2. Device display
The Windows sender now displays:
```text
本机设备:DESKTOP-XXXX
传输设备:DESKTOP-XXXX → Android 光学接收端 · 正在传输
```
The MANIFEST payload now appends:
```text
sender_device_len: u16
sender_device_utf8: bytes
```
The Android app displays both endpoints, for example:
```text
传输设备:DESKTOP-XXXX → Xiaomi 15
```
The field is appended to the end of the old MANIFEST payload, so the new Android
parser remains compatible with v0.1/v0.1.2 manifests.
## Important limitation
Windows -> Android is intentionally a one-way optical channel. The Android phone
does not send any ACK or identity back to Windows, so the Windows sender cannot
automatically know the exact receiving phone model. The Android side can show
both the sender PC name and its own local device model.
+20
View File
@@ -0,0 +1,20 @@
# QFT Windows v0.2.2 build fix
This patch fixes the five `cargo check` errors reported against eframe/egui 0.35.0.
## Fixed
1. Added semicolons after `ui.small(...)` calls that were used as the final expression of `if/else` blocks. `ui.small()` returns `egui::Response`, while those blocks must evaluate to `()`.
2. Removed the obsolete `Context::style()` and `Context::set_style()` calls. Those APIs are not available in egui 0.35.
3. Preserved the intended spacing by applying it through `Ui::spacing_mut()` inside `eframe::App::ui`.
4. Bumped Windows application/package version to 0.2.2.
## Verify on Windows
```powershell
cd E:\tools\qft_win_android_mvp\windows
cargo check
cargo run --release
```
The Android/Windows transfer protocol, Wi-Fi Direct pairing flow, receiver service and optical transport are unchanged by this patch.
+4567
View File
File diff suppressed because it is too large Load Diff
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "qft-windows"
version = "0.3.0"
edition = "2024"
rust-version = "1.95"
[dependencies]
eframe = "0.35.0"
rfd = "0.17.2"
qrcode = { version = "0.14.1", default-features = false }
base64 = "0.22.1"
crc32fast = "1.5.0"
sha2 = "0.10.9"
rand = "0.9.2"
anyhow = "1.0.99"
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.143"
if-addrs = "0.13.4"
rayon = "1.11.0"
[target.'cfg(windows)'.dependencies]
windows = { version = "0.62.2", features = [
"Devices_WiFiDirect",
"Security_Credentials",
] }
+17
View File
@@ -0,0 +1,17 @@
QFT Windows UI font
Place a Chinese-capable TrueType font here and name it:
qft-ui.ttf
The application loads TTF at runtime. It does not embed/distribute font files.
Lookup order:
1. QFT_FONT_PATH environment variable
2. qft-ui.ttf beside the executable
3. assets/qft-ui.ttf beside the executable
4. ./assets/qft-ui.ttf from the current working directory
5. common Windows CJK .ttf files (for example C:\Windows\Fonts\simhei.ttf)
Example PowerShell:
$env:QFT_FONT_PATH = 'D:\fonts\my-cjk-font.ttf'
cargo run --release
+79
View File
@@ -0,0 +1,79 @@
use anyhow::{bail, Context, Result};
#[cfg(windows)]
use windows::{
core::HSTRING,
Devices::WiFiDirect::{
WiFiDirectAdvertisementPublisher, WiFiDirectAdvertisementPublisherStatus,
},
Security::Credentials::PasswordCredential,
};
pub struct DirectAp {
pub ssid: String,
#[cfg(windows)]
publisher: WiFiDirectAdvertisementPublisher,
}
impl DirectAp {
pub fn start(ssid: String, passphrase: String) -> Result<Self> {
#[cfg(not(windows))]
{
let _ = (ssid, passphrase);
bail!("QFT Direct AP 仅支持 Windows")
}
#[cfg(windows)]
{
let publisher = WiFiDirectAdvertisementPublisher::new()
.context("创建 Wi-Fi Direct publisher 失败")?;
let ad = publisher.Advertisement()
.context("读取 Wi-Fi Direct advertisement 失败")?;
ad.SetIsAutonomousGroupOwnerEnabled(true)
.context("启用 Autonomous Group Owner 失败")?;
let legacy = ad.LegacySettings()
.context("读取 LegacySettings 失败")?;
legacy.SetIsEnabled(true)
.context("启用 Wi-Fi Direct Legacy AP 失败")?;
legacy.SetSsid(&HSTRING::from(&ssid))
.context("设置 QFT SSID 失败")?;
let credential = PasswordCredential::new()
.context("创建 Wi-Fi Direct 密码对象失败")?;
credential.SetPassword(&HSTRING::from(&passphrase))
.context("设置 QFT 热点密码失败")?;
legacy.SetPassphrase(&credential)
.context("应用 QFT 热点密码失败")?;
publisher.Start().context("启动 QFT Wi-Fi Direct AP 失败")?;
// Publisher startup is asynchronous. Do not expose the pairing QR until
// Windows reports Started; otherwise Android can scan a network that is
// not yet discoverable.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
let status = publisher.Status().context("读取 AP 状态失败")?;
if status == WiFiDirectAdvertisementPublisherStatus::Started {
break;
}
if status == WiFiDirectAdvertisementPublisherStatus::Aborted {
bail!("Wi-Fi Direct AP 启动被系统中止。请确认 Windows Wi-Fi 已开启,且系统移动热点未占用 Wi-Fi Direct。")
}
if std::time::Instant::now() >= deadline {
bail!("Wi-Fi Direct AP 启动超时。请确认无线网卡支持 Wi-Fi Direct,并关闭 Windows 移动热点后重试。")
}
std::thread::sleep(std::time::Duration::from_millis(80));
}
Ok(Self { ssid, publisher })
}
}
}
impl Drop for DirectAp {
fn drop(&mut self) {
#[cfg(windows)]
{
let _ = self.publisher.Stop();
}
}
}
+736
View File
@@ -0,0 +1,736 @@
mod direct_ap;
mod optical_cache;
mod pairing;
mod protocol;
mod qr;
mod receiver;
use eframe::egui::{self, FontData, FontDefinitions, FontFamily, TextureHandle, TextureOptions};
use optical_cache::OpticalPrefetcher;
use pairing::{PairingPayload, WifiCredentials};
use protocol::{hex_sha256, TransferSource};
use receiver::{ReceiverEvent, ReceiverServer};
use std::{
path::{Path, PathBuf},
sync::{mpsc, Arc},
time::{Duration, Instant},
};
const DEFAULT_CHUNK_SIZE: u16 = 900;
const UI_FONT_NAME: &str = "qft-ui";
const APP_VERSION: &str = "0.3.0-rc3";
fn main() -> eframe::Result {
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("QFT · 超速二维码文件传输")
.with_inner_size([1040.0, 800.0])
.with_min_inner_size([800.0, 640.0]),
..Default::default()
};
eframe::run_native(
"QFT",
options,
Box::new(|cc| Ok(Box::new(QftApp::new(cc)))),
)
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Screen {
Home,
OpticalSend,
PhoneToPc,
}
struct OpticalState {
source: Option<Arc<TransferSource>>,
prefetch: Option<OpticalPrefetcher>,
texture: Option<TextureHandle>,
page_index: u32,
round: u64,
playing: bool,
fps: f32,
lanes: usize,
cache_mib: usize,
last_advance: Instant,
fps_window_started: Instant,
displayed_in_window: u32,
actual_page_fps: f64,
status: String,
}
struct ReceiveState {
save_dir: Option<PathBuf>,
use_direct_ap: bool,
server: Option<ReceiverServer>,
direct_ap: Option<direct_ap::DirectAp>,
events: Option<mpsc::Receiver<ReceiverEvent>>,
pair_texture: Option<TextureHandle>,
session_token: String,
status: String,
connected_device: String,
current_file: String,
received: u64,
total: u64,
last_saved: String,
last_sha256: String,
transfer_started: Option<Instant>,
rate_bps: f64,
}
struct QftApp {
screen: Screen,
font_status: String,
local_device: String,
optical: OpticalState,
receive: ReceiveState,
}
impl QftApp {
fn new(cc: &eframe::CreationContext<'_>) -> Self {
cc.egui_ctx.set_pixels_per_point(1.0);
install_visuals(&cc.egui_ctx);
let font_status = match install_ttf_font(&cc.egui_ctx) {
Ok(path) => format!("字体:{}", path.display()),
Err(message) => format!("字体加载失败:{message}"),
};
Self {
screen: Screen::Home,
font_status,
local_device: protocol::local_device_name(),
optical: OpticalState {
source: None,
prefetch: None,
texture: None,
page_index: 0,
round: 0,
playing: false,
fps: 60.0,
lanes: 4,
cache_mib: 384,
last_advance: Instant::now(),
fps_window_started: Instant::now(),
displayed_in_window: 0,
actual_page_fps: 0.0,
status: "选择文件后开始光学发送。默认 4 码/页 · 60 FPS,缓存不足时会自动停在当前页等待。".into(),
},
receive: ReceiveState {
save_dir: None,
use_direct_ap: true,
server: None,
direct_ap: None,
events: None,
pair_texture: None,
session_token: String::new(),
status: "先选择接收文件夹,然后启动接收。".into(),
connected_device: "等待 Android 扫码".into(),
current_file: "—".into(),
received: 0,
total: 0,
last_saved: "—".into(),
last_sha256: String::new(),
transfer_started: None,
rate_bps: 0.0,
},
}
}
fn header(&mut self, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
ui.heading("QFT");
ui.label(format!("v{APP_VERSION}"));
ui.separator();
ui.label("扫码配对 · 本地直传 · 光学零网络");
let space = (ui.available_width() - 150.0).max(0.0);
ui.add_space(space);
if self.screen != Screen::Home && ui.button("← 返回首页").clicked() {
match self.screen {
Screen::PhoneToPc => self.stop_receiver(),
Screen::OpticalSend => { self.optical.playing = false; self.optical.prefetch = None; },
Screen::Home => {}
}
self.screen = Screen::Home;
}
});
ui.separator();
}
fn home_ui(&mut self, ui: &mut egui::Ui) {
ui.add_space(22.0);
ui.vertical_centered(|ui| {
ui.heading("选择传输方向");
ui.label("两个方向采用不同链路,让速度、兼容性和“无需外网”同时成立。")
});
ui.add_space(24.0);
ui.columns(2, |cols| {
cols[0].group(|ui| {
ui.set_min_height(300.0);
ui.vertical_centered(|ui| {
ui.add_space(22.0);
ui.heading("电脑 → Android");
ui.label("光学传输");
ui.add_space(12.0);
ui.label("文件只经过:电脑屏幕 → 手机摄像头");
ui.label("不使用 Wi-Fi / 蓝牙 / 局域网 / 外网");
ui.add_space(24.0);
if ui.add_sized([220.0, 46.0], egui::Button::new("选择文件并开始光传")).clicked() {
self.screen = Screen::OpticalSend;
}
});
});
cols[1].group(|ui| {
ui.set_min_height(300.0);
ui.vertical_centered(|ui| {
ui.add_space(22.0);
ui.heading("Android → 电脑");
ui.label("扫码直连");
ui.add_space(12.0);
ui.label("电脑创建临时 QFT Wi-Fi Direct AP");
ui.label("Android 扫码配网后高速上传到指定文件夹");
ui.add_space(24.0);
if ui.add_sized([220.0, 46.0], egui::Button::new("电脑接收手机文件")).clicked() {
self.screen = Screen::PhoneToPc;
}
});
});
});
ui.add_space(18.0);
ui.group(|ui| {
ui.label(format!("本机设备:{}", self.local_device));
ui.small(&self.font_status);
});
}
fn optical_ui(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
if self.optical.playing && self.optical.source.is_some() {
let interval = Duration::from_secs_f32(1.0 / self.optical.fps.max(1.0));
if self.optical.last_advance.elapsed() >= interval {
self.optical.last_advance = Instant::now();
self.optical_advance(ctx);
}
// Keep the UI scheduler hot enough for a 60 Hz display without busy-spinning.
ctx.request_repaint_after((interval / 3).max(Duration::from_millis(1)));
}
ui.horizontal_wrapped(|ui| {
ui.heading("电脑 → Android · 光学极速模式");
ui.separator();
ui.label("屏幕 → 摄像头 · 0 网络");
});
ui.add_space(8.0);
ui.group(|ui| {
ui.horizontal_wrapped(|ui| {
if ui.button("选择文件").clicked() { self.optical_pick_file(ctx); }
ui.label("刷新率");
ui.add(egui::Slider::new(&mut self.optical.fps, 1.0..=60.0).suffix(" FPS").step_by(1.0));
if ui.small_button("15").clicked() { self.optical.fps = 15.0; }
if ui.small_button("30").clicked() { self.optical.fps = 30.0; }
if ui.small_button("60").clicked() { self.optical.fps = 60.0; }
if ui.small_button("极速预设").clicked() {
self.optical.fps = 60.0;
self.optical.lanes = 4;
self.optical.cache_mib = 384;
self.optical.playing = false;
self.restart_optical_pipeline();
let _ = self.optical_render_first(ctx);
}
});
let old_lanes = self.optical.lanes;
let old_cache = self.optical.cache_mib;
ui.horizontal_wrapped(|ui| {
ui.label("视觉并行");
ui.radio_value(&mut self.optical.lanes, 1, "1 码/页 · 兼容");
ui.radio_value(&mut self.optical.lanes, 4, "4 码/页 · 极速");
ui.separator();
ui.label("预编码缓存");
ui.add(egui::Slider::new(&mut self.optical.cache_mib, 64..=optical_cache::MAX_MANAGED_CACHE_MIB)
.suffix(" MiB").step_by(64.0));
});
ui.small(format!(
"QFT 只允许预编码缓存使用最多 {} MiB,为进程/GPU/系统缓冲预留空间,目标整进程不超过约 {} MiB。",
optical_cache::MAX_MANAGED_CACHE_MIB, optical_cache::HARD_PROCESS_BUDGET_MIB
));
if old_lanes != self.optical.lanes || old_cache != self.optical.cache_mib {
self.optical.playing = false;
self.restart_optical_pipeline();
let _ = self.optical_render_first(ctx);
}
let enabled = self.optical.source.is_some();
ui.horizontal_wrapped(|ui| {
if ui.add_enabled(enabled, egui::Button::new(if self.optical.playing { "暂停" } else { "开始播放" })).clicked() {
if !self.optical.playing && self.optical.prefetch.is_none() {
self.restart_optical_pipeline();
}
self.optical.playing = !self.optical.playing;
self.optical.last_advance = Instant::now();
self.optical.fps_window_started = Instant::now();
self.optical.displayed_in_window = 0;
}
if ui.add_enabled(enabled, egui::Button::new("回到第 1 页")).clicked() {
self.optical.playing = false;
self.restart_optical_pipeline();
let _ = self.optical_render_first(ctx);
}
});
});
ui.add_space(8.0);
if let Some(source) = self.optical.source.as_ref() {
let m = &source.manifest;
let pages = source.total_pages(self.optical.lanes);
let logical_fps = self.optical.fps as f64 * self.optical.lanes as f64;
let payload_rate = logical_fps * m.chunk_size as f64;
ui.columns(3, |cols| {
cols[0].group(|ui| {
ui.small("传输");
ui.heading(format!("{:.0} FPS", self.optical.fps));
ui.label(format!("{} 码/页 · {:.0} 逻辑帧/s", self.optical.lanes, logical_fps));
});
cols[1].group(|ui| {
ui.small("实测显示");
ui.heading(format!("{:.1} 页/s", self.optical.actual_page_fps));
ui.label(format!("理论载荷 ≈ {}/s", human_bytes(payload_rate as u64)));
});
cols[2].group(|ui| {
ui.small("内存策略");
ui.heading(format!("{} MiB", self.optical.cache_mib));
let cap = self.optical.prefetch.as_ref().map(|p| p.capacity_pages).unwrap_or(0);
let page_mib = self.optical.prefetch.as_ref().map(|p| p.estimated_page_mib).unwrap_or(0.0);
ui.label(format!("预编码最多 {cap} 页 · {page_mib:.1} MiB/页 · 定位读取"));
});
});
ui.add_space(6.0);
ui.label(format!("传输设备:{} → Android 光学接收端", m.sender_device));
ui.label(format!("文件:{} · {}", m.file_name, human_bytes(m.file_size)));
ui.small(format!("源路径:{}", source.path().display()));
ui.label(format!("数据块:{} · 当前页:{}/{} · 完整轮次:{}", m.total_chunks, self.optical.page_index + 1, pages, self.optical.round));
ui.small(format!("SHA-256:{}", hex_sha256(&m.sha256)));
}
ui.label(&self.optical.status);
ui.separator();
if let Some(texture) = &self.optical.texture {
let avail = ui.available_size();
let side = avail.x.min(avail.y).min(680.0).max(320.0);
ui.vertical_centered(|ui| { ui.image((texture.id(), egui::vec2(side, side))); });
} else {
ui.vertical_centered(|ui| {
ui.add_space(100.0);
ui.heading("请选择一个文件");
ui.label("极速模式会在后台并行预编码二维码;手机仍可处于飞行模式。")
});
}
}
fn receive_ui(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
self.poll_receiver_events();
ctx.request_repaint_after(Duration::from_millis(100));
ui.horizontal_wrapped(|ui| {
ui.heading("Android → 电脑 · 扫码直连");
ui.separator();
ui.label("UDP 快速发现 · 4/8/16 MiB 自适应分块 · 最高 8 路并行 · 不经过外网");
});
ui.add_space(10.0);
let running = self.receive.server.is_some();
ui.group(|ui| {
ui.heading("1 · 保存位置");
ui.horizontal_wrapped(|ui| {
if ui.add_enabled(!running, egui::Button::new("选择接收文件夹")).clicked() {
if let Some(dir) = rfd::FileDialog::new().pick_folder() {
self.receive.save_dir = Some(dir);
self.receive.status = "保存位置已选择,可以启动接收。".into();
}
}
ui.label(self.receive.save_dir.as_ref().map(|p| p.display().to_string()).unwrap_or_else(|| "尚未选择".into()));
});
});
ui.add_space(8.0);
ui.group(|ui| {
ui.heading("2 · 连接方式");
ui.add_enabled_ui(!running, |ui| {
ui.radio_value(&mut self.receive.use_direct_ap, true, "QFT Direct(推荐)· Windows 自动创建临时 Wi-Fi Direct AP");
ui.radio_value(&mut self.receive.use_direct_ap, false, "当前局域网(备用)· 手机和电脑已经在同一 Wi-Fi/LAN");
});
if self.receive.use_direct_ap {
ui.small("Android 10+ 使用 WifiNetworkSpecifier;Android 7~9 使用兼容配网。连接后先 UDP 广播发现,再并行探测网关/IP,避免“已连 Wi-Fi 找不到电脑”。");
if !running && ui.small_button("重置 QFT Direct 网络身份").clicked() {
match pairing::reset_direct_ap_credentials() {
Ok(()) => self.receive.status = "QFT Direct 网络身份已重置;下次启动接收会生成新的 SSID/密码,Android 需要重新批准一次。".into(),
Err(e) => self.receive.status = format!("重置 QFT Direct 网络身份失败:{e:#}"),
}
}
} else {
ui.small("二维码不携带 Wi-Fi 密码;Android 会先 UDP 快速发现电脑,再并行探测二维码内的本地 IP。");
}
if running { ui.small("接收运行中,停止接收后才能修改保存目录或连接方式。"); }
});
ui.add_space(8.0);
ui.group(|ui| {
ui.heading("3 · 启动并扫码");
ui.horizontal(|ui| {
if ui.add_enabled(!running && self.receive.save_dir.is_some(), egui::Button::new("启动接收并生成二维码")).clicked() {
self.start_receiver(ctx);
}
if ui.add_enabled(running, egui::Button::new("停止接收")).clicked() {
self.stop_receiver();
}
});
ui.label(&self.receive.status);
});
if self.receive.server.is_some() {
ui.add_space(10.0);
ui.columns(2, |cols| {
cols[0].group(|ui| {
ui.heading("手机扫码 · QFTPAIR2");
if let Some(texture) = &self.receive.pair_texture {
let side = ui.available_width().min(420.0).max(260.0);
ui.vertical_centered(|ui| { ui.image((texture.id(), egui::vec2(side, side))); });
}
if let Some(ap) = &self.receive.direct_ap {
ui.label(format!("临时网络:{}", ap.ssid));
ui.small("网络身份会在这台电脑上复用以减少重复确认;每次接收仍会生成新的会话 Token。");
}
if !self.receive.session_token.is_empty() {
let short = &self.receive.session_token[..10.min(self.receive.session_token.len())];
ui.small(format!("临时会话:{short}… · 停止接收后立即失效"));
}
});
cols[1].group(|ui| {
ui.heading("接收状态 · Parallel v2");
ui.label(format!("电脑:{}", self.local_device));
ui.label(format!("手机:{}", self.receive.connected_device));
ui.separator();
ui.label(format!("当前文件:{}", self.receive.current_file));
let fraction = if self.receive.total == 0 { 0.0 } else { self.receive.received as f32 / self.receive.total as f32 };
ui.add(egui::ProgressBar::new(fraction.clamp(0.0, 1.0)).show_percentage());
ui.label(format!("已接收:{} / {}", human_bytes(self.receive.received), human_bytes(self.receive.total)));
if self.receive.rate_bps > 1.0 {
let eta = if self.receive.total > self.receive.received {
(self.receive.total - self.receive.received) as f64 / self.receive.rate_bps
} else { 0.0 };
ui.label(format!("速度:{}/s · 预计剩余:{}", human_bytes(self.receive.rate_bps as u64), human_duration(eta)));
}
ui.separator();
ui.label(format!("最近保存:{}", self.receive.last_saved));
if !self.receive.last_sha256.is_empty() { ui.small(format!("SHA-256:{}", self.receive.last_sha256)); }
});
});
}
}
fn optical_pick_file(&mut self, ctx: &egui::Context) {
let Some(path) = rfd::FileDialog::new().pick_file() else { return };
match TransferSource::open(&path, DEFAULT_CHUNK_SIZE) {
Ok(source) => {
self.optical.source = Some(Arc::new(source));
self.optical.playing = false;
self.optical.actual_page_fps = 0.0;
self.restart_optical_pipeline();
if let Err(e) = self.optical_render_first(ctx) {
self.optical.status = format!("生成二维码失败:{e:#}");
} else {
self.optical.status = "文件已载入。默认 4 码/页 · 60 FPS;低端手机若有效 QR/s 明显偏低,可降到 30 FPS。".into();
}
}
Err(e) => self.optical.status = format!("读取文件失败:{e:#}"),
}
}
fn optical_canvas_side(&self) -> usize {
if self.optical.lanes == 4 { 960 } else { 760 }
}
fn restart_optical_pipeline(&mut self) {
self.optical.prefetch = None;
self.optical.page_index = 0;
self.optical.round = 0;
let Some(source) = self.optical.source.clone() else { return };
self.optical.prefetch = Some(OpticalPrefetcher::start(
source,
self.optical.lanes,
self.optical_canvas_side(),
self.optical.cache_mib,
));
}
fn optical_render_first(&mut self, ctx: &egui::Context) -> anyhow::Result<()> {
let Some(source) = self.optical.source.as_ref() else { return Ok(()) };
let texts = source.text_page(0, self.optical.lanes)?;
let image = qr::render_qr_grid(&texts, self.optical_canvas_side())?;
self.set_optical_texture(ctx, image);
self.optical.page_index = 0;
self.optical.round = 0;
Ok(())
}
fn set_optical_texture(&mut self, ctx: &egui::Context, image: egui::ColorImage) {
if let Some(texture) = self.optical.texture.as_mut() {
// Reuse one GPU texture instead of allocating/freeing a texture ID
// for every 60 Hz optical page. This materially reduces GPU/driver
// churn and keeps the presentation path deterministic.
texture.set(image, TextureOptions::NEAREST);
} else {
self.optical.texture = Some(ctx.load_texture(
"qft-optical-frame", image, TextureOptions::NEAREST,
));
}
}
fn optical_advance(&mut self, ctx: &egui::Context) {
let next = match self.optical.prefetch.as_ref() {
Some(prefetch) => prefetch.try_next(),
None => {
self.restart_optical_pipeline();
return;
}
};
match next {
Ok(page) => {
self.set_optical_texture(ctx, page.image);
self.optical.page_index = page.page_index;
self.optical.round = page.round;
self.optical.displayed_in_window = self.optical.displayed_in_window.saturating_add(1);
let elapsed = self.optical.fps_window_started.elapsed();
if elapsed >= Duration::from_secs(1) {
self.optical.actual_page_fps = self.optical.displayed_in_window as f64 / elapsed.as_secs_f64().max(0.001);
self.optical.displayed_in_window = 0;
self.optical.fps_window_started = Instant::now();
}
self.optical.status = if self.optical.actual_page_fps + 3.0 < self.optical.fps as f64 && self.optical.actual_page_fps > 1.0 {
"实际页面速率低于目标:可降低 FPS 或把缓存调高;文件数据仍会循环补帧。".into()
} else {
"正在光学发送 · 4 码模式会把一页拆成四个独立 QR 并行解码。".into()
};
}
Err(std::sync::mpsc::TryRecvError::Empty) => {
self.optical.status = "预编码缓存正在补充,暂缓换页以避免显示空帧。".into();
}
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
self.optical.playing = false;
self.optical.status = "光学预编码线程已停止,请重新选择文件。".into();
}
}
}
fn start_receiver(&mut self, ctx: &egui::Context) {
let Some(save_dir) = self.receive.save_dir.clone() else { return };
self.stop_receiver();
self.receive.status = "正在初始化接收服务…".into();
let token = pairing::new_session_token();
let (tx, rx) = mpsc::channel();
let server = match ReceiverServer::start(save_dir, token.clone(), tx) {
Ok(v) => v,
Err(e) => { self.receive.status = format!("接收服务启动失败:{e:#}"); return; }
};
let mut direct_ap = None;
let wifi = if self.receive.use_direct_ap {
let (ssid, passphrase) = match pairing::load_or_create_direct_ap_credentials(&self.local_device) {
Ok(v) => v,
Err(e) => {
drop(server);
self.receive.status = format!("读取 QFT Direct 配网身份失败:{e:#}");
return;
}
};
match direct_ap::DirectAp::start(ssid.clone(), passphrase.clone()) {
Ok(ap) => {
direct_ap = Some(ap);
Some(WifiCredentials { ssid, passphrase, security: "WPA2".into() })
}
Err(e) => {
drop(server);
self.receive.status = format!("QFT Direct 启动失败:{e:#}\n可切换到“当前局域网”备用模式。 ");
return;
}
}
} else { None };
// Give the virtual adapter a moment to appear before enumerating addresses.
if direct_ap.is_some() { std::thread::sleep(Duration::from_millis(250)); }
let payload = PairingPayload {
v: 2,
session: token.clone(),
pc_name: self.local_device.clone(),
transport: "http-parallel-v2".into(),
port: server.port,
endpoints: pairing::local_ipv4_endpoints(server.port),
wifi,
};
let pair_text = match payload.encode_text() {
Ok(v) => v,
Err(e) => { self.receive.status = format!("配对信息生成失败:{e:#}"); return; }
};
let image = match qr::render_pair_qr(&pair_text, 520) {
Ok(v) => v,
Err(e) => { self.receive.status = format!("配对二维码生成失败:{e:#}"); return; }
};
let receiver_port = server.port;
self.receive.server = Some(server);
self.receive.direct_ap = direct_ap;
self.receive.events = Some(rx);
self.receive.pair_texture = Some(ctx.load_texture("qft-pair-code", image, TextureOptions::NEAREST));
self.receive.session_token = token;
self.receive.connected_device = "等待 Android 扫码".into();
self.receive.current_file = "—".into();
self.receive.received = 0;
self.receive.total = 0;
self.receive.last_saved = "—".into();
self.receive.last_sha256.clear();
self.receive.transfer_started = None;
self.receive.rate_bps = 0.0;
self.receive.status = if self.receive.use_direct_ap {
format!("接收已就绪 · TCP {} · UDP 发现 {}。Android 扫码后会自动配网并快速发现电脑。", receiver_port, receiver::DISCOVERY_PORT)
} else {
format!("接收已就绪 · TCP {} · UDP 发现 {}。Android 扫码后会自动发现同一局域网电脑。", receiver_port, receiver::DISCOVERY_PORT)
};
}
fn stop_receiver(&mut self) {
self.receive.events = None;
self.receive.server = None;
self.receive.direct_ap = None;
self.receive.pair_texture = None;
self.receive.session_token.clear();
self.receive.connected_device = "等待 Android 扫码".into();
self.receive.current_file = "—".into();
self.receive.received = 0;
self.receive.total = 0;
self.receive.transfer_started = None;
self.receive.rate_bps = 0.0;
self.receive.status = "接收已停止。".into();
}
fn poll_receiver_events(&mut self) {
let mut pending = Vec::new();
if let Some(rx) = &self.receive.events {
while let Ok(event) = rx.try_recv() { pending.push(event); }
}
for event in pending {
match event {
ReceiverEvent::ClientConnected { device } => {
self.receive.connected_device = device;
self.receive.status = "Android 已连接到电脑。可以开始发送文件。".into();
}
ReceiverEvent::UploadStarted { device, file_name, size } => {
self.receive.connected_device = device;
self.receive.current_file = file_name;
self.receive.received = 0;
self.receive.total = size;
self.receive.transfer_started = Some(Instant::now());
self.receive.rate_bps = 0.0;
self.receive.status = "正在接收文件…".into();
}
ReceiverEvent::UploadProgress { device, file_name, received, size } => {
self.receive.connected_device = device;
self.receive.current_file = file_name;
self.receive.received = received;
self.receive.total = size;
if let Some(started) = self.receive.transfer_started {
let secs = started.elapsed().as_secs_f64().max(0.001);
self.receive.rate_bps = received as f64 / secs;
}
}
ReceiverEvent::UploadCompleted { device, file_name, saved_path, sha256 } => {
self.receive.connected_device = device;
self.receive.current_file = file_name;
self.receive.received = self.receive.total;
self.receive.last_saved = saved_path.display().to_string();
self.receive.last_sha256 = sha256;
if let Some(started) = self.receive.transfer_started {
let secs = started.elapsed().as_secs_f64().max(0.001);
self.receive.rate_bps = self.receive.total as f64 / secs;
}
self.receive.status = "文件接收完成。二维码会继续保持有效,可继续发送其他文件。".into();
}
ReceiverEvent::Error(message) => self.receive.status = message,
}
}
}
}
impl eframe::App for QftApp {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
let ctx = ui.ctx().clone();
ui.spacing_mut().item_spacing = egui::vec2(10.0, 10.0);
ui.spacing_mut().button_padding = egui::vec2(14.0, 8.0);
egui::CentralPanel::default().show(ui, |ui| {
self.header(ui);
match self.screen {
Screen::Home => self.home_ui(ui),
Screen::OpticalSend => self.optical_ui(ui, &ctx),
Screen::PhoneToPc => self.receive_ui(ui, &ctx),
}
});
}
}
fn install_visuals(ctx: &egui::Context) {
// eframe/egui 0.35 no longer exposes Context::style()/set_style().
// Keep theme initialization here; per-UI spacing is applied in App::ui.
ctx.set_visuals(egui::Visuals::dark());
}
fn install_ttf_font(ctx: &egui::Context) -> Result<PathBuf, String> {
let font_path = find_ttf_font().ok_or_else(|| {
"未找到可用 TTF。请把支持中文的字体复制到 windows/assets/qft-ui.ttf,或设置 QFT_FONT_PATH。".to_owned()
})?;
let bytes = std::fs::read(&font_path).map_err(|e| format!("读取 {} 失败:{e}", font_path.display()))?;
let mut fonts = FontDefinitions::default();
fonts.font_data.insert(UI_FONT_NAME.to_owned(), Arc::new(FontData::from_owned(bytes)));
fonts.families.entry(FontFamily::Proportional).or_default().insert(0, UI_FONT_NAME.to_owned());
fonts.families.entry(FontFamily::Monospace).or_default().insert(0, UI_FONT_NAME.to_owned());
ctx.set_fonts(fonts);
Ok(font_path)
}
fn find_ttf_font() -> Option<PathBuf> {
let mut candidates = Vec::<PathBuf>::new();
if let Ok(explicit) = std::env::var("QFT_FONT_PATH") {
if !explicit.trim().is_empty() { candidates.push(PathBuf::from(explicit)); }
}
if let Ok(exe) = std::env::current_exe() {
if let Some(dir) = exe.parent() {
candidates.push(dir.join("qft-ui.ttf"));
candidates.push(dir.join("assets").join("qft-ui.ttf"));
}
}
candidates.push(PathBuf::from("assets").join("qft-ui.ttf"));
if cfg!(target_os = "windows") {
candidates.extend([
PathBuf::from(r"C:\Windows\Fonts\simhei.ttf"),
PathBuf::from(r"C:\Windows\Fonts\Deng.ttf"),
PathBuf::from(r"C:\Windows\Fonts\msyh.ttf"),
]);
}
candidates.into_iter().find(|path| is_ttf_file(path.as_path()))
}
fn is_ttf_file(path: &Path) -> bool {
path.is_file() && path.extension().and_then(|ext| ext.to_str()).is_some_and(|ext| ext.eq_ignore_ascii_case("ttf"))
}
fn human_duration(seconds: f64) -> String {
if !seconds.is_finite() || seconds <= 0.5 { return "<1 秒".into(); }
let total = seconds.ceil() as u64;
let minutes = total / 60;
let secs = total % 60;
if minutes > 0 { format!("{minutes} 分 {secs} 秒") } else { format!("{secs} 秒") }
}
fn human_bytes(v: u64) -> String {
const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
let mut n = v as f64;
let mut i = 0usize;
while n >= 1024.0 && i < UNITS.len() - 1 { n /= 1024.0; i += 1; }
if i == 0 { format!("{} {}", v, UNITS[i]) } else { format!("{n:.2} {}", UNITS[i]) }
}
+128
View File
@@ -0,0 +1,128 @@
use crate::{protocol::TransferSource, qr};
use eframe::egui::ColorImage;
use rayon::prelude::*;
use std::{
sync::{
atomic::{AtomicBool, Ordering},
mpsc::{self, Receiver, TryRecvError, TrySendError},
Arc,
},
thread::{self, JoinHandle},
time::Duration,
};
/// Keep the managed pre-render cache comfortably below the user's 1.1 GiB
/// whole-process ceiling. egui, GPU staging, Rust stacks and OS buffers still
/// need headroom, so QFT never intentionally reserves the entire 1.1 GiB.
pub const HARD_PROCESS_BUDGET_MIB: usize = 1100;
pub const MAX_MANAGED_CACHE_MIB: usize = 768;
const MIN_CACHE_MIB: usize = 64;
const MAX_CACHE_PAGES: usize = 192;
const PREENCODE_BATCH: usize = 8;
pub struct EncodedPage {
pub page_index: u32,
pub round: u64,
pub image: ColorImage,
}
pub struct OpticalPrefetcher {
rx: Receiver<EncodedPage>,
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
pub capacity_pages: usize,
pub cache_mib: usize,
pub estimated_page_mib: f64,
}
impl OpticalPrefetcher {
pub fn start(
source: Arc<TransferSource>,
lanes: usize,
canvas_side: usize,
requested_cache_mib: usize,
) -> Self {
let cache_mib = requested_cache_mib.clamp(MIN_CACHE_MIB, MAX_MANAGED_CACHE_MIB);
// ColorImage uses Color32 pixels: approximately four bytes per pixel.
let bytes_per_page = canvas_side.saturating_mul(canvas_side).saturating_mul(4).max(1);
let budget_bytes = cache_mib.saturating_mul(1024 * 1024);
let capacity_pages = (budget_bytes / bytes_per_page).clamp(4, MAX_CACHE_PAGES);
let estimated_page_mib = bytes_per_page as f64 / (1024.0 * 1024.0);
let (tx, rx) = mpsc::sync_channel::<EncodedPage>(capacity_pages);
let stop = Arc::new(AtomicBool::new(false));
let stop_worker = stop.clone();
// Render several consecutive pages in one Rayon batch. At 4 QR/page this
// lets all CPU cores work across both pages and QR lanes and is much more
// likely to keep a 60 Hz presentation queue full than a single-page loop.
let thread = thread::spawn(move || {
let total_pages = source.total_pages(lanes).max(1);
let mut next_page = 0u32;
let mut next_round = 0u64;
while !stop_worker.load(Ordering::Relaxed) {
let mut plan = Vec::with_capacity(PREENCODE_BATCH);
for order in 0..PREENCODE_BATCH {
plan.push((order, next_page, next_round));
next_page += 1;
if next_page >= total_pages {
next_page = 0;
next_round = next_round.saturating_add(1);
}
}
let mut rendered: Vec<(usize, EncodedPage)> = plan
.into_par_iter()
.filter_map(|(order, page_index, round)| {
if stop_worker.load(Ordering::Relaxed) { return None; }
let texts = source.text_page(page_index, lanes).ok()?;
let image = qr::render_qr_grid(&texts, canvas_side).ok()?;
Some((order, EncodedPage { page_index, round, image }))
})
.collect();
rendered.sort_unstable_by_key(|(order, _)| *order);
if rendered.is_empty() {
thread::sleep(Duration::from_millis(3));
continue;
}
// Reorder the parallel batch explicitly before queueing.
for (_, mut item) in rendered {
loop {
match tx.try_send(item) {
Ok(()) => break,
Err(TrySendError::Full(returned)) => {
item = returned;
if stop_worker.load(Ordering::Relaxed) { return; }
thread::sleep(Duration::from_millis(1));
}
Err(TrySendError::Disconnected(_)) => return,
}
}
}
}
});
Self {
rx,
stop,
thread: Some(thread),
capacity_pages,
cache_mib,
estimated_page_mib,
}
}
pub fn try_next(&self) -> Result<EncodedPage, TryRecvError> {
self.rx.try_recv()
}
}
impl Drop for OpticalPrefetcher {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(handle) = self.thread.take() {
let _ = handle.join();
}
}
}
+178
View File
@@ -0,0 +1,178 @@
use anyhow::{Context, Result};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use rand::RngCore;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{
fs,
net::{IpAddr, Ipv4Addr},
path::PathBuf,
};
pub const PAIR_PREFIX: &str = "QFTPAIR2:";
#[derive(Clone, Debug)]
pub struct PairingPayload {
pub v: u8,
pub session: String,
pub pc_name: String,
pub transport: String,
pub port: u16,
pub endpoints: Vec<String>,
pub wifi: Option<WifiCredentials>,
}
#[derive(Clone, Debug)]
pub struct WifiCredentials {
pub ssid: String,
pub passphrase: String,
pub security: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct DirectApIdentity {
version: u8,
ssid: String,
passphrase: String,
}
impl PairingPayload {
/// v2 intentionally uses short JSON keys. The Direct-AP QR no longer carries
/// a long transport string/security object and only keeps a small endpoint
/// fallback list. This materially lowers QR density and speeds phone scan.
pub fn encode_text(&self) -> Result<String> {
// Direct-AP pairing carries one short endpoint hint for the immediate
// happy path, while Android still treats the connected gateway + UDP
// discovery as authoritative fallbacks. One endpoint keeps QFTPAIR2
// compact but avoids a full discovery round on common Windows APs.
let endpoints: Vec<&str> = if self.wifi.is_some() {
self.endpoints.iter().take(1).map(String::as_str).collect()
} else {
self.endpoints.iter().take(3).map(String::as_str).collect()
};
let wifi = self.wifi.as_ref().map(|w| json!([w.ssid, w.passphrase]));
let value = json!({
"v": 2,
"s": self.session,
"n": self.pc_name,
"p": self.port,
"e": endpoints,
"w": wifi,
});
let json = serde_json::to_vec(&value).context("serialize pairing payload")?;
Ok(format!("{PAIR_PREFIX}{}", URL_SAFE_NO_PAD.encode(json)))
}
}
pub fn new_session_token() -> String {
let mut bytes = [0u8; 16];
rand::rng().fill_bytes(&mut bytes);
URL_SAFE_NO_PAD.encode(bytes)
}
/// Keep one random AP identity per Windows device so Android can remember the
/// user's approval for that exact local-only network. The AP itself is only
/// active while QFT receive mode is running; the file-transfer session token is
/// regenerated every time receive mode starts.
pub fn load_or_create_direct_ap_credentials(pc_name: &str) -> Result<(String, String)> {
let path = direct_ap_identity_path();
if let Ok(bytes) = fs::read(&path) {
if let Ok(identity) = serde_json::from_slice::<DirectApIdentity>(&bytes) {
if identity.version == 1
&& !identity.ssid.trim().is_empty()
&& (8..=63).contains(&identity.passphrase.len())
{
return Ok((identity.ssid, identity.passphrase));
}
}
}
let (ssid, passphrase) = new_direct_ap_credentials(pc_name);
let identity = DirectApIdentity {
version: 1,
ssid: ssid.clone(),
passphrase: passphrase.clone(),
};
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("创建 QFT 配置目录 {} 失败", parent.display()))?;
}
let tmp = path.with_extension("json.tmp");
let json = serde_json::to_vec_pretty(&identity)?;
fs::write(&tmp, json)
.with_context(|| format!("保存 QFT Direct 身份 {} 失败", tmp.display()))?;
if path.exists() {
let _ = fs::remove_file(&path);
}
fs::rename(&tmp, &path)
.with_context(|| format!("完成 QFT Direct 身份保存 {} 失败", path.display()))?;
Ok((ssid, passphrase))
}
pub fn reset_direct_ap_credentials() -> Result<()> {
let path = direct_ap_identity_path();
if path.exists() {
fs::remove_file(&path)
.with_context(|| format!("删除 QFT Direct 身份 {} 失败", path.display()))?;
}
Ok(())
}
fn direct_ap_identity_path() -> PathBuf {
if let Ok(root) = std::env::var("LOCALAPPDATA") {
if !root.trim().is_empty() {
return PathBuf::from(root).join("QFT").join("direct-ap.json");
}
}
PathBuf::from(".qft").join("direct-ap.json")
}
fn new_direct_ap_credentials(pc_name: &str) -> (String, String) {
let suffix = new_session_token();
let suffix = &suffix[..6.min(suffix.len())];
let base: String = pc_name
.chars()
.filter(|c| c.is_ascii_alphanumeric())
.take(10)
.collect();
let base = if base.is_empty() { "PC" } else { &base };
let ssid = format!("QFT-{base}-{suffix}");
let mut random = [0u8; 12];
rand::rng().fill_bytes(&mut random);
let password = URL_SAFE_NO_PAD.encode(random);
(ssid, password[..16.min(password.len())].to_owned())
}
pub fn local_ipv4_endpoints(port: u16) -> Vec<String> {
let mut ips = Vec::<Ipv4Addr>::new();
if let Ok(addrs) = if_addrs::get_if_addrs() {
for iface in addrs {
let IpAddr::V4(ip) = iface.ip() else { continue };
if ip.is_loopback() || ip.is_unspecified() || ip.is_link_local() {
continue;
}
if !ips.contains(&ip) {
ips.push(ip);
}
}
}
for fallback in [
Ipv4Addr::new(192, 168, 137, 1),
Ipv4Addr::new(192, 168, 49, 1),
] {
if !ips.contains(&fallback) {
ips.push(fallback);
}
}
ips.sort_by_key(|ip| {
if *ip == Ipv4Addr::new(192, 168, 137, 1) { 0 }
else if *ip == Ipv4Addr::new(192, 168, 49, 1) { 1 }
else if ip.is_private() { 2 }
else { 3 }
});
ips.into_iter()
.map(|ip| format!("http://{ip}:{port}"))
.collect()
}
+274
View File
@@ -0,0 +1,274 @@
use anyhow::{bail, Context, Result};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use crc32fast::hash as crc32;
use rand::RngCore;
use rayon::prelude::*;
use sha2::{Digest, Sha256};
use std::{
fs::File,
io::Read,
path::{Path, PathBuf},
};
pub const PREFIX: &str = "QFT1:";
pub const VERSION: u8 = 1;
#[derive(Clone, Copy, Debug)]
#[repr(u8)]
pub enum FrameKind {
Manifest = 1,
Data = 2,
End = 3,
}
#[derive(Clone, Debug)]
pub struct Manifest {
pub session_id: u64,
pub sender_device: String,
pub file_name: String,
pub file_size: u64,
pub chunk_size: u16,
pub total_chunks: u32,
pub sha256: [u8; 32],
}
pub struct TransferSource {
path: PathBuf,
file: File,
pub manifest: Manifest,
}
impl TransferSource {
pub fn open(path: impl AsRef<Path>, chunk_size: u16) -> Result<Self> {
if chunk_size == 0 {
bail!("chunk_size must be > 0");
}
let path = path.as_ref().to_path_buf();
let file = File::open(&path).context("open input file")?;
let file_size = file.metadata()?.len();
let total_chunks_u64 = if file_size == 0 {
0
} else {
(file_size + chunk_size as u64 - 1) / chunk_size as u64
};
if total_chunks_u64 > u32::MAX as u64 {
bail!("file requires too many chunks");
}
// Keep a single read-only file handle and use positioned reads for each
// optical chunk. This avoids mapping/touching a multi-GB file into the
// process working set, so the bounded QR prefetch cache remains the
// dominant managed memory consumer.
let sha256 = hash_file_streaming(&file)?;
let mut rng = rand::rng();
let session_id = rng.next_u64();
let file_name = path
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("qft.bin")
.to_owned();
let sender_device = local_device_name();
Ok(Self {
path,
file,
manifest: Manifest {
session_id,
sender_device,
file_name,
file_size,
chunk_size,
total_chunks: total_chunks_u64 as u32,
sha256,
},
})
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn total_playlist_frames(&self) -> u32 {
self.manifest.total_chunks.saturating_add(2)
}
pub fn total_pages(&self, lanes: usize) -> u32 {
let lanes = lanes.max(1) as u32;
let frames = self.total_playlist_frames();
(frames + lanes - 1) / lanes
}
/// Returns 1..=4 QFT text frames for one visual page. QR encodes are generated
/// in parallel by rayon; file bytes are read with positioned reads so workers
/// do not contend on a shared seek cursor and large files are not memory-mapped.
pub fn text_page(&self, page_index: u32, lanes: usize) -> Result<Vec<String>> {
let lanes = lanes.clamp(1, 4);
let total = self.total_playlist_frames();
let start = page_index.saturating_mul(lanes as u32);
if start >= total {
bail!("page index out of range");
}
let indices: Vec<u32> = (0..lanes)
.map(|lane| start + lane as u32)
.filter(|idx| *idx < total)
.collect();
indices
.into_par_iter()
.map(|idx| self.text_frame(idx))
.collect()
}
/// playlist_index: 0=manifest, 1..=N=data, N+1=end
pub fn text_frame(&self, playlist_index: u32) -> Result<String> {
let n = self.manifest.total_chunks;
if playlist_index == 0 {
return Ok(encode_manifest(&self.manifest));
}
if playlist_index >= 1 && playlist_index <= n {
return self.encode_data(playlist_index - 1);
}
if playlist_index == n + 1 {
return Ok(encode_frame(
FrameKind::End,
self.manifest.session_id,
0,
n,
&[],
));
}
bail!("playlist index out of range")
}
fn encode_data(&self, seq: u32) -> Result<String> {
let offset = seq as u64 * self.manifest.chunk_size as u64;
let remaining = self.manifest.file_size.saturating_sub(offset);
let len = remaining.min(self.manifest.chunk_size as u64) as usize;
let mut payload = vec![0u8; len];
if len > 0 {
read_exact_at(&self.file, &mut payload, offset)?;
}
Ok(encode_frame(
FrameKind::Data,
self.manifest.session_id,
seq,
self.manifest.total_chunks,
&payload,
))
}
}
fn encode_manifest(m: &Manifest) -> String {
let name = m.file_name.as_bytes();
let name_len = name.len().min(u16::MAX as usize) as u16;
let device = m.sender_device.as_bytes();
let device_len = device.len().min(u16::MAX as usize) as u16;
let mut payload = Vec::with_capacity(
8 + 2 + 32 + 2 + name_len as usize + 2 + device_len as usize,
);
payload.extend_from_slice(&m.file_size.to_be_bytes());
payload.extend_from_slice(&m.chunk_size.to_be_bytes());
payload.extend_from_slice(&m.sha256);
payload.extend_from_slice(&name_len.to_be_bytes());
payload.extend_from_slice(&name[..name_len as usize]);
payload.extend_from_slice(&device_len.to_be_bytes());
payload.extend_from_slice(&device[..device_len as usize]);
encode_frame(
FrameKind::Manifest,
m.session_id,
0,
m.total_chunks,
&payload,
)
}
pub fn encode_frame(
kind: FrameKind,
session_id: u64,
seq: u32,
total_chunks: u32,
payload: &[u8],
) -> String {
assert!(payload.len() <= u16::MAX as usize);
let mut binary = Vec::with_capacity(28 + payload.len());
binary.extend_from_slice(b"QFT1");
binary.push(VERSION);
binary.push(kind as u8);
binary.extend_from_slice(&session_id.to_be_bytes());
binary.extend_from_slice(&seq.to_be_bytes());
binary.extend_from_slice(&total_chunks.to_be_bytes());
binary.extend_from_slice(&(payload.len() as u16).to_be_bytes());
binary.extend_from_slice(payload);
let crc = crc32(&binary);
binary.extend_from_slice(&crc.to_be_bytes());
format!("{PREFIX}{}", URL_SAFE_NO_PAD.encode(binary))
}
pub fn hex_sha256(bytes: &[u8; 32]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(64);
for &b in bytes {
out.push(HEX[(b >> 4) as usize] as char);
out.push(HEX[(b & 0x0f) as usize] as char);
}
out
}
pub fn local_device_name() -> String {
let raw = std::env::var("COMPUTERNAME")
.or_else(|_| std::env::var("HOSTNAME"))
.unwrap_or_else(|_| "Windows-PC".to_owned());
let cleaned: String = raw
.chars()
.filter(|ch| !ch.is_control())
.take(64)
.collect();
if cleaned.trim().is_empty() {
"Windows-PC".to_owned()
} else {
cleaned
}
}
fn hash_file_streaming(file: &File) -> Result<[u8; 32]> {
let mut input = file.try_clone().context("clone input for sha256")?;
let mut hasher = Sha256::new();
let mut buf = vec![0u8; 4 * 1024 * 1024];
loop {
let n = input.read(&mut buf).context("read input for sha256")?;
if n == 0 { break; }
hasher.update(&buf[..n]);
}
Ok(hasher.finalize().into())
}
fn read_exact_at(file: &File, mut out: &mut [u8], mut offset: u64) -> Result<()> {
while !out.is_empty() {
let n = read_at_once(file, out, offset)?;
if n == 0 { bail!("unexpected EOF at offset {offset}"); }
offset = offset.saturating_add(n as u64);
let (_, rest) = out.split_at_mut(n);
out = rest;
}
Ok(())
}
#[cfg(windows)]
fn read_at_once(file: &File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
use std::os::windows::fs::FileExt;
file.seek_read(out, offset)
}
#[cfg(unix)]
fn read_at_once(file: &File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
use std::os::unix::fs::FileExt;
file.read_at(out, offset)
}
#[cfg(not(any(windows, unix)))]
fn read_at_once(file: &File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
use std::io::{Seek, SeekFrom};
let mut cloned = file.try_clone()?;
cloned.seek(SeekFrom::Start(offset))?;
cloned.read(out)
}
+103
View File
@@ -0,0 +1,103 @@
use anyhow::{Context, Result};
use eframe::egui::ColorImage;
use qrcode::{types::Color, EcLevel, QrCode};
use rayon::prelude::*;
const QUIET_MODULES: usize = 4;
/// Render exact black/white pixels with an explicit quiet zone.
pub fn render_qr(text: &str, scale: usize) -> Result<ColorImage> {
let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::L)
.context("QR payload too large")?;
let modules = code.width();
let scale = scale.max(1);
let side_modules = modules + QUIET_MODULES * 2;
let side_px = side_modules * scale;
let gray = render_code_gray(&code, side_px);
Ok(ColorImage::from_gray([side_px, side_px], &gray))
}
/// Render 1..=4 independent QR symbols into one fixed-size optical page.
/// A 2x2 page quadruples the number of logical QFT frames presented per
/// display refresh while keeping every symbol standards-compliant.
pub fn render_qr_grid(texts: &[String], canvas_side: usize) -> Result<ColorImage> {
let count = texts.len().clamp(1, 4);
if count == 1 {
return render_qr_fitted(&texts[0], canvas_side.max(320));
}
let canvas_side = canvas_side.max(640);
let gutter = (canvas_side / 64).clamp(12, 24);
let cell = (canvas_side - gutter * 3) / 2;
let rendered: Vec<(usize, Vec<u8>)> = texts[..count]
.par_iter()
.map(|text| render_qr_gray_fitted(text, cell))
.collect::<Result<Vec<_>>>()?;
let mut canvas = vec![255u8; canvas_side * canvas_side];
for (index, (side, gray)) in rendered.into_iter().enumerate() {
let col = index % 2;
let row = index / 2;
let cell_x = gutter + col * (cell + gutter);
let cell_y = gutter + row * (cell + gutter);
let x0 = cell_x + (cell.saturating_sub(side)) / 2;
let y0 = cell_y + (cell.saturating_sub(side)) / 2;
for y in 0..side {
let dst = (y0 + y) * canvas_side + x0;
let src = y * side;
canvas[dst..dst + side].copy_from_slice(&gray[src..src + side]);
}
}
Ok(ColorImage::from_gray([canvas_side, canvas_side], &canvas))
}
/// Pairing QR favors scan reliability over maximum capacity. QFTPAIR2 is kept
/// deliberately short, so medium error correction still yields a low-version
/// symbol that phones acquire faster at imperfect angles.
pub fn render_pair_qr(text: &str, target_side: usize) -> Result<ColorImage> {
let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::M)
.context("pair QR payload too large")?;
let modules = code.width() + QUIET_MODULES * 2;
let scale = (target_side / modules).max(1);
let side = modules * scale;
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
}
pub fn render_qr_fitted(text: &str, target_side: usize) -> Result<ColorImage> {
let (side, gray) = render_qr_gray_fitted(text, target_side)?;
Ok(ColorImage::from_gray([side, side], &gray))
}
fn render_qr_gray_fitted(text: &str, target_side: usize) -> Result<(usize, Vec<u8>)> {
let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::L)
.context("QR payload too large")?;
let modules = code.width() + QUIET_MODULES * 2;
let scale = (target_side / modules).max(1);
let side = modules * scale;
Ok((side, render_code_gray(&code, side)))
}
fn render_code_gray(code: &QrCode, side_px: usize) -> Vec<u8> {
let modules = code.width();
let side_modules = modules + QUIET_MODULES * 2;
let scale = (side_px / side_modules).max(1);
let actual_side = side_modules * scale;
let mut gray = vec![255u8; actual_side * actual_side];
let colors = code.to_colors();
for y in 0..modules {
for x in 0..modules {
if colors[y * modules + x] != Color::Dark {
continue;
}
let x0 = (x + QUIET_MODULES) * scale;
let y0 = (y + QUIET_MODULES) * scale;
for py in y0..y0 + scale {
let row = py * actual_side;
gray[row + x0..row + x0 + scale].fill(0);
}
}
}
gray
}
+540
View File
@@ -0,0 +1,540 @@
use anyhow::{bail, Context, Result};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use rand::RngCore;
use serde_json::json;
use sha2::{Digest, Sha256};
use std::{
collections::HashMap,
fs::{self, File, OpenOptions},
io::{BufRead, BufReader, Read, Seek, SeekFrom, Write},
net::{TcpListener, TcpStream, UdpSocket},
path::{Path, PathBuf},
sync::{
atomic::{AtomicBool, Ordering},
mpsc::Sender,
Arc, Mutex,
},
thread::{self, JoinHandle},
time::{Duration, Instant},
};
pub const PREFERRED_PORT: u16 = 39393;
pub const DISCOVERY_PORT: u16 = 39392;
pub const PARALLEL_CHUNK_SIZE: u64 = 8 * 1024 * 1024;
const IO_BUFFER: usize = 1024 * 1024;
#[derive(Clone, Debug)]
pub enum ReceiverEvent {
ClientConnected { device: String },
UploadStarted { device: String, file_name: String, size: u64 },
UploadProgress { device: String, file_name: String, received: u64, size: u64 },
UploadCompleted { device: String, file_name: String, saved_path: PathBuf, sha256: String },
Error(String),
}
#[derive(Debug)]
struct UploadSession {
device: String,
file_name: String,
size: u64,
chunk_size: u64,
total_chunks: u32,
part_path: PathBuf,
final_path: PathBuf,
received: Vec<bool>,
received_bytes: u64,
}
type SessionMap = Arc<Mutex<HashMap<String, Arc<Mutex<UploadSession>>>>>;
pub struct ReceiverServer {
pub port: u16,
stop: Arc<AtomicBool>,
tcp_thread: Option<JoinHandle<()>>,
udp_thread: Option<JoinHandle<()>>,
}
impl ReceiverServer {
pub fn start(save_dir: PathBuf, session_token: String, events: Sender<ReceiverEvent>) -> Result<Self> {
fs::create_dir_all(&save_dir).context("创建接收目录失败")?;
let listener = TcpListener::bind(("0.0.0.0", PREFERRED_PORT))
.or_else(|_| TcpListener::bind(("0.0.0.0", 0)))
.context("启动本地接收端口失败")?;
let port = listener.local_addr()?.port();
listener.set_nonblocking(true)?;
let stop = Arc::new(AtomicBool::new(false));
let sessions: SessionMap = Arc::new(Mutex::new(HashMap::new()));
let stop_tcp = stop.clone();
let sessions_tcp = sessions.clone();
let token_tcp = session_token.clone();
let dir_tcp = save_dir.clone();
let events_tcp = events.clone();
let tcp_thread = thread::spawn(move || {
while !stop_tcp.load(Ordering::Relaxed) {
match listener.accept() {
Ok((stream, _)) => {
let dir = dir_tcp.clone();
let token = token_tcp.clone();
let tx = events_tcp.clone();
let sessions = sessions_tcp.clone();
thread::spawn(move || {
if let Err(e) = handle_client(stream, &dir, &token, &tx, &sessions) {
let _ = tx.send(ReceiverEvent::Error(format!("接收失败:{e:#}")));
}
});
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(12));
}
Err(e) => {
let _ = events_tcp.send(ReceiverEvent::Error(format!("监听端口失败:{e}")));
break;
}
}
}
});
let stop_udp = stop.clone();
let token_udp = session_token;
let udp_thread = thread::spawn(move || {
let socket = match UdpSocket::bind(("0.0.0.0", DISCOVERY_PORT)) {
Ok(v) => v,
Err(e) => {
let _ = events.send(ReceiverEvent::Error(format!(
"快速发现端口 {DISCOVERY_PORT} 不可用:{e}。仍可使用网关/IP 探测。"
)));
return;
}
};
let _ = socket.set_read_timeout(Some(Duration::from_millis(250)));
let expected = format!("QFTDISC2:{token_udp}");
let response = format!("QFTHERE2:{token_udp}:{port}");
let mut buf = [0u8; 512];
while !stop_udp.load(Ordering::Relaxed) {
match socket.recv_from(&mut buf) {
Ok((n, peer)) => {
if std::str::from_utf8(&buf[..n]).ok() == Some(expected.as_str()) {
let _ = socket.send_to(response.as_bytes(), peer);
}
}
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {}
Err(_) => break,
}
}
});
Ok(Self {
port,
stop,
tcp_thread: Some(tcp_thread),
udp_thread: Some(udp_thread),
})
}
}
impl Drop for ReceiverServer {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(handle) = self.tcp_thread.take() {
let _ = handle.join();
}
if let Some(handle) = self.udp_thread.take() {
let _ = handle.join();
}
}
}
fn handle_client(
mut stream: TcpStream,
save_dir: &Path,
token: &str,
events: &Sender<ReceiverEvent>,
sessions: &SessionMap,
) -> Result<()> {
stream.set_nodelay(true).ok();
stream.set_read_timeout(Some(Duration::from_secs(120)))?;
stream.set_write_timeout(Some(Duration::from_secs(120)))?;
let cloned = stream.try_clone()?;
let mut reader = BufReader::with_capacity(64 * 1024, cloned);
let mut request_line = String::new();
reader.read_line(&mut request_line)?;
if request_line.len() > 8192 { bail!("请求行过长") }
let mut headers = HashMap::<String, String>::new();
loop {
let mut line = String::new();
let n = reader.read_line(&mut line)?;
if n == 0 { bail!("连接提前关闭") }
if line == "\r\n" || line == "\n" { break }
if line.len() > 16 * 1024 { bail!("请求头过长") }
if let Some((k, v)) = line.split_once(':') {
headers.insert(k.trim().to_ascii_lowercase(), v.trim().to_owned());
}
}
let mut parts = request_line.split_whitespace();
let method = parts.next().unwrap_or("");
let path = parts.next().unwrap_or("");
let supplied = headers.get("x-qft-token").map(String::as_str).unwrap_or("");
if supplied != token {
return write_response(&mut stream, 403, "text/plain", b"invalid session");
}
let device = decode_header(headers.get("x-qft-device")).unwrap_or_else(|| "Android".to_owned());
let _ = events.send(ReceiverEvent::ClientConnected { device: device.clone() });
if method == "GET" && path == "/qft/ping" {
let body = json!({"ok": true, "protocol": 2, "parallel": true}).to_string();
return write_response(&mut stream, 200, "application/json", body.as_bytes());
}
if method == "POST" && path == "/qft/upload/init" {
return init_parallel_upload(&mut stream, save_dir, &headers, &device, events, sessions);
}
if method == "POST" && path.starts_with("/qft/upload/chunk/") {
return receive_parallel_chunk(&mut stream, &mut reader, path, &headers, events, sessions);
}
if method == "POST" && path.starts_with("/qft/upload/finish/") {
return finish_parallel_upload(&mut stream, path, events, sessions);
}
// Compatibility path for old clients and content providers that cannot seek.
if method == "POST" && path == "/qft/upload" {
return receive_legacy_stream(&mut stream, &mut reader, save_dir, &headers, &device, events);
}
write_response(&mut stream, 404, "text/plain", b"not found")
}
fn init_parallel_upload(
stream: &mut TcpStream,
save_dir: &Path,
headers: &HashMap<String, String>,
device: &str,
events: &Sender<ReceiverEvent>,
sessions: &SessionMap,
) -> Result<()> {
let file_name = decode_header(headers.get("x-qft-filename"))
.map(sanitize_file_name)
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "qft-upload.bin".to_owned());
let size: u64 = headers.get("x-qft-size")
.context("缺少 X-QFT-Size")?
.parse().context("X-QFT-Size 无效")?;
let chunk_size = headers.get("x-qft-chunk-size")
.and_then(|v| v.parse::<u64>().ok())
.map(|v| v.clamp(1024 * 1024, 16 * 1024 * 1024))
.unwrap_or(PARALLEL_CHUNK_SIZE);
let total_chunks_u64 = if size == 0 { 0 } else { (size + chunk_size - 1) / chunk_size };
if total_chunks_u64 > u32::MAX as u64 { bail!("文件分块数过大") }
let total_chunks = total_chunks_u64 as u32;
let upload_id = random_id();
let mut map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
let final_path = unique_path_reserved(save_dir, &file_name, map.values());
let final_name = final_path.file_name().and_then(|v| v.to_str()).unwrap_or("qft-upload.bin");
let part_path = final_path.with_file_name(format!("{final_name}.{upload_id}.qftpart"));
let part = File::create(&part_path)
.with_context(|| format!("创建临时文件 {}", part_path.display()))?;
part.set_len(size)?;
drop(part);
let session = UploadSession {
device: device.to_owned(),
file_name: file_name.clone(),
size,
chunk_size,
total_chunks,
part_path,
final_path,
received: vec![false; total_chunks as usize],
received_bytes: 0,
};
map.insert(upload_id.clone(), Arc::new(Mutex::new(session)));
drop(map);
let _ = events.send(ReceiverEvent::UploadStarted {
device: device.to_owned(),
file_name,
size,
});
let body = json!({
"ok": true,
"upload_id": upload_id,
"chunk_size": chunk_size,
"total_chunks": total_chunks,
}).to_string();
write_response(stream, 200, "application/json", body.as_bytes())
}
fn receive_parallel_chunk(
stream: &mut TcpStream,
reader: &mut BufReader<TcpStream>,
path: &str,
headers: &HashMap<String, String>,
events: &Sender<ReceiverEvent>,
sessions: &SessionMap,
) -> Result<()> {
let suffix = path.trim_start_matches("/qft/upload/chunk/");
let (upload_id, index_text) = suffix.split_once('/').context("chunk 路径无效")?;
let index: u32 = index_text.parse().context("chunk index 无效")?;
let content_len: u64 = headers.get("content-length")
.context("缺少 Content-Length")?
.parse().context("Content-Length 无效")?;
let session_arc = {
let map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
map.get(upload_id).cloned().context("上传会话不存在或已完成")?
};
let (part_path, offset, expected_len, device, file_name, size, already) = {
let session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
if index >= session.total_chunks { bail!("chunk index 越界") }
let offset = index as u64 * session.chunk_size;
let expected = (session.size - offset).min(session.chunk_size);
(
session.part_path.clone(),
offset,
expected,
session.device.clone(),
session.file_name.clone(),
session.size,
session.received[index as usize],
)
};
if content_len != expected_len { bail!("chunk 长度不匹配:{content_len} != {expected_len}") }
if already {
drain_exact(reader, content_len)?;
return write_response(stream, 200, "application/json", b"{\"ok\":true,\"duplicate\":true}");
}
let mut out = OpenOptions::new().write(true).open(&part_path)?;
out.seek(SeekFrom::Start(offset))?;
copy_exact(reader, &mut out, content_len)?;
out.flush()?;
let received = {
let mut session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
if !session.received[index as usize] {
session.received[index as usize] = true;
session.received_bytes = session.received_bytes.saturating_add(content_len);
}
session.received_bytes
};
let _ = events.send(ReceiverEvent::UploadProgress { device, file_name, received, size });
write_response(stream, 200, "application/json", b"{\"ok\":true}")
}
fn finish_parallel_upload(
stream: &mut TcpStream,
path: &str,
events: &Sender<ReceiverEvent>,
sessions: &SessionMap,
) -> Result<()> {
let upload_id = path.trim_start_matches("/qft/upload/finish/");
let session_arc = {
let map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
map.get(upload_id).cloned().context("上传会话不存在或已完成")?
};
let (device, file_name, size, part_path, final_path) = {
let session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
if session.received.iter().any(|v| !*v) {
let missing = session.received.iter().filter(|v| !**v).count();
let body = json!({"ok": false, "missing": missing}).to_string();
return write_response(stream, 409, "application/json", body.as_bytes());
}
(
session.device.clone(), session.file_name.clone(), session.size,
session.part_path.clone(), session.final_path.clone(),
)
};
let sha = hash_file(&part_path)?;
if final_path.exists() { bail!("目标文件已存在,请重新初始化上传") }
fs::rename(&part_path, &final_path).context("完成文件重命名失败")?;
{
let mut map = sessions.lock().map_err(|_| anyhow::anyhow!("上传会话锁损坏"))?;
map.remove(upload_id);
}
let _ = events.send(ReceiverEvent::UploadCompleted {
device, file_name, saved_path: final_path, sha256: sha.clone(),
});
let body = json!({"ok": true, "sha256": sha, "size": size}).to_string();
write_response(stream, 200, "application/json", body.as_bytes())
}
fn receive_legacy_stream(
stream: &mut TcpStream,
reader: &mut BufReader<TcpStream>,
save_dir: &Path,
headers: &HashMap<String, String>,
device: &str,
events: &Sender<ReceiverEvent>,
) -> Result<()> {
let file_name = decode_header(headers.get("x-qft-filename"))
.map(sanitize_file_name)
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "qft-upload.bin".to_owned());
let size: u64 = headers.get("content-length")
.context("缺少 Content-Length")?
.parse().context("Content-Length 无效")?;
let declared_size = headers.get("x-qft-size")
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(size);
if declared_size != size { bail!("文件大小头与 Content-Length 不一致") }
let final_path = unique_path(save_dir, &file_name);
let final_name = final_path.file_name().and_then(|v| v.to_str()).unwrap_or("qft-upload.bin");
let part_path = final_path.with_file_name(format!("{final_name}.qftpart"));
let mut out = File::create(&part_path).with_context(|| format!("创建临时文件 {}", part_path.display()))?;
let _ = events.send(ReceiverEvent::UploadStarted { device: device.to_owned(), file_name: file_name.clone(), size });
let mut remaining = size;
let mut received = 0u64;
let mut buf = vec![0u8; IO_BUFFER];
let mut hasher = Sha256::new();
let mut last_report = Instant::now();
while remaining > 0 {
let want = remaining.min(buf.len() as u64) as usize;
let n = reader.read(&mut buf[..want])?;
if n == 0 { bail!("上传中连接提前关闭:{received}/{size}") }
out.write_all(&buf[..n])?;
hasher.update(&buf[..n]);
received += n as u64;
remaining -= n as u64;
if last_report.elapsed() >= Duration::from_millis(100) || remaining == 0 {
let _ = events.send(ReceiverEvent::UploadProgress {
device: device.to_owned(), file_name: file_name.clone(), received, size,
});
last_report = Instant::now();
}
}
out.sync_all()?;
drop(out);
fs::rename(&part_path, &final_path).context("完成文件重命名失败")?;
let sha = hex(&hasher.finalize());
let _ = events.send(ReceiverEvent::UploadCompleted {
device: device.to_owned(), file_name, saved_path: final_path, sha256: sha,
});
write_response(stream, 200, "application/json", b"{\"ok\":true,\"legacy\":true}")
}
fn copy_exact(reader: &mut impl Read, writer: &mut impl Write, mut remaining: u64) -> Result<()> {
let mut buf = vec![0u8; IO_BUFFER];
while remaining > 0 {
let want = remaining.min(buf.len() as u64) as usize;
let n = reader.read(&mut buf[..want])?;
if n == 0 { bail!("chunk 上传中连接提前关闭") }
writer.write_all(&buf[..n])?;
remaining -= n as u64;
}
Ok(())
}
fn drain_exact(reader: &mut impl Read, remaining: u64) -> Result<()> {
copy_exact(reader, &mut std::io::sink(), remaining)
}
fn hash_file(path: &Path) -> Result<String> {
let mut input = File::open(path)?;
let mut hasher = Sha256::new();
let mut buf = vec![0u8; 4 * 1024 * 1024];
loop {
let n = input.read(&mut buf)?;
if n == 0 { break }
hasher.update(&buf[..n]);
}
Ok(hex(&hasher.finalize()))
}
fn write_response(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> Result<()> {
let reason = match code {
200 => "OK", 400 => "Bad Request", 403 => "Forbidden", 404 => "Not Found",
409 => "Conflict", _ => "Error",
};
write!(stream,
"HTTP/1.1 {code} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len())?;
stream.write_all(body)?;
stream.flush()?;
Ok(())
}
fn decode_header(value: Option<&String>) -> Option<String> {
let raw = value?;
let bytes = URL_SAFE_NO_PAD.decode(raw).ok()?;
String::from_utf8(bytes).ok()
}
fn sanitize_file_name(name: String) -> String {
let cleaned: String = name.chars()
.map(|c| if c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*') { '_' } else { c })
.collect();
cleaned.trim().trim_matches('.').chars().take(180).collect()
}
fn unique_path(dir: &Path, name: &str) -> PathBuf {
let base = Path::new(name);
let stem = base.file_stem().and_then(|s| s.to_str()).unwrap_or("qft-upload");
let ext = base.extension().and_then(|s| s.to_str());
let mut candidate = dir.join(name);
let mut n = 1;
while candidate.exists() {
let next = match ext {
Some(ext) => format!("{stem} ({n}).{ext}"),
None => format!("{stem} ({n})"),
};
candidate = dir.join(next);
n += 1;
}
candidate
}
fn unique_path_reserved<'a>(
dir: &Path,
name: &str,
sessions: impl Iterator<Item = &'a Arc<Mutex<UploadSession>>>,
) -> PathBuf {
let reserved: Vec<PathBuf> = sessions
.filter_map(|s| s.lock().ok().map(|v| v.final_path.clone()))
.collect();
let base = Path::new(name);
let stem = base.file_stem().and_then(|s| s.to_str()).unwrap_or("qft-upload");
let ext = base.extension().and_then(|s| s.to_str());
let mut n = 0u32;
loop {
let next_name = if n == 0 {
name.to_owned()
} else {
match ext {
Some(ext) => format!("{stem} ({n}).{ext}"),
None => format!("{stem} ({n})"),
}
};
let candidate = dir.join(next_name);
if !candidate.exists() && !reserved.contains(&candidate) {
return candidate;
}
n += 1;
}
}
fn random_id() -> String {
let mut bytes = [0u8; 12];
rand::rng().fill_bytes(&mut bytes);
URL_SAFE_NO_PAD.encode(bytes)
}
fn hex(bytes: &[u8]) -> String {
const H: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for &b in bytes { out.push(H[(b >> 4) as usize] as char); out.push(H[(b & 15) as usize] as char); }
out
}