V0.4.0加入锁定二维码

This commit is contained in:
zhy
2026-08-10 17:09:30 +08:00
parent d885259e2b
commit 241e22abea
34 changed files with 1754 additions and 985 deletions
+37
View File
@@ -0,0 +1,37 @@
const ALPHABET: &[u8; 45] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
/// RFC 9285 Base45. Its alphabet is fully supported by QR alphanumeric mode,
/// so the QR encoder can use fewer modules than Base64 text for the same
/// binary QFT frame while still giving Android a normal Result.text string.
pub fn encode(input: &[u8]) -> String {
if input.is_empty() {
return String::new();
}
let mut out = String::with_capacity((input.len() * 3 + 1) / 2);
let mut i = 0usize;
while i + 1 < input.len() {
let value = input[i] as usize * 256 + input[i + 1] as usize;
out.push(ALPHABET[value % 45] as char);
out.push(ALPHABET[(value / 45) % 45] as char);
out.push(ALPHABET[value / (45 * 45)] as char);
i += 2;
}
if i < input.len() {
let value = input[i] as usize;
out.push(ALPHABET[value % 45] as char);
out.push(ALPHABET[value / 45] as char);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_vectors() {
assert_eq!(encode(b"AB"), "BB8");
assert_eq!(encode(b"Hello!!"), "%69 VD92EX0");
assert_eq!(encode(b"base-45"), "UJCLQE7W581");
}
}
+160 -92
View File
@@ -1,3 +1,4 @@
mod base45;
mod direct_ap;
mod optical_cache;
mod pairing;
@@ -16,9 +17,9 @@ use std::{
time::{Duration, Instant},
};
const DEFAULT_CHUNK_SIZE: u16 = 900;
const DEFAULT_CHUNK_SIZE: u16 = 450;
const UI_FONT_NAME: &str = "qft-ui";
const APP_VERSION: &str = "0.3.0-rc3";
const APP_VERSION: &str = "0.4.0-rc2";
fn main() -> eframe::Result {
let options = eframe::NativeOptions {
@@ -50,8 +51,11 @@ struct OpticalState {
round: u64,
playing: bool,
fps: f32,
lanes: usize,
cache_mib: usize,
control_width: f32,
qr_zoom: f32,
focus_qr: bool,
advanced_open: bool,
last_advance: Instant,
fps_window_started: Instant,
displayed_in_window: u32,
@@ -105,14 +109,17 @@ impl QftApp {
page_index: 0,
round: 0,
playing: false,
fps: 60.0,
lanes: 4,
cache_mib: 384,
fps: 45.0,
cache_mib: 256,
control_width: 330.0,
qr_zoom: 1.0,
focus_qr: false,
advanced_open: false,
last_advance: Instant::now(),
fps_window_started: Instant::now(),
displayed_in_window: 0,
actual_page_fps: 0.0,
status: "选择文件后开始光学发送。默认 4 码/页 · 60 FPS,缓存不足时会自动停在当前页等待。".into(),
status: "选择文件后开始光学发送。v0.4 使用单个大二维码 + QFT2/Base45 低密度 450B 数据块,优先提高 Android 有效识别率。".into(),
},
receive: ReceiveState {
save_dir: None,
@@ -209,118 +216,180 @@ impl QftApp {
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.heading("电脑 → Android · 单码锁定极速模式");
ui.separator();
ui.label("屏幕 → 摄像头 · 0 网络");
ui.separator();
if ui.button(if self.optical.focus_qr { "退出专注二维码" } else { "专注二维码" }).clicked() {
self.optical.focus_qr = !self.optical.focus_qr;
}
});
ui.add_space(8.0);
ui.group(|ui| {
if self.optical.focus_qr {
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();
}
let enabled = self.optical.source.is_some();
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() {
ui.label(format!("{:.0} FPS", self.optical.fps));
ui.add(egui::Slider::new(&mut self.optical.qr_zoom, 0.65..=1.0).text("二维码占比").show_value(false));
ui.small("控制区已收起,尽可能把屏幕面积留给二维码");
});
ui.separator();
self.optical_qr_panel(ui);
return;
}
let available = ui.available_size();
let min_qr_width = 360.0_f32.min(available.x * 0.55);
let max_control = (available.x - min_qr_width - 12.0).max(240.0);
self.optical.control_width = self.optical.control_width.clamp(240.0, max_control);
let split_height = ui.available_height().max(420.0);
ui.horizontal(|ui| {
ui.allocate_ui_with_layout(
egui::vec2(self.optical.control_width, split_height),
egui::Layout::top_down(egui::Align::Min),
|ui| {
egui::ScrollArea::vertical().show(ui, |ui| {
self.optical_controls(ui, ctx);
});
},
);
let (bar_rect, bar_response) = ui.allocate_exact_size(
egui::vec2(8.0, split_height),
egui::Sense::drag(),
);
let bar_color = if bar_response.dragged() || bar_response.hovered() {
ui.visuals().widgets.active.bg_fill
} else {
ui.visuals().widgets.inactive.bg_fill
};
ui.painter().rect_filled(bar_rect.shrink2(egui::vec2(2.0, 0.0)), 3.0, bar_color);
if bar_response.dragged() {
let dx = ui.input(|i| i.pointer.delta().x);
self.optical.control_width = (self.optical.control_width + dx).clamp(240.0, max_control);
ctx.request_repaint();
}
bar_response.on_hover_text("拖动压缩/展开控制区,右侧二维码会自动放大");
ui.allocate_ui_with_layout(
egui::vec2(ui.available_width(), split_height),
egui::Layout::top_down(egui::Align::Center),
|ui| self.optical_qr_panel(ui),
);
});
}
fn optical_controls(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
ui.group(|ui| {
ui.heading("发送控制");
ui.horizontal_wrapped(|ui| {
if ui.button("选择文件").clicked() { self.optical_pick_file(ctx); }
let enabled = self.optical.source.is_some();
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(6.0);
ui.label("显示刷新率");
ui.add(egui::Slider::new(&mut self.optical.fps, 5.0..=60.0).suffix(" FPS").step_by(1.0));
ui.horizontal_wrapped(|ui| {
if ui.small_button("稳定 30").clicked() { self.optical.fps = 30.0; }
if ui.small_button("平衡 45").clicked() { self.optical.fps = 45.0; }
if ui.small_button("最高 60").clicked() { self.optical.fps = 60.0; }
});
ui.small("Android 会先全屏搜索一次,然后锁定单个二维码区域进行局部高频解码;60 FPS 是显示目标,实际有效识别率由手机相机决定。");
});
ui.add_space(8.0);
ui.group(|ui| {
ui.heading("二维码可读性");
ui.label(format!("单码 · 每块 {} B · QFT2/Base45 · QR-L · 完整静区", DEFAULT_CHUNK_SIZE));
ui.add(egui::Slider::new(&mut self.optical.qr_zoom, 0.65..=1.0).text("画面占比"));
ui.small("v0.4 已彻底删除 4 码模式;QFT2 使用 Base45 让 QR 进入字母数字模式,比旧 Base64 文本更低密度。默认 450 B 数据块仍保持较低 QR 版本,让 Android 更容易稳定锁定。");
});
ui.add_space(8.0);
ui.checkbox(&mut self.optical.advanced_open, "高级设置");
if self.optical.advanced_open {
ui.group(|ui| {
let old_cache = self.optical.cache_mib;
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!(
"托管缓存最多 {} MiB;整进程设计预算约 {} MiB。缓存只影响二维码预编码是否跟得上,不会把整个文件读进内存。",
optical_cache::MAX_MANAGED_CACHE_MIB, optical_cache::HARD_PROCESS_BUDGET_MIB
));
if old_cache != self.optical.cache_mib {
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/页 · 定位读取"));
});
let pages = source.total_playlist_frames().max(1);
let payload_rate = self.optical.fps as f64 * m.chunk_size as f64;
ui.group(|ui| {
ui.small("实时状态");
ui.heading(format!("{:.1} 页/s", self.optical.actual_page_fps));
ui.label(format!("理论载荷 ≈ {}/s", human_bytes(payload_rate as u64)));
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.small(format!("预编码缓存:{} MiB · 最多 {cap} 帧 · {page_mib:.1} MiB/帧", self.optical.cache_mib));
ui.separator();
ui.label(format!("设备:{} → Android", m.sender_device));
ui.label(format!("文件:{} · {}", m.file_name, human_bytes(m.file_size)));
ui.label(format!("帧:{}/{} · 完整轮次:{}", self.optical.page_index + 1, pages, self.optical.round));
ui.small(format!("SHA-256:{}", hex_sha256(&m.sha256)));
});
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.add_space(6.0);
ui.label(&self.optical.status);
ui.separator();
}
fn optical_qr_panel(&mut self, ui: &mut egui::Ui) {
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))); });
let reserved = if self.optical.focus_qr { 4.0 } else { 28.0 };
let base = avail.x.min((avail.y - reserved).max(220.0)).max(220.0);
let side = (base * self.optical.qr_zoom).clamp(220.0, base);
ui.vertical_centered(|ui| {
ui.image((texture.id(), egui::vec2(side, side)));
if !self.optical.focus_qr {
ui.small("拖动左侧分隔条可继续放大二维码;也可点击顶部“专注二维码”占满可用区域。");
}
});
} else {
ui.vertical_centered(|ui| {
ui.add_space(100.0);
ui.add_space(120.0);
ui.heading("请选择一个文件");
ui.label("极速模式会在后台并行预编码二维码;手机仍可处于飞行模式。")
ui.label("单个大二维码会在这里显示,Android 识别后自动锁定区域。");
});
}
}
@@ -437,7 +506,7 @@ impl QftApp {
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();
self.optical.status = "文件已载入。默认单个大二维码 · QFT2/Base45 450B 数据块 · 45 FPS;可按手机能力切到 30 或 60 FPS。".into();
}
}
Err(e) => self.optical.status = format!("读取文件失败:{e:#}"),
@@ -445,7 +514,7 @@ impl QftApp {
}
fn optical_canvas_side(&self) -> usize {
if self.optical.lanes == 4 { 960 } else { 760 }
1024
}
fn restart_optical_pipeline(&mut self) {
@@ -455,7 +524,6 @@ impl QftApp {
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,
));
@@ -463,8 +531,8 @@ impl QftApp {
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())?;
let text = source.text_frame(0)?;
let image = qr::render_qr_fitted(&text, self.optical_canvas_side())?;
self.set_optical_texture(ctx, image);
self.optical.page_index = 0;
self.optical.round = 0;
@@ -507,7 +575,7 @@ impl QftApp {
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()
"正在光学发送 · 单个大二维码,Android 锁定后仅在二维码 ROI 内高频解码。".into()
};
}
Err(std::sync::mpsc::TryRecvError::Empty) => {
+7 -13
View File
@@ -11,14 +11,12 @@ use std::{
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.
/// Managed pre-render cache stays below the requested whole-process ceiling.
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;
const PREENCODE_BATCH: usize = 12;
pub struct EncodedPage {
pub page_index: u32,
@@ -38,12 +36,10 @@ pub struct OpticalPrefetcher {
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);
@@ -52,11 +48,10 @@ impl OpticalPrefetcher {
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.
// Single QR on screen, but multiple *future frames* are encoded in
// parallel so the display thread can still target 60 Hz.
let thread = thread::spawn(move || {
let total_pages = source.total_pages(lanes).max(1);
let total_pages = source.total_playlist_frames().max(1);
let mut next_page = 0u32;
let mut next_round = 0u64;
while !stop_worker.load(Ordering::Relaxed) {
@@ -74,8 +69,8 @@ impl OpticalPrefetcher {
.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()?;
let text = source.text_frame(page_index).ok()?;
let image = qr::render_qr_fitted(&text, canvas_side).ok()?;
Some((order, EncodedPage { page_index, round, image }))
})
.collect();
@@ -86,7 +81,6 @@ impl OpticalPrefetcher {
continue;
}
// Reorder the parallel batch explicitly before queueing.
for (_, mut item) in rendered {
loop {
match tx.try_send(item) {
+29 -49
View File
@@ -1,8 +1,7 @@
use crate::base45;
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,
@@ -10,8 +9,8 @@ use std::{
path::{Path, PathBuf},
};
pub const PREFIX: &str = "QFT1:";
pub const VERSION: u8 = 1;
pub const PREFIX: &str = "QFT2:";
pub const VERSION: u8 = 2;
#[derive(Clone, Copy, Debug)]
#[repr(u8)]
@@ -55,12 +54,7 @@ impl TransferSource {
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
@@ -93,43 +87,17 @@ impl TransferSource {
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> {
pub fn binary_frame(&self, playlist_index: u32) -> Result<Vec<u8>> {
let n = self.manifest.total_chunks;
if playlist_index == 0 {
return Ok(encode_manifest(&self.manifest));
return Ok(encode_manifest_binary(&self.manifest));
}
if playlist_index >= 1 && playlist_index <= n {
return self.encode_data(playlist_index - 1);
return self.encode_data_binary(playlist_index - 1);
}
if playlist_index == n + 1 {
return Ok(encode_frame(
return Ok(encode_frame_binary(
FrameKind::End,
self.manifest.session_id,
0,
@@ -140,7 +108,15 @@ impl TransferSource {
bail!("playlist index out of range")
}
fn encode_data(&self, seq: u32) -> Result<String> {
/// QFT2 uses Base45 because the whole alphabet is legal in QR alphanumeric
/// mode. This is close to raw byte efficiency without relying on ZXing's
/// rawBytes interpretation, and Android can consume Result.text directly.
pub fn text_frame(&self, playlist_index: u32) -> Result<String> {
let binary = self.binary_frame(playlist_index)?;
Ok(format!("{PREFIX}{}", base45::encode(&binary)))
}
fn encode_data_binary(&self, seq: u32) -> Result<Vec<u8>> {
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;
@@ -148,7 +124,7 @@ impl TransferSource {
if len > 0 {
read_exact_at(&self.file, &mut payload, offset)?;
}
Ok(encode_frame(
Ok(encode_frame_binary(
FrameKind::Data,
self.manifest.session_id,
seq,
@@ -158,7 +134,7 @@ impl TransferSource {
}
}
fn encode_manifest(m: &Manifest) -> String {
fn encode_manifest_binary(m: &Manifest) -> Vec<u8> {
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();
@@ -173,7 +149,7 @@ fn encode_manifest(m: &Manifest) -> String {
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(
encode_frame_binary(
FrameKind::Manifest,
m.session_id,
0,
@@ -182,16 +158,16 @@ fn encode_manifest(m: &Manifest) -> String {
)
}
pub fn encode_frame(
pub fn encode_frame_binary(
kind: FrameKind,
session_id: u64,
seq: u32,
total_chunks: u32,
payload: &[u8],
) -> String {
) -> Vec<u8> {
assert!(payload.len() <= u16::MAX as usize);
let mut binary = Vec::with_capacity(28 + payload.len());
binary.extend_from_slice(b"QFT1");
binary.extend_from_slice(b"QFT2");
binary.push(VERSION);
binary.push(kind as u8);
binary.extend_from_slice(&session_id.to_be_bytes());
@@ -201,7 +177,7 @@ pub fn encode_frame(
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))
binary
}
pub fn hex_sha256(bytes: &[u8; 32]) -> String {
@@ -236,7 +212,9 @@ fn hash_file_streaming(file: &File) -> Result<[u8; 32]> {
let mut buf = vec![0u8; 4 * 1024 * 1024];
loop {
let n = input.read(&mut buf).context("read input for sha256")?;
if n == 0 { break; }
if n == 0 {
break;
}
hasher.update(&buf[..n]);
}
Ok(hasher.finalize().into())
@@ -245,7 +223,9 @@ fn hash_file_streaming(file: &File) -> Result<[u8; 32]> {
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}"); }
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;
+21 -77
View File
@@ -1,60 +1,22 @@
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> {
/// Active optical renderer. QFT2/Base45 text uses only QR alphanumeric
/// characters, allowing the QR encoder to choose a compact alphanumeric data
/// mode. Exact integer module pixels + full quiet zone maximize camera clarity.
pub fn render_qr_fitted(text: &str, target_side: 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))
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)))
}
/// 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.
/// Pairing QR stays static and uses M error correction for first-scan reliability.
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")?;
@@ -64,38 +26,20 @@ pub fn render_pair_qr(text: &str, target_side: usize) -> Result<ColorImage> {
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;
fn render_code_gray(code: &QrCode, side: usize) -> Vec<u8> {
let qr_width = code.width();
let modules = qr_width + QUIET_MODULES * 2;
let scale = (side / modules).max(1);
let actual_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 {
for y in 0..qr_width {
for x in 0..qr_width {
if code[(x, y)] != Color::Dark { continue; }
let px0 = (x + QUIET_MODULES) * scale;
let py0 = (y + QUIET_MODULES) * scale;
for py in py0..py0 + scale {
let row = py * actual_side;
gray[row + x0..row + x0 + scale].fill(0);
gray[row + px0..row + px0 + scale].fill(0);
}
}
}