#!/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()