# QR Code Transceiver (Optical Air-Gapped Data Transfer)

[English](README.md) | [한국어](README.ko.md)

A lightweight, zero-dependency, browser-based transceiver system for transferring text and binary files across physical air gaps using animated, sequential QR codes ("QR Code Movie").

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Python 3.x](https://img.shields.io/badge/Python-3.x-green.svg)](https://www.python.org/)
[![WebRTC / HTTPS](https://img.shields.io/badge/Browser-WebRTC%20%2F%20HTTPS-orange.svg)]()

---

## 📌 Overview

The **QR Code Transceiver** allows secure data transfer between physically isolated ("air-gapped") devices—such as a computer monitor and a smartphone camera—without requiring Wi-Fi, Bluetooth, cellular, or physical USB connections.

### Key Features
* 📺 **Optical Data Transfer**: Transmits text or binary files as a visual QR code animation stream.
* 📦 **Systematic LT Code Fountain Engine**: Slices payload into $K$ source blocks and uses a two-phase strategy: Phase 1 ($s=1..K$) streams raw source blocks directly for 0-overhead instant decoding, and Phase 2 ($s > K$) generates endless fountain droplets using Mulberry32 PRNG and Robust Soliton distribution for erasure recovery.
* 🛡️ **Level M Error Correction**: Uses Error Correction Level M (15% Reed-Solomon error tolerance) to withstand camera motion blur, lens distortion, and optical reflection.
* 🎯 **Camera-Optimized Optical Density**: Version options (Version 10, 12, 15) capped at $77 \times 77$ modules to maintain legible module pixel width on mobile sensors.
* 🚀 **Offscreen Frame Pre-Rendering Engine**: Pre-calculates QR frames offscreen into an in-memory data URL cache ($N = \max(K \times 2, 60)$), removing runtime canvas generation latency during high-speed playback.
* ⚡ **Raw 8-Bit Binary QR Mode**: Replaces Base64 + JSON encoding with packed binary headers and 8-bit byte QR frames (`MODE_8BIT_BYTE`), eliminating ~40% encoding overhead.
* ⏩ **Speed Presets**: Includes shutter-synchronized presets: **Standard (5 FPS)**, **🚀 High Speed (7 FPS - Mobile Sweet Spot)**, and **⚡ Ultra Speed (10 FPS)**.
* 📷 **High-Speed Camera Scanner**: Utilizes high-framerate camera scanning (up to 60 scans/sec) with real-time QR code outline tracking.
* 🧩 **Real-Time BP Decoder & DOM-Cached Progress**: Uses Belief Propagation (BP) decoding to solve source blocks in real time with cached progress grid elements for maximum scan throughput.
* 📥 **Automatic Binary File Reassembly**: Reconstructs original data buffers (`Uint8Array`) directly and triggers browser file downloads preserving original filenames.
* 🔒 **Local HTTPS Server Included**: Ships with a Python SSL server and self-signed TLS certificates to satisfy browser media security requirements (`navigator.mediaDevices.getUserMedia`).
* ✨ **Gemini AI Integration**: Optional integration to summarize long text input before optical transmission.

---

## 🏗️ System Architecture

```mermaid
flowchart TD
    subgraph Transmitter ["Transmitter (Screen)"]
        A[Text / Binary File Input] --> B[Slice Payload into K Source Blocks]
        B --> C[LT Fountain Encoder: Mulberry32 PRNG + Robust Soliton]
        C --> D[Pack Binary Packet Header & Payload]
        D --> E[Render Raw 8-Bit Byte QR Code Movie Stream]
    end

    subgraph Receiver ["Receiver (Camera)"]
        F[Camera Video Stream] --> G[Real-Time Frame Scanner]
        G --> H[Unpack Binary Packet Header]
        H --> I[Belief Propagation (BP) Fountain Decoder]
        I --> J[Update Visual Progress & Solved Blocks]
        J -->|K Blocks Solved| K[Reassemble Raw Uint8Array Payload]
        K -->|Text| L[Display Text UI]
        K -->|Binary File| M[Trigger File Download]
    end

    Transmitter -- "Optical Air Gap (Display -> Camera)" --> Receiver
```

---

## 🚀 Getting Started

### Prerequisites
* **Python 3.x** installed on the host serving the web interface.
* Modern web browser (Chrome, Firefox, Safari, Edge) with camera permissions enabled on the receiving device.

### Quick Start

1. **Clone the repository**:
   ```bash
   git clone https://github.com/your-username/qrcode_transceiver.git
   cd qrcode_transceiver
   ```

2. **Start the local HTTPS server**:
   ```bash
   python3 server.py 8000
   ```
   *(Note: You can pass a custom port as an optional argument, e.g., `python3 server.py 8080`)*

3. **Open the web applications**:
   * **Transmitter**: Navigate to `https://localhost:8000/transmitter.html` on the sending device.
   * **Receiver**: Navigate to `https://<your-local-ip>:8000/receiver.html` on the receiving device (e.g. mobile device on the same local network, or direct display-to-camera scanning).

---

## 📖 Usage Guide

### Sending Data (Transmitter)

1. Open `transmitter.html`.
2. Input text in the **Text Data** area OR upload a binary file via **Upload a File**.
3. Adjust QR code parameters as needed:
   * **QR Code Size**: Small (128px), Medium (192px), Large (256px), Extra Large (300px), Huge (400px), Max (450px).
   * **QR Code Version**: Auto (Version 10), Version 10 (57x57), Version 12 (65x65), Version 15 (77x77).
4. Click **Generate Movie**. The offscreen frame pre-rendering engine will prepare $N = \max(K \times 2, 60)$ frames into memory.
5. Select a speed preset or adjust the **Speed (FPS)** slider:
   * **Standard (5 FPS)**: Recommended for basic setups / low-end camera sensors (200ms per frame).
   * **🚀 High Speed (7 FPS - Mobile Sweet Spot)**: Optimal balance of shutter speed and optical decode stability for mobile camera sensors (142ms per frame).
   * **⚡ Ultra Speed (10 FPS)**: High-speed optical streaming for high-framerate camera sensors (100ms per frame).
6. *(Optional)* Click **✨ Summarize & Generate** to use Gemini AI to condense text prior to generation.

### Receiving Data (Receiver)

1. Open `receiver.html`.
2. Select your desired camera (Rear or Front) and adjust the **Scan Rate** slider (1–60 scans/sec).
3. Click **Start Camera** and grant camera permissions when prompted.
4. Point the camera at the animated QR code on the transmitter display.
5. The visual progress grid will update as fountain droplets arrive and blocks are solved by the BP decoder.
6. Once $K$ blocks are resolved (100% complete), the payload will be automatically reconstructed and displayed (or downloaded).

---

## ⚡ Throughput & Performance Benchmarks

With Error Correction Level M, camera-optimized module densities (Versions 10–15), raw 8-bit byte QR framing, offscreen frame pre-rendering, and DOM cell element caching, the transceiver achieves reliable optical data rates across physical air gaps:

### Module Density & Payload Capacities (Level M)

| Version | Matrix Size | Module Width (350px display) | Max Raw Packet | Block Size $L$ |
|---|---|---|---|---|
| **Version 1** | $21 \times 21$ | 16.6 px | 12 Bytes | 1 Byte |
| **Version 5** | $37 \times 37$ | 9.4 px | 60 Bytes | 44 Bytes |
| **Version 10** | $57 \times 57$ | 6.1 px | 158 Bytes | 142 Bytes |
| **Version 12** | $65 \times 65$ | 5.3 px | 204 Bytes | 188 Bytes |
| **Version 15** | $77 \times 77$ | 4.5 px | 272 Bytes | 256 Bytes |

### Throughput Benchmarks

| Speed Preset | Framerate (FPS) | QR Version | Packet Capacity / Frame | Throughput Range | Reception Overhead |
|---|---|---|---|---|---|
| **Standard** | 5 FPS | Version 10 – 15 | 158 – 272 bytes | **0.8 – 1.36 KB/sec** | 0% (Phase 1 Systematic) |
| **🚀 High Speed** | 7 FPS *(Mobile Sweet Spot)* | Version 10 – 15 | 158 – 272 bytes | **1.1 – 1.9 KB/sec** | 0% (Phase 1 Systematic) |
| **⚡ Ultra Speed** | 10 FPS | Version 10 – 15 | 158 – 272 bytes | **1.6 – 2.72 KB/sec** | 0% (Phase 1 Systematic) |

*Note: Phase 1 (Seeds $1 \dots K$) delivers 0% reception overhead under clean optical conditions. Phase 2 (Seeds $> K$) provides rateless fountain recovery (~5–10% overhead) in lossy environments with frame drops, lens blur, or motion jitter.*

---

## 📡 Protocol & Packet Format

Data payloads are sliced into $K$ source blocks of length $L$ bytes. Each QR code frame carries a packed binary packet composed of a compact binary header followed by XOR-encoded block payload bytes.

### Binary Header Structure

| Offset (Bytes) | Field | Type | Description |
|---|---|---|---|
| `0..3` | `Seed` | uint32 (Big-Endian) | PRNG seed used by Mulberry32 to sample degree distribution and block indices (Seeds $1..K$ = Systematic direct blocks). |
| `4..5` | `K` | uint16 (Big-Endian) | Total number of source blocks in the payload. |
| `6..7` | `L` | uint16 (Big-Endian) | Payload length per source block in bytes. |
| `8` | `Flags` | uint8 | Flag bits: `0x01` = Is Binary File (`0` = Text, `1` = File), `0x02` = Has Filename Header, `0x04` = Is Systematic Frame ($s \le K$). |
| `9` | `Filename Length` | uint8 (Optional) | Length $N$ of filename UTF-8 string (present when `Flags & 0x02` is set). |
| `10..9+N` | `Filename` | String (Optional) | UTF-8 encoded original filename (present when `Flags & 0x02` is set). |
| `HeaderLen..` | `Payload` | Bytes ($L$ bytes) | XOR sum of sampled source blocks for this fountain droplet (direct block payload for systematic frames). |

---

## 📁 Repository Structure

```
.
├── server.py             # Simple Python HTTPS server with SSL wrapper
├── transmitter.html      # HTML/JS transmitter UI & QR code generator
├── receiver.html         # HTML/JS receiver UI & real-time camera scanner
├── lt_engine.js          # LT Code Fountain engine (PRNG, Soliton distribution, BP Decoder)
├── easy.qrcode.min.js    # Local JS library for dynamic QR code rendering
├── certs/
│   ├── cert.pem          # Self-signed TLS certificate
│   └── key.pem           # TLS private key
└── docs/
    └── adr/              # Architecture Decision Records
```

---

## 📑 Architecture Decision Records (ADRs)

Key technical decisions in this project are documented as ADRs:

* [ADR 0001: Animated QR Code Frame Streaming Protocol & LT Fountain Engine](docs/adr/0001-animated-qr-code-frame-streaming.md)
* [ADR 0002: Packed Binary Header & Raw 8-Bit Byte QR Packet Schema](docs/adr/0002-chunking-and-json-metadata-packet-schema.md)
* [ADR 0003: HTTPS Requirement & Local TLS Certificates for Media Access](docs/adr/0003-https-requirement-and-local-tls-certificates.md)
* [ADR 0004: Real-time Out-of-Order Frame Assembly & Progress Tracking](docs/adr/0004-real-time-out-of-order-frame-assembly.md)

---

## 🔒 Security & Performance Considerations

* **Air-Gap Integrity**: No network sockets or data channels are established between the transmitter and receiver. All data is carried optically across the physical gap.
* **HTTPS Context**: Local self-signed certificates in `./certs/` are required to meet modern web browser security policies regarding camera API access (`navigator.mediaDevices.getUserMedia`).
* **Transmission Speed vs. Reliability**: Capping QR density at Version 15 ($77 \times 77$) and adopting 7 FPS as the mobile sweet spot ensures high shutter capture stability. Error Correction Level M provides 15% fault tolerance against glare, tilt, and optical distortion while streaming data at 1.1–2.7 KB/sec.

---

## 📄 License

This project is licensed under the MIT License.
