ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4

C2, the hierarchy (tools/move.py, every reference rewritten mechanically):
- codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder;
  codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample
  VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url;
  codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err
  Crc32 Adler32 Base64 Md5 Input Sniff.
- LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md).
- Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes.

C3, generic code out of format folders:
- containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first,
  trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64
  through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it.
- codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position,
  priming and end trimming) that aac, caf and m4a each carried (~70 lines each).
- codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of
  its own (the AND mask / alpha rule stay ICO's).
- codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model),
  Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is
  Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the
  fixtures' bind shapes).
- README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes:
  FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the
  shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks
  decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type
  baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 12:25:03 -05:00
1 parent 9c553b9d1a
commit 434a304315
283 files changed
+1877 -1660

No files matched your search

+68 -15
View File
@@ -1,7 +1,8 @@
# formats-luau style guide
Every format looks the same: one folder, one contract, one test, one fixture generator. `bash tools/lint.sh` enforces
most of what follows (the rule names in CAPITALS are lint rules, implemented in `tools/lint_rules.py`).
Every format looks the same: one folder, one contract, one test, one fixture generator, and the folder holds only what
is specific to the format (section 2a). `bash tools/lint.sh` enforces most of what follows (the rule names in
CAPITALS are lint rules, implemented in `tools/lint_rules.py`).
The reference implementation to copy is **PNG**:
@@ -11,27 +12,36 @@ The reference implementation to copy is **PNG**:
| Private hot submodules (`--!native`) | `src/Formats/image/png/Decode.luau`, `src/Formats/image/png/Encode.luau` |
| Test | `tests/image/png.luau` |
| Fixture generator | `tools/fixtures/png.py` (a reference tool through nix: `tools/fixtures/_png_reference.py`) |
| A codec (layer 1) | `src/Formats/codecs/Deflate/` + `tests/codecs/deflate.luau` + `tools/fixtures/deflate.py` |
| A codec (layer 3) | `src/Formats/codecs/compress/Deflate/` + `tests/codecs/deflate.luau` + `tools/fixtures/deflate.py` |
## 1. Layout and layers
```
src/Formats/
init.luau Registry.luau (generated) api (layer 6)
ops/ ops (layer 5.5) editing on the standard types
ops/ ops (layer 5.5) editing on the standard types (F.ops.image /
mesh / layers / audio; ImageOps, MeshOps, ...)
<category>/<fmt>/ formats (layer 5) image audio video model cad font archive data
vector layered subtitle music playlist
containers/ containers (layer 4) Riff, IsoBmff, Ebml, Ogg, Zip, Tar, ...
codecs/ codecs (layer 3) Deflate, Lzw, Dct, Huffman-heavy algorithms
containers/ containers (layer 4) Chunks, Riff, IsoBmff, Ebml, Ogg, Zip, Tar, ...
codecs/<domain>/<Name> codecs (layer 3) generic algorithms, by domain:
compress/ Deflate Lzma Zstd Brotli Bzip2 Lzw entropy/ Huffman RangeCoder
image/ Jpeg Dct Vp8 Vp8L Pixels Yuv Quantize Raster Blend
audio/ Pcm Stream Resample Mdct Aac Alac VorbisComment Tracker SoundFont
video/ H264 Mpeg1 Video (the video codec registry) text/ Json Xml Text Url
font/ TrueType Cff model/ Mat4 MeshFlatten
host/ host (layer 2) runtime adapters; only the api uses them
Types.luau types (layer 1) standard types + constructors
core/ core (layer 0) Bytes, Bits, Err, Crc32, Adler32, Huffman, Input
core/ core (layer 0) Bytes, Bits, Err, Crc32, Adler32, Base64, Md5,
Input, Sniff (runtime-neutral primitives)
```
LAYERS: a module requires only what is below it. core requires core; Types requires core; codecs require core, Types
and other codecs; containers add codecs; a format may require core, Types, codecs, containers and **its own folder**,
never another format (shared code moves down to `codecs/` or `containers/`: WebP lossy and WebM both use `codecs/Vp8`).
Nothing but the api requires `host/`: formats are pure functions of bytes.
never another format (shared code moves down to `codecs/` or `containers/`: WebP lossy and WebM both use `codecs/image/Vp8`).
Nothing but the api requires `host/`: formats are pure functions of bytes. A codec lives in a domain folder
(`codecs/<compress|entropy|image|audio|video|text|font|model>/<Name>`); `containers/` and `core/` are flat. Moving a
module: `python3 -I tools/move.py old/Path=new/Path` rewrites every reference (requires, deps, headers, docs).
REQUIRE: every require is a string literal `require("@formats/<path>")` (tests and tools may also use
`require("@tests/<path>")`). No `script.X`, no `@self`, no relative paths, no computed requires: `tools/build.py` turns
@@ -119,6 +129,18 @@ Rules:
- Extra format-specific functions (`Png.info(r)`) are fine; `F.format("png")` returns the module.
- No globals, no state between calls, no host access (no files, no `game`).
### Conventions shared by every format
- Images: `rgba8` unless `opts.native`; `img.loops` is the play count (0 = forever: GIF stores repeats, APNG / WebP
play counts); animation frames per `Types.Frame`.
- Audio: interleaved f32 in **WAVE channel order** (FL FR C LFE BL BR SL SR; Vorbis / Opus streams are reordered with
`Pcm.WAVE_FROM_VORBIS`); `tags` keys are **lower case** (title, artist, album, albumartist, date, genre, track,
disc, comment, ...: `codecs/audio/VorbisComment` for Vorbis / Opus / FLAC); raw fields go in `meta.source`.
- Hooks: a format never requires another format. For embedded data in another format the api passes
`opts.decodeImage(buf)`, `opts.encodeImage(img, format)`, `opts.openAudio(demuxer, track)` (audio tracks of video
containers, through `containers/AudioWrap`), `opts.plugins` (injected optional dependencies such as the B-rep
kernel) and `opts.resolve(uri)` (sibling files); without them the embedded part is `Err.UNSUPPORTED`. Video codecs
register in `codecs/video/Video` (fourcc / Matroska id -> decoder) so every container finds them.
### Errors (Err)
Nothing throws on bad data or bad arguments. Every failure is `return nil, Err.new(code, message, offset?)`:
@@ -134,7 +156,9 @@ Nothing throws on bad data or bad arguments. Every failure is `return nil, Err.n
Messages are lower case, without the format name (the api adds it: `png: CORRUPT at 0x21: bad filter type 7`).
The `Bytes` reader's errors are sticky: read a run of fields, then check `if r.err then return nil, r.err end` once.
Private submodules may return `false, "message"` or `nil, "message"`; `init.luau` turns that into an `Err`.
Private submodules may return `false, "message"` or `nil, "message"[, kind]`; `init.luau` turns that into an `Err`
with `Err.from(message, offset?, kind?)` (kind = "truncated" / "limit" / ...; without it a `"limit: "` /
`"unsupported: "` prefix or "truncated" / "past the end" in the message picks the code, else CORRUPT).
### Native code (NATIVE)
A Luau error unwinding through a native frame crashes Roblox Studio, even inside `pcall`. So:
@@ -150,12 +174,38 @@ A Luau error unwinding through a native frame crashes Roblox Studio, even inside
- Bits / Bytes readers are for headers; inner loops read the buffer directly.
- LuaJIT runs the same code through `compat/luajit.lua` (FFI `buffer`, unsigned `bit32`). It is fastest with
straight-line code in the hottest loop: a tiny inner loop (`for k = 0, len - 1 do ... end` inside the symbol loop)
splits LuaJIT's traces; codecs/Deflate/Inflate copies short matches with four `readu32` / `writeu32` instead.
splits LuaJIT's traces; codecs/compress/Deflate/Inflate copies short matches with four `readu32` / `writeu32` instead.
- Benchmark with `bash tools/bench.sh` pinned to one core (`taskset -c 2 bash tools/bench.sh`): on hybrid CPUs (this
machine: Zen 5 + Zen 5c) the same run differs 2x between core types.
- Avoid `string.pack` / `string.unpack` (not in LuaJIT), `\0` inside Lua patterns (LuaJIT: use `%z` or plain find),
and fractional operands to `bit32` (LuaJIT rounds where Luau truncates).
## 2a. What belongs in a format folder
A format folder holds only what is specific to the format: its header / chunk parsing, the mapping to and from the
standard type, its writer, and hot loops nothing else shares. Anything generic goes down a layer and is called:
| Need | Use |
|---|---|
| chunked files (RIFF / IFF / PNG / CAF style: id, size, body, pad, trailer) | `containers/Chunks` (`containers/Riff` for RIFF forms) |
| a decode() that drains open() | `codecs/audio/Pcm.drain(dec, source)` |
| a streaming Decoder over packets (priming, end padding, seek pre-roll) | `codecs/audio/Stream.packets` |
| encoder input (Audio or Decoder), sample formats, channel order | `codecs/audio/Pcm` (`source`, `collect`, `Convert`, `reorder`) |
| other sample rates | `codecs/audio/Resample` |
| Vorbis comments | `codecs/audio/VorbisComment` |
| bitmap rows (indexed bits, BGR / BGRA, 5-5-5, masks, RLE4 / 8, bottom-up) | `codecs/image/Pixels` |
| 4x4 matrices, quaternions, TRS | `codecs/model/Mat4` |
| compression, entropy coding, CRCs, base64 | `codecs/compress/*`, `codecs/entropy/*`, `core/Crc32` (`.msb` too), `core/Base64` |
| bit writing for encoders | `core/Bits` (`msbWriter`, or `Bits.msbPut` on a raw record) |
| argument checking of (buffer \| string, offset, length) | `core/Bytes.span` |
| sniffing text (BOM) / magic | `core/Sniff` |
| private-submodule errors -> Err | `core/Err.from` |
| UTF-8 code points, text decoding | `codecs/text/Text` |
DUP enforces the direction: a function body of 12 or more code lines repeated token for token in another module
fails the lint. When two formats need the same code, move it down (to `codecs/<domain>/` or `containers/`) instead of
copying.
## 3. Tests
`tests/<category>/<fmt>.luau`, run by `bash tools/test.sh [filter]` under `luau --codegen -O2` **and** LuaJIT. Template:
@@ -193,14 +243,17 @@ t:done()
their licence in `licenses/`). Prefer generating over committing. Keep fixture modules under ~15 MB.
- Both runtimes read the same `require("@tests/gen/<name>")`; there is no second mechanism.
- A fuzz pass is mandatory for every decoder (CONTRACT checks `:fuzz(`).
- Types: `luau-analyze` diagnostics are counted by the lint (TYPES) and may not rise above
`tools/lint_types_baseline.txt`; new code should add none (`LINT_TYPES=1 bash tools/lint.sh` lists them, and
`LINT_TYPES_UPDATE=1` lowers the baseline after a cleanup).
## 4. Adding a format
1. `src/Formats/<category>/<fmt>/init.luau` from the template above (copy `image/png/init.luau`), private submodules
next to it. Use `core/Bytes` for parsing, `core/Bits` / `core/Huffman` for entropy coding, `Types` constructors for
the result.
2. Shared code (a codec two formats need, a container) goes to `codecs/` or `containers/` instead, with its own test in
`tests/codecs/` / `tests/containers/`.
next to it. Use `core/Bytes` for parsing, `core/Bits` / `codecs/entropy/Huffman` for entropy coding, the shared
modules of section 2a for everything generic, `Types` constructors for the result.
2. Shared code (a codec two formats need, a container) goes to `codecs/<domain>/` or `containers/` instead, with its
own test in `tests/codecs/` / `tests/containers/`.
3. `deps = { ... }` = the requires outside the folder.
4. `python3 -I tools/gen_registry.py` (regenerates `src/Formats/Registry.luau` and `docs/FORMATS.md`; never edit those
by hand; after a merge, just rerun it).