# ADR 0002: Packed Binary Header & Raw 8-Bit Byte QR Packet Schema

* **Status**: Accepted (Updated)
* **Date**: 2026-08-07
* **Deciders**: Core Development Team

---

## Context

When streaming Fountain Code droplets over optical QR frames, the receiver requires metadata per frame to sample the PRNG seed, identify total source block count $K$, determine block payload length $L$, distinguish text vs binary files, and reconstruct original filenames.

Encoding binary payloads into Base64 strings introduces a ~33% data expansion overhead, while JSON container formatting adds ~30–60 bytes of text syntax per frame. To maximize optical data throughput, packets must use compact binary headers and raw 8-bit byte QR code encoding (`MODE_8BIT_BYTE`).

---

## Decision

We decided to replace Base64 JSON chunk headers with a **Packed Binary Header & Raw 8-Bit Byte QR Packet Schema**.

### Packet Layout

| Offset (Bytes) | Field | Type | Description |
|---|---|---|---|
| `0..3` | `Seed` | uint32 (Big-Endian) | PRNG seed used by Mulberry32 to sample degree distribution and block indices. |
| `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. |
| `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. |

### Key Contract Details
1. **Packed Binary Header**: Fixed 9-byte binary header layout (or $9 + 1 + N$ bytes when filename is present) packed using DataView/Uint8Array byte views in Big-Endian order.
2. **Raw 8-Bit Binary QR Encoding**: Packet Uint8Array binary buffers are serialized directly to 8-bit byte strings (`MODE_8BIT_BYTE`), eliminating Base64 string encoding.
3. **Optimized Capacity**: Maximize net data payload per frame without JSON syntax or Base64 character expansion.

---

## Consequences

### Positive
* **Zero Base64 Expansion**: Binary data is transmitted directly as raw bytes, saving ~33% payload expansion.
* **Minimal Header Overhead**: Compact 9-byte fixed binary header replaces 30–60 byte JSON syntax overhead.
* **Deterministic File Reconstruction**: Filenames, binary file flags, and block sizes are preserved across optical streaming.

### Negative
* **Bitwise & DataView Parsing**: Frame encoding and decoding require explicit byte manipulation (`DataView.setUint32`, bitwise flag masks) instead of native `JSON.parse` / `JSON.stringify`.
