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
+89 -71
View File
@@ -3,96 +3,114 @@ import base64, binascii, hashlib, math, os, random, struct
import qrcode
from qrcode.constants import ERROR_CORRECT_L
PREFIX = "QFT1:"
CHUNK = 900
LANES = 4
PREFIX = "QFT2:"
LEGACY_PREFIX = "QFT1:"
CHUNK = 450
DISPLAY_FPS = 60
B45 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"
def enc(kind, sid, seq, total, payload=b""):
def b45encode(data: bytes) -> str:
out=[]
i=0
while i+1 < len(data):
v=data[i]*256+data[i+1]
out += [B45[v%45], B45[(v//45)%45], B45[v//2025]]
i += 2
if i < len(data):
v=data[i]
out += [B45[v%45], B45[v//45]]
return ''.join(out)
def b45decode(text: str) -> bytes:
rev={c:i for i,c in enumerate(B45)}
out=bytearray(); i=0
while i < len(text):
rem=len(text)-i
if rem == 1: raise ValueError('bad Base45 length')
if rem >= 3:
v=rev[text[i]] + 45*rev[text[i+1]] + 2025*rev[text[i+2]]
if v > 0xffff: raise ValueError('overflow')
out += bytes((v//256, v%256)); i += 3
else:
v=rev[text[i]] + 45*rev[text[i+1]]
if v > 0xff: raise ValueError('overflow')
out.append(v); i += 2
return bytes(out)
def enc_binary(kind, sid, seq, total, payload=b""):
body = b"QFT2" + bytes([2, kind]) + struct.pack(">QIIH", sid, seq, total, len(payload)) + payload
crc = binascii.crc32(body) & 0xFFFFFFFF
return body + struct.pack(">I", crc)
def enc_text(kind, sid, seq, total, payload=b""):
return PREFIX + b45encode(enc_binary(kind, sid, seq, total, payload))
def legacy_text(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("=")
raw=body+struct.pack(">I",crc)
return LEGACY_PREFIX + base64.urlsafe_b64encode(raw).decode().rstrip('=')
def dec(text):
def dec_text(text):
assert text.startswith(PREFIX)
b64 = text[len(PREFIX):]
raw = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4))
raw=b45decode(text[len(PREFIX):])
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
assert body[:4] == b"QFT2" and body[4] == 2
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 qr_info(sample: str):
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
return qr.version, 1024//modules_with_quiet, modules_with_quiet
def main():
assert b45encode(b"AB") == "BB8" and b45decode("BB8") == b"AB"
assert b45encode(b"Hello!!") == "%69 VD92EX0" and b45decode("%69 VD92EX0") == b"Hello!!"
assert b45encode(b"base-45") == "UJCLQE7W581" and b45decode("UJCLQE7W581") == b"base-45"
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)]
data=os.urandom(1_200_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_text(1,sid,0,total,manifest)]
playlist += [enc_text(2,sid,i,total,data[i*CHUNK:(i+1)*CHUNK]) for i in range(total)]
playlist += [enc_text(3,sid,0,total)]
version, module_px, chars = test_qr_density(playlist[min(2, len(playlist)-1)])
sample=playlist[min(2,len(playlist)-1)]
version,module_px,modules=qr_info(sample)
legacy=legacy_text(2,sid,0,total,os.urandom(480))
legacy_version,legacy_px,_=qr_info(legacy)
assert version <= 15,(version,len(sample))
assert module_px >= 10,(version,modules,module_px)
assert version < legacy_version,(version,legacy_version)
got = [None] * total
rounds = 0
manifests = 0
# Model both whole-camera-frame losses and per-lane decode failures.
got=[None]*total; rounds=0
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
for text in playlist:
if random.random() < 0.22: continue
kind,rsid,seq,rtotal,payload=dec_text(text)
assert rsid==sid and rtotal==total
if kind==2 and got[seq] is None: got[seq]=payload
assert rounds < 60
rebuilt=b''.join(got)[:len(data)]
assert rebuilt==data and hashlib.sha256(rebuilt).digest()==digest
rate=CHUNK*DISPLAY_FPS
print(f"PASS QFT2/Base45 single-QR: {len(data)} bytes, {total} chunks, 22% frame loss, recovered in {rounds} rounds; QR-L v{version} vs legacy Base64 v{legacy_version}, {module_px}px/module@1024, text={len(sample)} chars, theoretical payload={rate/1024:.1f} KiB/s")
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()
if __name__=='__main__': main()