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.
This commit is contained in:
4DBug committed 2026-10-31 12:25:03 -05:00
1 parent 763f4a7c04
commit 51b08575c4
283 files changed
+1877 -1660

No files matched your search

+111 -41
View File
@@ -3,73 +3,143 @@
Read, write and convert file formats in pure Luau, from one source tree that runs on **Roblox** (Luau, native code
generation) and on **LuaJIT / LÖVE** (through `tools/build.py`). Every format of a category maps onto one standard type
(`src/Formats/Types.luau`): a PNG and a WebP both load as an `Image`, every audio format opens as the same streaming
`Decoder`.
`Decoder`, every model format loads as a `Scene`.
Status: foundation. Formats so far: PNG (read / write). Codecs: DEFLATE (inflate + compressor, zlib, gzip). See
[docs/FORMATS.md](docs/FORMATS.md) (generated) for the capability matrix.
About 76 formats across images, audio, video, 3D models, CAD, fonts, archives, data, vector graphics, layered images,
subtitles, music and playlists: see [docs/FORMATS.md](docs/FORMATS.md) (generated from the code) for the list and each
format's capabilities, and [docs/API.md](docs/API.md) for the whole API.
```luau
local F = require(Formats) -- LuaJIT: require("formats"); luau CLI: require("@formats")
local img, err = F.load(src) -- src: buffer | string | path (hosts with files)
if not img then print(tostring(err)) end -- errors are values: "png: CORRUPT at 0x21: bad filter type 7"
local buf = F.save(img, nil, { format = "png" }) -- a buffer; F.save(img, "out.png") writes a file
local s = F.saveString(img, { format = "png" })
local F = require(Formats) -- LuaJIT: require("formats"); luau CLI: require("@formats")
local img, err = F.load(src) -- src: buffer | string | path (hosts with files)
if not img then print(tostring(err)) end -- errors are values: "png: CORRUPT at 0x21: bad filter type 7"
local buf = F.save(img, nil, { format = "webp" }) -- a buffer; F.save(img, "out.webp") writes a file
local out = F.convert(src, "png", { level = 9 })
local img2 = F.image.load(src) -- category facades: F.image / audio / video / model / font / ...
for _, f in F.formats() do print(f.name, f.caps.decode, f.caps.encode) end
local small = F.ops.image.resize(img, 64, 64, "lanczos")
```
Nothing throws on bad data or bad arguments: every call returns `nil, err` (`err.code` is one of the `F.Err` codes).
## Runtimes
## Install
| Runtime | How | Files |
**Roblox (Rojo).** `python3 -I tools/build.py roblox` writes `build/roblox/Formats` (requires turned into instance
paths); `default.project.json` mounts it, so `rojo build -o Formats.rbxm` (or `rojo serve`) gives a `Formats`
ModuleScript to put in ReplicatedStorage: `local F = require(game.ReplicatedStorage.Formats)`. There is no file system:
pass buffers or strings. `F.host.toEditableImage(img)` makes an EditableImage.
**LuaJIT / LÖVE.** `python3 -I tools/build.py luajit` writes `build/luajit/formats/` (Lua 5.1 + LuaJIT FFI; the Luau
standard library pieces come from `formats/_compat.lua`). Copy the `formats` folder into the game (or put
`build/luajit/?.lua;build/luajit/?/init.lua` on `package.path`) and `local F = require("formats")`. Files load by path
(`love.filesystem` under LÖVE, else `io.open`); `F.host.toImageData(img)`, `F.host.fromImageData(imageData)` and
`F.host.toSoundData(audioOrDecoder)` bridge to LÖVE. `examples/love` is a runnable example and smoke test
(`love examples/love` from the repo root after building).
**luau CLI.** `luau` with the `.luaurc` alias `@formats` runs `src/` directly (no file system).
## Quick start
```luau
-- images: PNG / APNG, JPEG, WebP, GIF, BMP, TGA, QOI, TIFF, ICO, PNM, HDR -> Image (rgba8 pixels in a buffer)
local img = F.image.load(pngBytes)
print(img.width, img.height, #(img.frames or {}), img.loops) -- animations: frames; loops = play count, 0 forever
local jpg = F.save(img, nil, { format = "jpeg", quality = 85 })
-- audio: WAV, FLAC, MP3 / MP2, Ogg Vorbis, Opus, AAC, M4A, AIFF, AU, CAF, VOC -> streaming Decoder or Audio
local dec = F.audio.open(flacBytes) -- dec:read(n) -> interleaved f32 buffer, frames; dec:seek(s)
local song = F.audio.load(mp3Bytes) -- Audio { sampleRate, channels, frames, samples, tags }
local mono = F.ops.audio.downmix(song, 1) -- channels are in WAVE order; tags keys are lower case
local opus = F.save(F.ops.audio.resample(mono, 48000), nil, { format = "opus", bitrate = 64000 })
-- video: MP4 / MOV, MKV / WebM, AVI, MPEG-TS / PS, Y4M (+ animated images) -> VideoDecoder
local v = F.video.open(mp4Bytes) -- v:nextFrame() -> frame (image yuv420p or rgba8, pts)
-- models: glTF / GLB, OBJ, STL, PLY, FBX, Collada, 3MF, USDA, OFF, VOX -> Scene
local scene = F.model.load(glbBytes)
local prim = F.ops.mesh.merge(scene) -- one triangle primitive in world space
-- fonts, archives, data, vector, layered, subtitles, music, playlists
local font = F.font.load(ttfBytes) -- outlines, metrics, kerning
local zip = F.archive.load(zipBytes) -- entries; F.archive.save writes zip / tar / gzip
local t = F.data.load('{"a": [1, 2]}', { format = "json" }) -- JSON, XML, YAML, TOML, CSV, INI, plist, msgpack, CBOR
local icon = F.ops.vector.rasterize(F.vector.load(svgText), 64, 64)
local flat = F.ops.layers.flatten(F.layered.load(psdBytes))
local subs = F.subtitle.load(srtText)
local tune = F.music.load(modBytes) -- MOD / S3M / XM / IT / MIDI, rendered to audio on request
```
## The API in short
`F.load`, `F.open`, `F.save`, `F.saveString`, `F.convert`, `F.detect`, `F.formats`, `F.format(name)`; the category
facades `F.image`, `F.audio`, `F.video`, `F.model`, `F.cad`, `F.font`, `F.archive`, `F.data`, `F.vector`,
`F.layered`, `F.subtitle`, `F.music`, `F.playlist`; editing in `F.ops.image`, `F.ops.mesh`, `F.ops.layers`,
`F.ops.audio`, `F.ops.vector.rasterize`; `F.host`, `F.plugins`, `F.Err`, `F.Types`. Options and the hooks the api
hands to formats (decodeImage / encodeImage / openAudio / plugins): [docs/API.md](docs/API.md).
## Host notes
| Host | Files | Bridges |
|---|---|---|
| Roblox | `python3 -I tools/build.py roblox`, then `rojo build` / `rojo serve` (`default.project.json` mounts `build/roblox/Formats`) | none: pass buffers / strings; `F.host.toEditableImage(img)` |
| LuaJIT | `python3 -I tools/build.py luajit`; `package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path` | `io.open` |
| LÖVE | the LuaJIT build, copied into the game | `love.filesystem` (+ `io`); `F.host.toImageData(img)`, `F.host.fromImageData(id)`, `F.host.toSoundData(audio or decoder)` |
| luau CLI | `luau` with the `.luaurc` alias `@formats` (`src/` directly) | none |
| Roblox | none: pass buffers / strings | `F.host.toEditableImage(img)` |
| LÖVE | `love.filesystem`, then `io` | `toImageData`, `fromImageData`, `toSoundData` |
| LuaJIT | `io.open` | |
| luau CLI | none | |
The LuaJIT build supplies the Luau standard library pieces it needs from `compat/luajit.lua` (unsigned `bit32`,
`buffer` on FFI memory, `table.create`, `math.clamp`, `string.split`, `utf8`, ...), required by each module, without
touching globals (`require("formats._compat").install()` puts `buffer` / `bit32` / `utf8` / `typeof` in `_G` if a
game wants them).
- **Paths.** A string is read as a path only on hosts with files, when it looks like one (short, no NUL / newline)
and the file exists, or when `opts.path = true`; `opts.data = true` forces bytes. Files next to a loaded model
(OBJ `.mtl`, glTF `.bin` and textures) are found through `opts.resolve`, which the api fills in for paths.
- **LuaJIT trace tuning.** On load the host raises LuaJIT's trace limits (`jit.opt.start("maxtrace=8000",
"maxmcode=65536")`): the big decoders (Opus CELT, VP8, H.264, MPEG-1) outgrow the defaults and fall back to the
interpreter (2x or more slower). Set `_G.FORMATS_NO_JIT_TUNE = true` before requiring the library to leave the
JIT settings alone.
## Layout
```
src/Formats/
init.luau Registry.luau (generated) api: F.*
ops/ editing on the standard types (ImageOps, MeshOps, LayerOps, AudioOps)
<category>/<fmt>/ formats: only what is specific to the format (parsing, mapping, writing)
containers/ Chunks, Riff, IsoBmff, Ebml, Ogg, Zip, Tar, Avi, MpegTs, MpegPs, ...
codecs/compress/ Deflate, Lzma, Zstd, Brotli, Bzip2, Lzw
codecs/entropy/ Huffman, RangeCoder
codecs/image/ Jpeg, Dct, Vp8, Vp8L, Pixels, Yuv, Quantize, Raster, Blend
codecs/audio/ Pcm, Stream, Resample, Mdct, Aac, Alac, VorbisComment, Tracker, SoundFont
codecs/video/ H264, Mpeg1, Video (the codec registry)
codecs/text/ codecs/font/ codecs/model/ Json, Xml, Text, Url / TrueType, Cff / Mat4, MeshFlatten
host/ runtime adapters (only the api uses them)
Types.luau the standard types + constructors
core/ Bytes, Bits, Err, Crc32, Adler32, Base64, Md5, Input, Sniff
compat/luajit.lua tools/ tests/ (T.luau, <category>/<fmt>.luau, codecs/, containers/, gen/) docs/ licenses/
examples/love/
```
How the layers fit, the format contract, and what belongs in a format folder: [docs/STYLE.md](docs/STYLE.md).
## Development
```sh
bash tools/test.sh # fixtures, registry, build, every test under luau --codegen -O2 and LuaJIT, lint
bash tools/test.sh png # one test (both runtimes), no lint
bash tools/lint.sh # globals, headers, requires, native-throw, layers, deps, contract, registry
bash tools/lint.sh # globals, type baseline, headers, requires, native-throw, layers, deps, contract, DUP
bash tools/bench.sh # throughput on both runtimes (pin it: taskset -c 2 bash tools/bench.sh)
python3 -I tools/build.py # build/roblox + build/luajit
python3 -I tools/gen_registry.py # src/Formats/Registry.luau + docs/FORMATS.md from the format folders
python3 -I tools/fixtures.py # tests/gen/*.luau from tools/fixtures/*.py
python3 -I tools/fixtures.py # tests/gen/*.luau from tools/fixtures/*.py (reference tools through nix)
python3 -I tools/move.py codecs/image/Foo=codecs/video/Foo # move a module, rewriting every reference
```
Tools: python3, and through nix: `luau` (+ `luau-analyze`), `luajit`, `darklua` 0.19, `rojo` (each script finds them
on PATH or runs them with `nix shell nixpkgs#<tool>`).
on PATH or runs them with `nix shell nixpkgs#<tool>`); the fixture generators run ffmpeg, ImageMagick, libwebp, flac,
lame, opus-tools, vorbis-tools, assimp, fontTools and others through nix.
Layout, layering, the format contract, how to add a format or absorb a repo: [docs/STYLE.md](docs/STYLE.md).
The type checker's diagnostics may only go down: `tools/lint.sh` fails when their count passes
`tools/lint_types_baseline.txt` (`LINT_TYPES=1` lists them, `LINT_TYPES_UPDATE=1` lowers the baseline).
```
src/Formats/ init.luau (API) Types.luau Registry.luau (generated) core/ host/ codecs/ containers/
<category>/<fmt>/ ops/
compat/luajit.lua tools/ tests/ (T.luau, <category>/<fmt>.luau, fixtures/, gen/) docs/ licenses/
```
## Performance
## Performance (one Zen 5 core, `taskset -c 2 bash tools/bench.sh`)
| | luau --codegen -O2 | LuaJIT 2.1 |
|---|---|---|
| inflate, 6 MB text + binary (exact size) | ~330 MB/s | ~470 MB/s |
| zlib (inflate + Adler-32) | ~170 MB/s | ~280 MB/s |
| CRC-32 | ~310 MB/s | ~520 MB/s |
| PNG decode 1024x768 RGBA | ~52 MB/s | ~30-75 MB/s |
| deflate compress -6 | ~12 MB/s | ~8-20 MB/s |
LuaJIT numbers vary between runs: its trace recorder is randomised, and about one run in ten picks a slower trace
layout for a loop (inflate then runs at ~190 MB/s). Unpinned runs on this hybrid CPU also differ 2x between core types.
`tools/bench.luau` prints throughput per codec on both runtimes; run it pinned to one core
(`taskset -c 2 bash tools/bench.sh`: on hybrid CPUs the core types differ 2x). LuaJIT numbers vary between runs (its
trace recorder is randomised).
## Licence
+2 -2
View File
@@ -38,7 +38,7 @@ one category. Extras:
- `F.video.open(src)` also opens animated images (GIF / APNG / WebP) as videos; `F.video.fromImage(img)`,
`F.video.fromFrames(images, delays?)` (an image sequence: `F.save(F.video.fromFrames(list, 1 / 25), "out.avi")`),
`F.video.codecs` (the codec registry `codecs/Video`).
`F.video.codecs` (the codec registry `codecs/video/Video`).
- `F.model.loadTextures(scene, opts?)`: decodes embedded / referenced textures into `texture.image`.
- `F.cad.toBodies`, `F.cad.fromBodies`, `F.cad.tessellate`: STEP B-rep calls through the injected kernel
(`F.plugins.brep`).
@@ -54,7 +54,7 @@ arguments.
| `F.ops.image` | `ops/ImageOps` | `convert` (pixel formats), `crop`, `resize` (nearest / bilinear / Lanczos-3), `flip`, `rotate90`, `rotate`, `blit`, `composite`, `premultiply` / `unpremultiply`, `getPixel` / `setPixel` / `fill`, `new` / `copy`, animations: `coalesce` (frames on full canvases), `fromFrames`, `frameCount`, `durations` |
| `F.ops.mesh` | `ops/MeshOps` | `triangulate`, `transform`, `computeNormals`, `computeTangents`, `weld` / `unweld`, `bounds`, `merge`, `scale` / `setUnit` / `setUp`, `voxelsToPrimitive`, `meshVoxels` |
| `F.ops.layers` | `ops/LayerOps` | `flatten(layered, { frame })`, `flattenFrames`, `leaves` |
| `F.ops.audio` | `ops/AudioOps` | `toAudio` (an Audio from an Audio or a Decoder), `gain`, `gainDb`, `normalize`, `peak`, `rms`, `mix`, `remix` / `downmix` / `upmix` (WAVE-layout matrices), `resample` (`codecs/Resample`), `trim`, `concat`, `fade` |
| `F.ops.audio` | `ops/AudioOps` | `toAudio` (an Audio from an Audio or a Decoder), `gain`, `gainDb`, `normalize`, `peak`, `rms`, `mix`, `remix` / `downmix` / `upmix` (WAVE-layout matrices), `resample` (`codecs/audio/Resample`), `trim`, `concat`, `fade` |
| `F.ops.vector` | `vector/svg` | `rasterize(vector, w?, h?, opts?)`: any `Vector` to an rgba8 `Image` |
```luau
+46 -34
View File
@@ -83,38 +83,50 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| playlist | pls | .pls | yes | yes | | `tests/playlist/pls.luau` |
| playlist | xspf | .xspf | yes | yes | | `tests/playlist/xspf.luau` |
Codecs (layer 1, shared by formats; not loadable on their own):
Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
- codecs/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable
- codecs/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written
- codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec
- codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
- codecs/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws).
- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
- codecs/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the
- codecs/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG
- codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
- codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
- codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
- codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
- codecs/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks
- codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from
- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
- codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette
- codecs/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt):
- codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
- codecs/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or
- codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by
- codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is
- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
- codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed
- codecs/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL,
- codecs/Video: the video codec registry and the generic VideoDecoder. New in formats-luau.
- codecs/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags.
- codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
- codecs/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1):
- codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ...
- codecs/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or
- codecs/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd
- **audio**
- codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
- codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
- codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
- codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
- codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or
- codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by
- codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part
- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags.
- **compress**
- codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written
- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec
- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
- codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
- codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd
- **entropy**
- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders.
- codecs/entropy/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt):
- **font**
- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
- codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed
- **image**
- codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable
- codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws).
- codecs/image/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG
- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP,
- codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette
- codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
- codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1):
- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or
- **model**
- codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16
- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks
- **text**
- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
- codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is
- codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL,
- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ...
- **video**
- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the
- codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from
- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau.
+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).
+6 -6
View File
@@ -24,10 +24,10 @@ F.convert(gif, "avi") -- animated images become videos (un
| `containers/Demux` | the indexed Demuxer every container builds: per-track cursors, keyframe seek, `count` / `get` / `info` |
| `containers/Ebml`, `Avi`, `IsoBmff`, `MpegTs`, `MpegPs`, `MpegEs` | container structures |
| `containers/AudioWrap` | an audio track as a stream an audio format reads (PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, ...) |
| `codecs/Video` | the codec registry and the generic VideoDecoder (`Video.open(demuxer, opts)`, `Video.fromFrames`) |
| `codecs/Video/Source` | what writers write: copied packets or frames encoded by a registry encoder, PCM from the audio |
| `codecs/Yuv` | yuv420p <-> rgba8 (BT.601 / 709, limited / full range from `image.meta.yuv`), range remap |
| `codecs/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) |
| `codecs/video/Video` | the codec registry and the generic VideoDecoder (`Video.open(demuxer, opts)`, `Video.fromFrames`) |
| `codecs/video/Video/Source` | what writers write: copied packets or frames encoded by a registry encoder, PCM from the audio |
| `codecs/image/Yuv` | yuv420p <-> rgba8 (BT.601 / 709, limited / full range from `image.meta.yuv`), range remap |
| `codecs/image/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) |
| `video/<fmt>` | the formats: demux into `containers/Demux`, `open` = `Video.open(demuxer, opts)`, `encode` via Source |
Audio tracks reach the audio formats through the api hook `opts.openAudio(demuxer, track)` (a format never requires
@@ -36,13 +36,13 @@ another format): `F.video.open` / `F.load` set it; calling a video format's `ope
## Adding a codec (H.264, ...)
The registry is static (Roblox has no dynamic require): add an entry to `BUILTIN` in `src/Formats/codecs/Video/init.luau`
The registry is static (Roblox has no dynamic require): add an entry to `BUILTIN` in `src/Formats/codecs/video/Video/init.luau`
with a `new` constructor that requires the codec lazily, or call `Video.register(entry)` at run time
(`F.video.codecs.register`).
```luau
{ id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", ... }, matroska = { "V_MPEG4/ISO/AVC" },
new = function(track, opts) return require("@formats/codecs/H264").newVideoDecoder(track, opts) end }
new = function(track, opts) return require("@formats/codecs/video/H264").newVideoDecoder(track, opts) end }
```
`new(track, opts)` returns a `Types.VideoCodecDecoder`:
+62 -62
View File
@@ -20,7 +20,7 @@ local list: { Entry } = {
path = "image/bmp",
extensions = { "bmp", "dib" },
mime = { "image/bmp", "image/x-bmp", "image/x-ms-bmp" },
deps = { "core/Err", "core/Bytes", "Types" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" },
caps = { decode = true, encode = true, alpha = true, depths = { 1, 2, 4, 8, 16, 24, 32 }, rle = true },
load = function()
return require("@formats/image/bmp")
@@ -32,7 +32,7 @@ local list: { Entry } = {
path = "image/gif",
extensions = { "gif" },
mime = { "image/gif" },
deps = { "core/Err", "core/Bytes", "codecs/Lzw", "codecs/Quantize", "Types" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Lzw", "codecs/image/Quantize", "Types" },
caps = { decode = true, encode = true, animation = true, alpha = true, palette = true, depths = { 1, 2, 4, 8 } },
load = function()
return require("@formats/image/gif")
@@ -56,7 +56,7 @@ local list: { Entry } = {
path = "image/ico",
extensions = { "ico", "cur" },
mime = { "image/vnd.microsoft.icon", "image/x-icon" },
deps = { "core/Err", "core/Bytes", "Types" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" },
caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } },
load = function()
return require("@formats/image/ico")
@@ -68,7 +68,7 @@ local list: { Entry } = {
path = "image/jpeg",
extensions = { "jpg", "jpeg", "jpe", "jfif" },
mime = { "image/jpeg" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Jpeg" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg" },
caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true },
load = function()
return require("@formats/image/jpeg")
@@ -80,7 +80,7 @@ local list: { Entry } = {
path = "image/png",
extensions = { "png", "apng" },
mime = { "image/png", "image/apng" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "Types", "containers/Chunks" },
caps = { decode = true, encode = true, animation = true, alpha = true, depths = { 1, 2, 4, 8, 16 } },
load = function()
return require("@formats/image/png")
@@ -128,7 +128,7 @@ local list: { Entry } = {
path = "image/tiff",
extensions = { "tif", "tiff" },
mime = { "image/tiff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "codecs/Lzw" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/compress/Lzw" },
caps = { decode = true, encode = true, alpha = true, pages = true, depths = { 1, 2, 4, 8, 16, 32 }, float = true },
load = function()
return require("@formats/image/tiff")
@@ -140,7 +140,7 @@ local list: { Entry } = {
path = "image/webp",
extensions = { "webp" },
mime = { "image/webp" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Vp8", "codecs/Vp8L", "containers/Riff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Vp8", "codecs/image/Vp8L", "containers/Riff" },
caps = { decode = true, encode = true, animation = true, alpha = true, lossy = true, lossless = true, depths = { 8 } },
load = function()
return require("@formats/image/webp")
@@ -152,7 +152,7 @@ local list: { Entry } = {
path = "audio/aac",
extensions = { "aac", "adts" },
mime = { "audio/aac", "audio/aacp", "audio/x-aac" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Pcm", "codecs/audio/Stream" },
caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true },
load = function()
return require("@formats/audio/aac")
@@ -164,7 +164,7 @@ local list: { Entry } = {
path = "audio/aiff",
extensions = { "aiff", "aif", "aifc", "afc" },
mime = { "audio/aiff", "audio/x-aiff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "containers/Chunks" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
load = function()
return require("@formats/audio/aiff")
@@ -176,7 +176,7 @@ local list: { Entry } = {
path = "audio/au",
extensions = { "au", "snd" },
mime = { "audio/basic", "audio/x-au" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
load = function()
return require("@formats/audio/au")
@@ -188,7 +188,7 @@ local list: { Entry } = {
path = "audio/caf",
extensions = { "caf", "caff" },
mime = { "audio/x-caf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" },
caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true },
load = function()
return require("@formats/audio/caf")
@@ -200,7 +200,7 @@ local list: { Entry } = {
path = "audio/flac",
extensions = { "flac", "oga" },
mime = { "audio/flac", "audio/x-flac" },
deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" },
deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/audio/Pcm", "codecs/audio/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true },
load = function()
return require("@formats/audio/flac")
@@ -212,7 +212,7 @@ local list: { Entry } = {
path = "audio/m4a",
extensions = { "m4a", "m4b", "m4r" },
mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream" },
caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true },
load = function()
return require("@formats/audio/m4a")
@@ -224,7 +224,7 @@ local list: { Entry } = {
path = "audio/mp3",
extensions = { "mp3", "mp2", "mp1", "mpga" },
mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/Pcm", "codecs/Resample" },
deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/audio/Pcm", "codecs/audio/Resample" },
caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 },
load = function()
return require("@formats/audio/mp3")
@@ -236,7 +236,7 @@ local list: { Entry } = {
path = "audio/opus",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/RangeCoder/Decoder", "codecs/RangeCoder/Encoder", "codecs/Pcm", "codecs/Resample", "codecs/VorbisComment" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/entropy/RangeCoder/Decoder", "codecs/entropy/RangeCoder/Encoder", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 },
load = function()
return require("@formats/audio/opus")
@@ -248,7 +248,7 @@ local list: { Entry } = {
path = "audio/voc",
extensions = { "voc" },
mime = { "audio/x-voc" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false },
load = function()
return require("@formats/audio/voc")
@@ -260,7 +260,7 @@ local list: { Entry } = {
path = "audio/vorbis",
extensions = { "ogg", "oga" },
mime = { "audio/ogg", "audio/vorbis" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm", "codecs/VorbisComment" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/audio/Pcm", "codecs/audio/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 },
load = function()
return require("@formats/audio/vorbis")
@@ -272,7 +272,7 @@ local list: { Entry } = {
path = "audio/wav",
extensions = { "wav", "wave", "rf64", "bw64" },
mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true },
load = function()
return require("@formats/audio/wav")
@@ -284,7 +284,7 @@ local list: { Entry } = {
path = "video/avi",
extensions = { "avi" },
mime = { "video/x-msvideo", "video/avi" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true },
load = function()
return require("@formats/video/avi")
@@ -296,7 +296,7 @@ local list: { Entry } = {
path = "video/h264",
extensions = { "h264", "264", "avc", "jsv", "26l", "jvt" },
mime = { "video/h264" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source", "codecs/H264" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source", "codecs/video/H264" },
caps = { decode = true, encode = true, streaming = true, video = { "h264" }, depths = { 8 } },
load = function()
return require("@formats/video/h264")
@@ -308,7 +308,7 @@ local list: { Entry } = {
path = "video/mkv",
extensions = { "mkv", "webm", "mka", "mk3d" },
mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/Deflate", "codecs/Video", "codecs/Video/Source" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true },
load = function()
return require("@formats/video/mkv")
@@ -320,7 +320,7 @@ local list: { Entry } = {
path = "video/mp4",
extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" },
mime = { "video/mp4", "video/quicktime", "video/3gpp" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true },
load = function()
return require("@formats/video/mp4")
@@ -332,7 +332,7 @@ local list: { Entry } = {
path = "video/mpegps",
extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" },
mime = { "video/mpeg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/Video" },
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" },
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true },
load = function()
return require("@formats/video/mpegps")
@@ -344,7 +344,7 @@ local list: { Entry } = {
path = "video/mpegts",
extensions = { "ts", "m2ts", "mts", "tsv" },
mime = { "video/mp2t" },
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/Video" },
deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" },
caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true },
load = function()
return require("@formats/video/mpegts")
@@ -356,7 +356,7 @@ local list: { Entry } = {
path = "video/y4m",
extensions = { "y4m" },
mime = { "video/x-yuv4mpeg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" },
caps = { decode = true, encode = true, streaming = true, video = { "rawvideo" }, depths = { 8, 10, 12, 16 } },
load = function()
return require("@formats/video/y4m")
@@ -368,7 +368,7 @@ local list: { Entry } = {
path = "model/3mf",
extensions = { "3mf" },
mime = { "model/3mf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "containers/Zip" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "containers/Zip" },
caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true },
load = function()
return require("@formats/model/3mf")
@@ -380,7 +380,7 @@ local list: { Entry } = {
path = "model/dae",
extensions = { "dae", "zae" },
mime = { "model/vnd.collada+xml", "model/vnd.collada+zip" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "core/Base64", "containers/Zip" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "core/Base64", "containers/Zip", "codecs/model/Mat4" },
caps = { decode = true, encode = true, materials = true, polygons = true, skins = true, morphTargets = true, animation = true, cameras = true, lights = true, zae = true },
load = function()
return require("@formats/model/dae")
@@ -392,7 +392,7 @@ local list: { Entry } = {
path = "model/fbx",
extensions = { "fbx" },
mime = { "application/vnd.autodesk.fbx", "model/fbx" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "core/Base64" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "core/Base64", "codecs/model/Mat4" },
caps = { decode = true, encode = true, binary = true, ascii = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true },
load = function()
return require("@formats/model/fbx")
@@ -404,7 +404,7 @@ local list: { Entry } = {
path = "model/gltf",
extensions = { "gltf", "glb" },
mime = { "model/gltf+json", "model/gltf-binary" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Base64", "core/Sniff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff" },
caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true },
load = function()
return require("@formats/model/gltf")
@@ -428,7 +428,7 @@ local list: { Entry } = {
path = "model/off",
extensions = { "off" },
mime = { "model/off", "text/plain" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" },
caps = { decode = true, encode = true, polygons = true, points = true, colors = true, binary = false },
load = function()
return require("@formats/model/off")
@@ -440,7 +440,7 @@ local list: { Entry } = {
path = "model/ply",
extensions = { "ply" },
mime = { "model/ply", "application/ply" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" },
caps = { decode = true, encode = true, ascii = true, binary = true, polygons = true, points = true, colors = true },
load = function()
return require("@formats/model/ply")
@@ -452,7 +452,7 @@ local list: { Entry } = {
path = "model/stl",
extensions = { "stl" },
mime = { "model/stl", "application/sla" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/MeshFlatten" },
caps = { decode = true, encode = true, ascii = true, binary = true, colors = true, indexed = false },
load = function()
return require("@formats/model/stl")
@@ -464,7 +464,7 @@ local list: { Entry } = {
path = "model/usda",
extensions = { "usda", "usd", "usdz" },
mime = { "model/vnd.usda", "model/vnd.usdz+zip" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/model/Mat4" },
caps = { decode = true, encode = true, materials = true, animation = true, cameras = true, lights = true, polygons = true, vertexColors = true, usdz = "read", usdc = false },
load = function()
return require("@formats/model/usda")
@@ -512,7 +512,7 @@ local list: { Entry } = {
path = "font/ttf",
extensions = { "ttf", "otf", "ttc", "otc" },
mime = { "font/ttf", "font/otf", "font/collection" },
deps = { "core/Err", "core/Bytes", "codecs/TrueType" },
deps = { "core/Err", "core/Bytes", "codecs/font/TrueType" },
caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true },
load = function()
return require("@formats/font/ttf")
@@ -524,7 +524,7 @@ local list: { Entry } = {
path = "font/woff",
extensions = { "woff" },
mime = { "font/woff" },
deps = { "core/Err", "core/Bytes", "codecs/Deflate", "codecs/TrueType" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/font/TrueType" },
caps = { decode = true, encode = false, outlines = { "truetype", "cff" } },
load = function()
return require("@formats/font/woff")
@@ -536,7 +536,7 @@ local list: { Entry } = {
path = "font/woff2",
extensions = { "woff2" },
mime = { "font/woff2" },
deps = { "core/Err", "core/Bytes", "codecs/TrueType", "codecs/Brotli" },
deps = { "core/Err", "core/Bytes", "codecs/font/TrueType", "codecs/compress/Brotli" },
caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, transforms = { "glyf", "loca", "hmtx" } },
load = function()
return require("@formats/font/woff2")
@@ -548,7 +548,7 @@ local list: { Entry } = {
path = "archive/7z",
extensions = { "7z" },
mime = { "application/x-7z-compressed" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/Lzma", "codecs/Deflate", "codecs/Bzip2", "codecs/Zstd", "containers/Archive" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/compress/Lzma", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Zstd", "containers/Archive" },
caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false },
load = function()
return require("@formats/archive/7z")
@@ -560,7 +560,7 @@ local list: { Entry } = {
path = "archive/br",
extensions = { "br" },
mime = { "application/x-brotli" },
deps = { "core/Err", "core/Bytes", "codecs/Brotli", "containers/Archive" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Brotli", "containers/Archive" },
caps = { decode = true, encode = false, stream = true },
load = function()
return require("@formats/archive/br")
@@ -572,7 +572,7 @@ local list: { Entry } = {
path = "archive/bz2",
extensions = { "bz2", "tbz2", "tbz" },
mime = { "application/x-bzip2" },
deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/Bzip2" },
deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Bzip2" },
caps = { decode = true, encode = false, stream = true },
load = function()
return require("@formats/archive/bz2")
@@ -584,7 +584,7 @@ local list: { Entry } = {
path = "archive/gzip",
extensions = { "gz", "tgz", "gzip" },
mime = { "application/gzip" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "containers/Archive", "containers/Tar" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" },
caps = { decode = true, encode = true, stream = true },
load = function()
return require("@formats/archive/gzip")
@@ -608,7 +608,7 @@ local list: { Entry } = {
path = "archive/xz",
extensions = { "xz", "txz", "lzma" },
mime = { "application/x-xz", "application/x-lzma" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Lzma", "containers/Archive" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "containers/Archive" },
caps = { decode = true, encode = false, stream = true, filters = { "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" } },
load = function()
return require("@formats/archive/xz")
@@ -632,7 +632,7 @@ local list: { Entry } = {
path = "archive/zst",
extensions = { "zst", "tzst" },
mime = { "application/zstd" },
deps = { "core/Err", "core/Bytes", "codecs/Zstd", "containers/Archive" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Zstd", "containers/Archive" },
caps = { decode = true, encode = false, stream = true },
load = function()
return require("@formats/archive/zst")
@@ -656,7 +656,7 @@ local list: { Entry } = {
path = "data/csv",
extensions = { "csv", "tsv" },
mime = { "text/csv", "text/tab-separated-values" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Sniff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" },
caps = { decode = true, encode = true, header = true },
load = function()
return require("@formats/data/csv")
@@ -668,7 +668,7 @@ local list: { Entry } = {
path = "data/ini",
extensions = { "ini", "cfg", "conf", "inf", "desktop" },
mime = { "text/plain" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Sniff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Sniff" },
caps = { decode = true, encode = true, ordered = true },
load = function()
return require("@formats/data/ini")
@@ -680,7 +680,7 @@ local list: { Entry } = {
path = "data/json",
extensions = { "json", "jsonl", "ndjson", "geojson" },
mime = { "application/json", "application/x-ndjson" },
deps = { "core/Err", "core/Bytes", "codecs/Json", "core/Sniff" },
deps = { "core/Err", "core/Bytes", "codecs/text/Json", "core/Sniff" },
caps = { decode = true, encode = true, ordered = true, streaming = true },
load = function()
return require("@formats/data/json")
@@ -704,7 +704,7 @@ local list: { Entry } = {
path = "data/plist",
extensions = { "plist" },
mime = { "application/x-plist", "application/x-bplist" },
deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/Xml", "codecs/Json" },
deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/text/Xml", "codecs/text/Json" },
caps = { decode = true, encode = true, binary = "read", ordered = true },
load = function()
return require("@formats/data/plist")
@@ -716,7 +716,7 @@ local list: { Entry } = {
path = "data/toml",
extensions = { "toml" },
mime = { "application/toml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "codecs/Text" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "codecs/text/Text" },
caps = { decode = true, encode = true, ordered = true, dates = true },
load = function()
return require("@formats/data/toml")
@@ -728,7 +728,7 @@ local list: { Entry } = {
path = "data/xml",
extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" },
mime = { "application/xml", "text/xml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "core/Sniff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "core/Sniff" },
caps = { decode = true, encode = true, namespaces = true, streaming = true },
load = function()
return require("@formats/data/xml")
@@ -740,7 +740,7 @@ local list: { Entry } = {
path = "data/yaml",
extensions = { "yaml", "yml" },
mime = { "application/yaml", "application/x-yaml", "text/yaml" },
deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/Text" },
deps = { "core/Err", "core/Bytes", "Types", "core/Base64", "codecs/text/Text" },
caps = { decode = true, encode = true, ordered = true, multiDocument = true, anchors = true },
load = function()
return require("@formats/data/yaml")
@@ -752,7 +752,7 @@ local list: { Entry } = {
path = "vector/svg",
extensions = { "svg" },
mime = { "image/svg+xml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Raster", "codecs/Blend", "core/Sniff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "codecs/image/Raster", "codecs/image/Blend", "core/Sniff" },
caps = { decode = true, encode = true, rasterize = true, text = false },
load = function()
return require("@formats/vector/svg")
@@ -764,7 +764,7 @@ local list: { Entry } = {
path = "vector/tiled",
extensions = { "tmx", "tmj", "tsx", "tsj" },
mime = { "application/x-tiled-tmx", "application/x-tiled-tmj" },
deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/Xml", "codecs/Json", "codecs/Deflate", "core/Sniff" },
deps = { "core/Err", "core/Bytes", "core/Base64", "Types", "codecs/text/Xml", "codecs/text/Json", "codecs/compress/Deflate", "core/Sniff" },
caps = { decode = true, encode = true, tilesets = true, infinite = true },
load = function()
return require("@formats/vector/tiled")
@@ -776,7 +776,7 @@ local list: { Entry } = {
path = "layered/aseprite",
extensions = { "aseprite", "ase" },
mime = { "image/x-aseprite" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate" },
caps = { decode = true, encode = true, layers = true, groups = true, animation = true, depths = { 8, 16, 32 } },
load = function()
return require("@formats/layered/aseprite")
@@ -788,7 +788,7 @@ local list: { Entry } = {
path = "layered/psd",
extensions = { "psd", "psb" },
mime = { "image/vnd.adobe.photoshop" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Blend", "codecs/Deflate" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Blend", "codecs/compress/Deflate" },
caps = { decode = true, encode = true, layers = true, groups = true, depths = { 1, 8, 16, 32 } },
load = function()
return require("@formats/layered/psd")
@@ -836,7 +836,7 @@ local list: { Entry } = {
path = "music/it",
extensions = { "it" },
mime = { "audio/it", "audio/x-it" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" },
caps = { decode = true, encode = false, render = true, channels = { 1, 64 }, compressedSamples = true },
load = function()
return require("@formats/music/it")
@@ -848,7 +848,7 @@ local list: { Entry } = {
path = "music/midi",
extensions = { "mid", "midi", "smf", "kar", "rmi" },
mime = { "audio/midi", "audio/x-midi" },
deps = { "core/Err", "core/Bytes", "codecs/SoundFont", "Types" },
deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont", "Types" },
caps = { decode = true, encode = true, formats = { 0, 1, 2 }, render = true, streaming = true, rmid = true },
load = function()
return require("@formats/music/midi")
@@ -860,7 +860,7 @@ local list: { Entry } = {
path = "music/mod",
extensions = { "mod", "m15", "stk", "nst" },
mime = { "audio/x-mod", "audio/mod" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" },
caps = { decode = true, encode = true, render = true, channels = { 1, 32 } },
load = function()
return require("@formats/music/mod")
@@ -872,7 +872,7 @@ local list: { Entry } = {
path = "music/s3m",
extensions = { "s3m" },
mime = { "audio/s3m", "audio/x-s3m" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" },
caps = { decode = true, encode = false, render = true, channels = { 1, 32 } },
load = function()
return require("@formats/music/s3m")
@@ -884,7 +884,7 @@ local list: { Entry } = {
path = "music/sf2",
extensions = { "sf2" },
mime = { "audio/x-soundfont" },
deps = { "core/Err", "core/Bytes", "codecs/SoundFont" },
deps = { "core/Err", "core/Bytes", "codecs/audio/SoundFont" },
caps = { decode = true, encode = false, sm24 = true, sf3 = false },
load = function()
return require("@formats/music/sf2")
@@ -896,7 +896,7 @@ local list: { Entry } = {
path = "music/xm",
extensions = { "xm" },
mime = { "audio/xm", "audio/x-xm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Tracker" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Tracker" },
caps = { decode = true, encode = true, render = true, channels = { 1, 64 } },
load = function()
return require("@formats/music/xm")
@@ -908,7 +908,7 @@ local list: { Entry } = {
path = "playlist/m3u",
extensions = { "m3u", "m3u8" },
mime = { "audio/x-mpegurl", "audio/mpegurl", "application/vnd.apple.mpegurl", "application/x-mpegurl" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text", "core/Sniff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" },
caps = { decode = true, encode = true, hls = true },
load = function()
return require("@formats/playlist/m3u")
@@ -920,7 +920,7 @@ local list: { Entry } = {
path = "playlist/pls",
extensions = { "pls" },
mime = { "audio/x-scpls", "audio/scpls" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Text", "core/Sniff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Text", "core/Sniff" },
caps = { decode = true, encode = true },
load = function()
return require("@formats/playlist/pls")
@@ -932,7 +932,7 @@ local list: { Entry } = {
path = "playlist/xspf",
extensions = { "xspf" },
mime = { "application/xspf+xml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Url", "codecs/Xml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Url", "codecs/text/Xml" },
caps = { decode = true, encode = true },
load = function()
return require("@formats/playlist/xspf")
+3 -3
View File
@@ -166,7 +166,7 @@ Types.Midi = Midi
-- ------------------------------------------------------------------------------------------------ Video
-- A video file opens (F.video.open / a video format's open) as a VideoDecoder; F.load returns the same object (kind =
-- "video", decoded lazily). Underneath sits a Demuxer: the container's tracks and their packets. Video tracks decode
-- through the codec registry (codecs/Video: by codec id or FourCC, so other codecs can plug in), audio tracks through
-- through the codec registry (codecs/video/Video: by codec id or FourCC, so other codecs can plug in), audio tracks through
-- the audio formats (the api hook opts.openAudio, since a format never requires another format).
--
-- Times: Packet pts / dts / duration are integer ticks of the track's timescale (exact, for remuxing); VideoFrame pts
@@ -242,7 +242,7 @@ export type VideoDecoder = {
demuxer: Demuxer?, -- nil for frames-backed videos (animated images)
meta: { [string]: any },
}
-- a codec's decoder instance (codecs/Video registry entries create them): packets in, pictures out
-- a codec's decoder instance (codecs/video/Video registry entries create them): packets in, pictures out
export type VideoCodecDecoder = {
decode: (self: any, packet: Packet) -> Err?, -- feed one packet (decode order)
receive: (self: any) -> (Image?, number?, boolean?), -- the next picture, the pts (ticks) it carries, keyframe | nil
@@ -997,7 +997,7 @@ end
Types.Vector = Vector
-- ------------------------------------------------------------------------------------------------ Layered (PSD, Aseprite)
-- blend: a codecs/Blend mode name ("normal", "multiply", ...; groups also "passThrough"). Optional: children (a group:
-- blend: a codecs/image/Blend mode name ("normal", "multiply", ...; groups also "passThrough"). Optional: children (a group:
-- its layers bottom to top; its image is 0 x 0), clip (clipped to the alpha of the layer below), mask (a grey mask in
-- canvas coordinates; outside its rectangle the mask is `default`).
export type LayerMask = { image: Image, x: number, y: number, default: number, disabled: boolean? }
+5 -5
View File
@@ -13,10 +13,10 @@ local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Types = require("@formats/Types")
local Lzma = require("@formats/codecs/Lzma")
local Deflate = require("@formats/codecs/Deflate")
local Bzip2 = require("@formats/codecs/Bzip2")
local Zstd = require("@formats/codecs/Zstd")
local Lzma = require("@formats/codecs/compress/Lzma")
local Deflate = require("@formats/codecs/compress/Deflate")
local Bzip2 = require("@formats/codecs/compress/Bzip2")
local Zstd = require("@formats/codecs/compress/Zstd")
local Archive = require("@formats/containers/Archive")
local Header = require("@formats/archive/7z/Header")
@@ -26,7 +26,7 @@ local SevenZip = {
category = "archive",
extensions = { "7z" },
mime = { "application/x-7z-compressed" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/Lzma", "codecs/Deflate", "codecs/Bzip2", "codecs/Zstd", "containers/Archive" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/compress/Lzma", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Zstd", "containers/Archive" },
caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false },
}
+3 -3
View File
@@ -1,6 +1,6 @@
--!strict
-- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (meta.stream: the api unwraps a .tar.br to the tar
-- inside). Decoding through codecs/Brotli. The entry is named after opts.name without ".br" (else "data").
-- inside). Decoding through codecs/compress/Brotli. The entry is named after opts.name without ".br" (else "data").
-- Supports: read (eager decompression). Not supported: write (no Brotli compressor). Brotli has no magic number:
-- sniff accepts only data that decodes cleanly (the whole stream for small files, a 64 KB prefix for big ones), at a
-- low confidence, so the extension decides between candidates.
@@ -8,7 +8,7 @@
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Brotli = require("@formats/codecs/Brotli")
local Brotli = require("@formats/codecs/compress/Brotli")
local Archive = require("@formats/containers/Archive")
-- ------------------------------------------------------------------------------------------------ contract
@@ -17,7 +17,7 @@ local Br = {
category = "archive",
extensions = { "br" },
mime = { "application/x-brotli" },
deps = { "core/Err", "core/Bytes", "codecs/Brotli", "containers/Archive" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Brotli", "containers/Archive" },
caps = { decode = true, encode = false, stream = true },
}
+4 -4
View File
@@ -1,14 +1,14 @@
--!strict
-- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/Bzip2; concatenated
-- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/compress/Bzip2; concatenated
-- streams are joined, as bzip2 -d does). The entry is named after the file without its .bz2 (".tbz2" -> ".tar"),
-- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). New in formats-luau. Not supported:
-- writing (codecs/Bzip2 has no compressor), randomised blocks (bzip2 0.9.0 and older).
-- writing (codecs/compress/Bzip2 has no compressor), randomised blocks (bzip2 0.9.0 and older).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Archive = require("@formats/containers/Archive")
local Bzip2 = require("@formats/codecs/Bzip2")
local Bzip2 = require("@formats/codecs/compress/Bzip2")
-- ------------------------------------------------------------------------------------------------ contract
local Bz2 = {
@@ -16,7 +16,7 @@ local Bz2 = {
category = "archive",
extensions = { "bz2", "tbz2", "tbz" },
mime = { "application/x-bzip2" },
deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/Bzip2" },
deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Bzip2" },
caps = { decode = true, encode = false, stream = true },
}
+3 -3
View File
@@ -3,13 +3,13 @@
-- file name without .gz, else "data"), with the header's MTIME; concatenated members decode as one stream, as gzip -d
-- does. Writing: an Archive with one entry (or a buffer / string) becomes one member with FNAME and MTIME; an Archive
-- with several entries is written as a tar inside the gzip (a .tar.gz). The api unwraps a .tar.gz / .tgz on load (the
-- inner tar, meta.compression = "gzip"). Deflate is codecs/Deflate. Not supported: FHCRC verification.
-- inner tar, meta.compression = "gzip"). Deflate is codecs/compress/Deflate. Not supported: FHCRC verification.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Deflate = require("@formats/codecs/Deflate")
local Deflate = require("@formats/codecs/compress/Deflate")
local Archive = require("@formats/containers/Archive")
local Tar = require("@formats/containers/Tar")
@@ -19,7 +19,7 @@ local Gzip = {
category = "archive",
extensions = { "gz", "tgz", "gzip" },
mime = { "application/gzip" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "containers/Archive", "containers/Tar" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" },
caps = { decode = true, encode = true, stream = true },
}
+3 -3
View File
@@ -1,6 +1,6 @@
--!strict
-- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") files, read as single-stream archives holding one
-- entry (the decompressed data). Built on codecs/Lzma. Supports: concatenated streams, stream padding, every block
-- entry (the decompressed data). Built on codecs/compress/Lzma. Supports: concatenated streams, stream padding, every block
-- layout, checks none / CRC-32 / CRC-64 (verified; SHA-256 is not verified), filters LZMA2, delta and the BCJ filters
-- x86 / PowerPC / ARM / ARM-Thumb / SPARC / ARM64. Not supported: writing, IA-64 / RISC-V filters.
-- The entry is named after the file (opts.name without .xz / .lzma; .txz -> .tar), else "data". meta.stream = true:
@@ -10,7 +10,7 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Lzma = require("@formats/codecs/Lzma")
local Lzma = require("@formats/codecs/compress/Lzma")
local Archive = require("@formats/containers/Archive")
-- ------------------------------------------------------------------------------------------------ contract
@@ -19,7 +19,7 @@ local Xz = {
category = "archive",
extensions = { "xz", "txz", "lzma" },
mime = { "application/x-xz", "application/x-lzma" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Lzma", "containers/Archive" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "containers/Archive" },
caps = { decode = true, encode = false, stream = true, filters = { "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" } },
}
+1 -1
View File
@@ -3,7 +3,7 @@
-- Absorbed from zip-luau 121d4b0 (same author, no third-party code; the reader, now containers/Zip) plus a new
-- writer. Supports: reading stored and deflated entries (CRC-checked), ZIP64, data descriptors, archive comments,
-- prefixed archives (self-extractors), UTF-8 names, case-insensitive / basename lookup; writing stored and deflated
-- entries (codecs/Deflate), unchanged entries copied without recompressing, ZIP64 when needed.
-- entries (codecs/compress/Deflate), unchanged entries copied without recompressing, ZIP64 when needed.
-- Not supported: encryption (traditional PKWARE or AES), compression methods other than store / deflate (bzip2,
-- LZMA, zstd entries are listed but not readable), multi-disk archives.
--
+3 -3
View File
@@ -1,13 +1,13 @@
--!strict
-- archive/zst: a Zstandard-compressed file (.zst, RFC 8878) as a single-stream archive holding one entry, decoded
-- through codecs/Zstd. The entry is named after the file without its extension (opts.name; ".tzst" -> ".tar"), else
-- through codecs/compress/Zstd. The entry is named after the file without its extension (opts.name; ".tzst" -> ".tar"), else
-- "data". The api unwraps it when the entry is itself an archive (.tar.zst loads as the tar). Read-only.
-- Not supported: dictionaries, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Zstd = require("@formats/codecs/Zstd")
local Zstd = require("@formats/codecs/compress/Zstd")
local Archive = require("@formats/containers/Archive")
-- ------------------------------------------------------------------------------------------------ contract
@@ -16,7 +16,7 @@ local Zst = {
category = "archive",
extensions = { "zst", "tzst" },
mime = { "application/zstd" },
deps = { "core/Err", "core/Bytes", "codecs/Zstd", "containers/Archive" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Zstd", "containers/Archive" },
caps = { decode = true, encode = false, stream = true },
}
+22 -76
View File
@@ -1,6 +1,6 @@
--!strict
-- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3), the .aac files encoders and radio streams
-- write. Supports: reading AAC-LC through codecs/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected
-- write. Supports: reading AAC-LC through codecs/audio/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected
-- headers skipped), a leading ID3v2 tag (skipped; its text frames become tags), resync after garbage, seeking (by
-- frame), HE-AAC streams play their AAC-LC core. Not supported: writing (AAC encoding is out of scope), ADIF, LATM.
@@ -8,8 +8,9 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Aac = require("@formats/codecs/Aac")
local Pcm = require("@formats/codecs/audio/Pcm")
local Stream = require("@formats/codecs/audio/Stream")
local Aac = require("@formats/codecs/audio/Aac")
-- ------------------------------------------------------------------------------------------------ contract
local AacFormat = {
@@ -17,7 +18,7 @@ local AacFormat = {
category = "audio",
extensions = { "aac", "adts" },
mime = { "audio/aac", "audio/aacp", "audio/x-aac" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Pcm", "codecs/audio/Stream" },
caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true },
}
@@ -168,11 +169,6 @@ function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?,
local id3 = id3Size(r.buf, r.base, r.limit)
local tags = if id3 > 0 then id3Tags(r.buf, r.base, id3) else {}
local buf = r.buf
local nextFrame = 1
local pendPos, pendN = 0, 0
local drop = 0
local pos = 0
local failed: Err.Err? = nil
local out: any = {
sampleRate = sr,
channels = channels,
@@ -181,74 +177,24 @@ function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?,
bitrate = if total > 0 then math.floor(bytes * 8 * sr / total) else 0,
tags = tags,
codec = "aac",
error = nil,
}
local function fill(): boolean
while true do
if nextFrame > nframes then
return false
end
local i = nextFrame
nextFrame += 1
local n, e = d:decode(buf, offs[i], sizes[i])
if not n then
failed = e
out.error = e
return false
end
if drop >= n then
drop -= n
else
pendPos, pendN = drop, n
drop = 0
return true
end
end
end
function out.read(_self: any, n: number, ob: buffer?): (buffer, number)
local want = math.max(0, math.floor(n))
local need = want * channels * 4
local res = if ob and buffer.len(ob) >= need then ob else buffer.create(need)
local got = 0
local writef32 = buffer.writef32
while got < want do
if pendPos >= pendN then
if failed or not fill() then
break
end
end
local take = math.min(want - got, pendN - pendPos)
local src = d.pcm
local q = got * channels * 4
local s = pendPos * channels
for k = 1, take * channels do
writef32(res, q, src[s + k])
q += 4
end
pendPos += take
got += take
end
pos += got
return res, got
end
function out.seek(_self: any, seconds: number)
local target = math.clamp(math.floor(seconds * sr + 0.5), 0, total)
local f = target // 1024 -- frame holding the target (0-based)
local start = math.max(0, f - 1) -- one frame of pre-roll for the overlap
d:reset()
nextFrame = start + 1
drop = target - start * 1024
pendPos, pendN = 0, 0
failed = nil
pos = target
end
function out.position(_self: any): number
return pos / sr
end
if nframes > 0 and not fill() and failed then
return nil, failed
end
return out, nil
-- 1024 frames per ADTS frame; one frame of pre-roll for the overlap when seeking
return Stream.packets(out, {
count = nframes,
start = function(i: number): number
return (i - 1) * 1024
end,
decode = function(i: number): (number?, Err.Err?)
return d:decode(buf, offs[i], sizes[i])
end,
pcm = function(): { number }
return d.pcm
end,
reset = function()
d:reset()
end,
preroll = 1,
})
end
function AacFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
+9 -9
View File
@@ -10,7 +10,8 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Chunks = require("@formats/containers/Chunks")
local Pcm = require("@formats/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Aiff = {
@@ -18,7 +19,7 @@ local Aiff = {
category = "audio",
extensions = { "aiff", "aif", "aifc", "afc" },
mime = { "audio/aiff", "audio/x-aiff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "containers/Chunks" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
}
@@ -159,12 +160,12 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
local ssnd: number? = nil
local ssndLen = 0
local tags: Types.Tags = {}
local p = base + 12
while p + 8 <= formEnd do
local id = buffer.readstring(b, p, 4)
local len = bit32.byteswap(buffer.readu32(b, p + 4))
local d = p + 8
local avail = math.min(len, limit - d)
-- (walked to the end of the data: a FORM size that undercounts still reads the last chunk's body)
for _, c in Chunks.walk(b, base + 12, limit, Chunks.IFF) do
local id, len, d, avail, p = c.id, c.declared, c.offset, c.avail, c.start
if p + 8 > formEnd then
break
end
if id == "COMM" then
if avail < 18 or (aifc and avail < 22) then
return nil, Err.new(Err.TRUNCATED, "COMM chunk too short", p)
@@ -219,7 +220,6 @@ local function parse(r: Bytes.Reader): (Info?, Err.Err?)
if len > formEnd - d then
break
end
p = d + len + len % 2
end
if not comm or not info then
return nil, Err.new(Err.CORRUPT, "no COMM chunk", base)
+2 -2
View File
@@ -9,7 +9,7 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Pcm = require("@formats/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Au = {
@@ -17,7 +17,7 @@ local Au = {
category = "audio",
extensions = { "au", "snd" },
mime = { "audio/basic", "audio/x-au" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
}
+27 -109
View File
@@ -1,6 +1,6 @@
--!strict
-- audio/caf: Apple Core Audio Format (CAF 1.0, Apple's "Core Audio Format Specification"). Supports reading linear
-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/Alac), AAC-LC (codecs/Aac,
-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/audio/Alac), AAC-LC (codecs/audio/Aac,
-- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown
-- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 /
-- 24-bit) with info tags. Not supported: IMA4, other compressed formats (UNSUPPORTED).
@@ -9,9 +9,11 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Aac = require("@formats/codecs/Aac")
local Alac = require("@formats/codecs/Alac")
local Chunks = require("@formats/containers/Chunks")
local Pcm = require("@formats/codecs/audio/Pcm")
local Stream = require("@formats/codecs/audio/Stream")
local Aac = require("@formats/codecs/audio/Aac")
local Alac = require("@formats/codecs/audio/Alac")
-- ------------------------------------------------------------------------------------------------ contract
local Caf = {
@@ -19,7 +21,7 @@ local Caf = {
category = "audio",
extensions = { "caf", "caff" },
mime = { "audio/x-caf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream", "containers/Chunks" },
caps = { decode = true, encode = true, codecs = { "pcm", "alac", "aac", "ulaw", "alaw" }, encodeCodecs = { "pcm", "alac" }, tags = true, streaming = true },
}
@@ -146,26 +148,15 @@ local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?)
if Caf.sniff(r) == 0 then
return nil, Err.new(Err.CORRUPT, "not a CAF file", r.base)
end
r:seek(8)
local p: Parsed = { desc = nil :: any, dataStart = 0, dataEnd = 0, priming = 0, remainder = 0, tags = {} }
local haveData = false
while r:remaining() >= 12 do
local typ = r:string(4)
local size = r:i64be()
local start = r.pos
if size == -1 and typ == "data" then
size = r.limit - start
end
if size < 0 then
return nil, Err.new(Err.CORRUPT, "bad chunk size", start - 12)
end
local stop = start + size
if stop > r.limit then
if typ ~= "data" then
return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", start - 12)
end
stop = r.limit -- a truncated data chunk: play what is there
-- 64-bit big-endian chunk sizes; the data chunk may say -1 (= to the end) or run past a truncated file
for _, ch in Chunks.walk(r.buf, r.base + 8, r.limit, { bigEndian = true, sizeBytes = 8, openEnded = { data = true } }) do
local typ, start = ch.id, ch.offset
if ch.truncated and typ ~= "data" then
return nil, Err.new(Err.TRUNCATED, "chunk '" .. typ .. "' runs past the end", ch.start)
end
local stop = start + ch.avail
local c = Bytes.reader(r.buf, start, stop - start)
if typ == "desc" then
p.desc = {
@@ -226,7 +217,6 @@ local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?)
p.tags[INFO_TAGS[string.lower(k)] or string.lower(k)] = v
end
end
r.pos = stop
if typ == "data" and stop >= r.limit then
break
end
@@ -456,12 +446,6 @@ function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
stopAt = math.max(skip, total - p.remainder)
end
local frames = math.max(0, stopAt - skip)
local nextPacket = 1
local decoded = 0
local pendPos, pendN = 0, 0
local dropUntil = skip
local pos = 0
local failed: Err.Err? = nil
local dec: any = {
sampleRate = rate,
channels = ch,
@@ -471,87 +455,21 @@ function Caf.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
tags = p.tags,
codec = src.codec,
bitsPerSample = src.bits,
error = nil,
}
local function fill(): boolean
while true do
if nextPacket > src.packetCount or decoded >= stopAt then
return false
end
local i = nextPacket
nextPacket += 1
local start = starts[i]
local n, e = src.decode(i)
if not n then
failed = e
dec.error = e
return false
end
decoded = start + n
local a = math.max(start, dropUntil)
local b = math.min(decoded, stopAt)
if b > a then
pendPos, pendN = a - start, b - start
return true
end
end
end
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
local want = math.max(0, math.floor(n))
local need = want * ch * 4
local ob = if out and buffer.len(out) >= need then out else buffer.create(need)
local got = 0
local writef32 = buffer.writef32
while got < want do
if pendPos >= pendN then
if failed or not fill() then
break
end
end
local take = math.min(want - got, pendN - pendPos)
local q = got * ch * 4
local sidx = pendPos * ch
local pcm = src.pcm
for k = 1, take * ch do
writef32(ob, q, pcm[sidx + k])
q += 4
end
pendPos += take
got += take
end
pos += got
return ob, got
end
function dec.seek(_self: any, seconds: number)
local target = math.clamp(math.floor(seconds * rate + 0.5), 0, frames) + skip
local lo, hi, found = 1, src.packetCount, 1
while lo <= hi do
local mid = (lo + hi) // 2
if starts[mid] <= target then
found = mid
lo = mid + 1
else
hi = mid - 1
end
end
if src.codec == "aac" then
found = math.max(1, found - 1)
end
src.reset()
nextPacket = found
decoded = starts[found]
dropUntil = target
pendPos, pendN = 0, 0
failed = nil
pos = target - skip
end
function dec.position(_self: any): number
return pos / rate
end
if src.packetCount > 0 and frames > 0 and not fill() and failed then
return nil, failed
end
return dec, nil
return Stream.packets(dec, {
count = src.packetCount,
start = function(i: number): number
return starts[i]
end,
decode = src.decode,
pcm = function(): { number }
return src.pcm
end,
reset = src.reset,
skip = skip,
stop = stopAt,
preroll = if src.codec == "aac" then 1 else 0,
})
end
function Caf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Err?)
+2 -2
View File
@@ -8,11 +8,11 @@
-- libFLAC's precision table, the order estimated from the prediction error or searched exhaustively at -8), wasted
-- bits; Rice / Rice2 partitions with the partition order and parameters searched per subframe. Frames carry CRC-8 /
-- CRC-16; STREAMINFO carries the sizes, total samples and the MD5 of the PCM; VORBIS_COMMENT from the tags; an optional
-- SEEKTABLE. Streams: input blocks are pulled from a codecs/Pcm Source, so a Decoder is encoded without decoding it
-- SEEKTABLE. Streams: input blocks are pulled from a codecs/audio/Pcm Source, so a Decoder is encoded without decoding it
-- whole. Never throws: bad options are rejected by audio/flac before calling in.
local Bits = require("@formats/core/Bits")
local Md5 = require("@formats/core/Md5")
local VorbisComment = require("@formats/codecs/VorbisComment")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
local Frame = require("@formats/audio/flac/Frame")
local Encode = {}
+1 -1
View File
@@ -4,7 +4,7 @@
-- audio/flac/Meta: FLAC metadata blocks: STREAMINFO, SEEKTABLE, VORBIS_COMMENT and PICTURE (its fields are listed, the image is
-- left in place); every other block is skipped. Nothing throws: bad data gives nil, err.
-- Absorbed from flac-luau 7083d0d (same author, no third-party code).
local VorbisComment = require("@formats/codecs/VorbisComment")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
local readu8, readu32 = buffer.readu8, buffer.readu32
+2 -2
View File
@@ -21,7 +21,7 @@ local Types = require("@formats/Types")
local Ogg = require("@formats/containers/Ogg")
local Stream = require("@formats/audio/flac/Stream")
local Encode = require("@formats/audio/flac/Encode")
local Pcm = require("@formats/codecs/Pcm")
local Pcm = require("@formats/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Flac = {
@@ -29,7 +29,7 @@ local Flac = {
category = "audio",
extensions = { "flac", "oga" },
mime = { "audio/flac", "audio/x-flac" },
deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm", "codecs/VorbisComment" },
deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "containers/Ogg", "core/Md5", "codecs/audio/Pcm", "codecs/audio/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true },
}
+24 -105
View File
@@ -1,6 +1,6 @@
--!strict
-- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading
-- AAC-LC (codecs/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/Alac) tracks, gapless
-- AAC-LC (codecs/audio/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/audio/Alac) tracks, gapless
-- trimming through the edit list (encoder priming / padding), seeking, iTunes tags and cover art (dec.pictures);
-- writing ALAC (16 / 20 / 24-bit, 1 - 8 channels) with tags and cover art. Not supported: writing AAC, other codecs
-- inside MP4 (MP3 / Opus / FLAC / AC-3: UNSUPPORTED), encrypted files.
@@ -9,10 +9,11 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Pcm = require("@formats/codecs/audio/Pcm")
local Stream = require("@formats/codecs/audio/Stream")
local IsoBmff = require("@formats/containers/IsoBmff")
local Aac = require("@formats/codecs/Aac")
local Alac = require("@formats/codecs/Alac")
local Aac = require("@formats/codecs/audio/Aac")
local Alac = require("@formats/codecs/audio/Alac")
-- ------------------------------------------------------------------------------------------------ contract
local M4a = {
@@ -20,7 +21,7 @@ local M4a = {
category = "audio",
extensions = { "m4a", "m4b", "m4r" },
mime = { "audio/mp4", "audio/x-m4a", "audio/m4a" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/Aac", "codecs/Alac", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "codecs/audio/Aac", "codecs/audio/Alac", "codecs/audio/Pcm", "codecs/audio/Stream" },
caps = { decode = true, encode = true, codecs = { "aac", "alac" }, encodeCodecs = { "alac" }, tags = true, streaming = true },
}
@@ -181,15 +182,6 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
end
local frames = math.max(0, total - skip)
local buf = r.buf
-- streaming state
local nextPacket = 1
local decoded = 0 -- frames produced by the packets decoded so far (before trimming)
local pend, pendPos, pendN = p.pcm, 0, 0 -- the current packet: frames pendPos .. pendN - 1 not yet returned
local dropUntil = skip -- absolute frame index of the first frame to return
local stopAt = total
local pos = 0 -- frames returned
local failed: Err.Err? = nil
local dec: any = {
sampleRate = sr,
channels = channels,
@@ -201,103 +193,30 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
codec = t.codec,
track = t,
movie = movie,
error = nil,
}
local bytes = 0
for i = 1, t.sampleCount do
bytes += t.sizes[i]
end
dec.bitrate = if frames > 0 then math.floor(bytes * 8 * sr / frames) else (t.bitrate or 0)
-- decode the next packet into pend; false at the end / on an error
local function fill(): boolean
while true do
if nextPacket > t.sampleCount or decoded >= stopAt then
return false
end
local i = nextPacket
nextPacket += 1
local start = decoded
local n, e = p.decode(buf, t.offsets[i], t.sizes[i])
if not n then
failed = e
dec.error = e
return false
end
decoded += n
-- the part of this packet inside [dropUntil, stopAt)
local a = math.max(start, dropUntil)
local b = math.min(decoded, stopAt)
if b > a then
pendPos = a - start
pendN = b - start
return true
end
end
end
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
local want = math.max(0, math.floor(n))
local need = want * channels * 4
local ob = if out and buffer.len(out) >= need then out else buffer.create(need)
local got = 0
local writef32 = buffer.writef32
while got < want do
if pendPos >= pendN then
if failed or not fill() then
break
end
end
local take = math.min(want - got, pendN - pendPos)
local src = pend
local o = got * channels * 4
local s = pendPos * channels
for k = 1, take * channels do
writef32(ob, o, src[s + k])
o += 4
end
pendPos += take
got += take
end
pos += got
return ob, got
end
function dec.seek(_self: any, seconds: number)
local target = math.clamp(math.floor(seconds * sr + 0.5), 0, frames) + skip -- absolute frame
-- the last packet starting at or before the target, minus one for the codec's overlap (AAC)
local ticks = target / tickScale
local lo, hi, found = 1, t.sampleCount, 1
while lo <= hi do
local mid = (lo + hi) // 2
if t.dts[mid] <= ticks then
found = mid
lo = mid + 1
else
hi = mid - 1
end
end
local startPacket = if t.codec == "aac" then math.max(1, found - 1) else found
p.reset()
nextPacket = startPacket
decoded = math.floor((t.dts[startPacket] or 0) * tickScale + 0.5)
dropUntil = math.max(target, skip)
pendPos, pendN = 0, 0
failed = nil
pos = target - skip
end
function dec.position(_self: any): number
return pos / sr
end
-- prime: surface a broken first packet as an open error
if t.sampleCount > 0 and frames > 0 then
if not fill() and failed then
return nil, failed
end
end
return dec, nil
-- packet start frames (media ticks -> frames); one AAC packet of pre-roll for the overlap when seeking
return Stream.packets(dec, {
count = t.sampleCount,
start = function(i: number): number
return math.floor((t.dts[i] or (t.dts[t.sampleCount] or 0) + (t.durations[t.sampleCount] or 0)) * tickScale + 0.5)
end,
decode = function(i: number): (number?, Err.Err?)
return p.decode(buf, t.offsets[i], t.sizes[i])
end,
pcm = function(): { number }
return p.pcm
end,
reset = p.reset,
skip = skip,
stop = total,
preroll = if t.codec == "aac" then 1 else 0,
cumulative = true,
})
end
-- decode(r, opts?) -> Types.Audio | nil, Err (the whole stream, tags, cover pictures in meta.pictures)
+7 -7
View File
@@ -6,7 +6,7 @@
-- past garbage, mono / stereo switches (upmixed), ID3v2.2 / 2.3 / 2.4 and ID3v1 / 1.1 tags (APEv2 skipped).
-- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, audio/mp3/Encode3 + Encode2): layer III
-- (shine-style CBR, MPEG-1 / 2 / 2.5) and layer II (MPEG-1 / 2), mono / stereo / joint stereo, an ID3v2.4 tag from
-- the tags; input at rates the layer cannot hold is resampled (codecs/Resample). Not supported: MPEG-2 multichannel
-- the tags; input at rates the layer cannot hold is resampled (codecs/audio/Resample). Not supported: MPEG-2 multichannel
-- extension, CRC checks, VBR / Xing output.
--
-- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay,
@@ -23,8 +23,8 @@ local Tags = require("@formats/audio/mp3/Tags")
local Stream = require("@formats/audio/mp3/Stream")
local Encode3 = require("@formats/audio/mp3/Encode3")
local Encode2 = require("@formats/audio/mp3/Encode2")
local Pcm = require("@formats/codecs/Pcm")
local Resample = require("@formats/codecs/Resample")
local Pcm = require("@formats/codecs/audio/Pcm")
local Resample = require("@formats/codecs/audio/Resample")
-- ------------------------------------------------------------------------------------------------ contract
local Mp3 = {
@@ -32,7 +32,7 @@ local Mp3 = {
category = "audio",
extensions = { "mp3", "mp2", "mp1", "mpga" },
mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/Pcm", "codecs/Resample" },
deps = { "core/Err", "core/Bytes", "core/Bits", "Types", "codecs/audio/Pcm", "codecs/audio/Resample" },
caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 },
}
@@ -48,8 +48,8 @@ export type EncodeOptions = {
-- "mono" for mono input; layer II has no joint stereo (intensity) and writes "joint" as "stereo"
id3: boolean?, -- write an ID3v2.4 tag from the tags (default true when there are tags)
sampleRate: number?, -- output rate (one the layer holds); default the input rate if possible, else the nearest
-- higher one (input at other rates is resampled through codecs/Resample)
resampleQuality: ("low" | "medium" | "high")?, -- codecs/Resample quality (default "medium")
-- higher one (input at other rates is resampled through codecs/audio/Resample)
resampleQuality: ("low" | "medium" | "high")?, -- codecs/audio/Resample quality (default "medium")
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -173,7 +173,7 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
local Enc = if layer == 3 then Encode3 else Encode2
-- the output rate: opts.sampleRate, else the input's when the layer has it, else the nearest rate above it (else
-- the highest); other input rates go through codecs/Resample
-- the highest); other input rates go through codecs/audio/Resample
local rate = o.sampleRate or src.sampleRate
if o.sampleRate and not Enc.RATES[o.sampleRate] then
return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz", layer, tostring(o.sampleRate)))
+1 -1
View File
@@ -7,7 +7,7 @@
--
-- Arrays are Luau tables of numbers. All normalised-band data (X, Y, the folding memory `norm` and the scratch
-- copies) lives in one table W, and the "pointers" of the C code are 0-based offsets into it.
local RD = require("@formats/codecs/RangeCoder/Decoder")
local RD = require("@formats/codecs/entropy/RangeCoder/Decoder")
local Mdct = require("@formats/audio/opus/Mdct")
local T = require("@formats/audio/opus/CeltTables")
+3 -3
View File
@@ -5,11 +5,11 @@
-- bit rate, long MDCTs only (no transient detection), no pitch pre-filter, normal spreading, default allocation trim,
-- mono, or stereo as mid / side per band (the angle, intensity when it has no bits; dual L / R stereo on request). The bitstream side is a port of the libopus 1.6 encoder paths
-- (celt_encoder.c, quant_bands.c, laplace.c, rate.c, bands.c, vq.c, cwrs.c; BSD: licenses/libopus-BSD.txt) that
-- mirror audio/opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/Mdct.
-- mirror audio/opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/audio/Mdct.
-- Never throws.
local RE = require("@formats/codecs/RangeCoder/Encoder")
local RE = require("@formats/codecs/entropy/RangeCoder/Encoder")
local T = require("@formats/audio/opus/CeltTables")
local Mdct = require("@formats/codecs/Mdct")
local Mdct = require("@formats/codecs/audio/Mdct")
local CeltEncoder = {}
+1 -1
View File
@@ -4,7 +4,7 @@
-- audio/opus/Decoder: The Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c): per-frame mode switching
-- between SILK, hybrid and CELT, the redundant CELT frames of mode transitions, cross-fades, PLC fallbacks, the
-- multi-frame packet loop and multistream (channel mapping) decoding. Output is 48 kHz float in Luau arrays.
local RD = require("@formats/codecs/RangeCoder/Decoder")
local RD = require("@formats/codecs/entropy/RangeCoder/Decoder")
local Packet = require("@formats/audio/opus/Packet")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
+5 -5
View File
@@ -2,14 +2,14 @@
-- audio/opus/Encode: Ogg Opus writing (RFC 7845) around audio/opus/CeltEncoder: CELT-only packets (TOC config 31:
-- full band, 20 ms, code 0), OpusHead (mapping family 0, the pre-skip = the encoder's delay), OpusTags (vendor +
-- the tags as Vorbis comments), granule positions with end trimming, pages through containers/Ogg's muxer. Input at
-- other rates is resampled to 48 kHz (codecs/Resample); the input is a Types.Audio or a Decoder (codecs/Pcm). New in
-- other rates is resampled to 48 kHz (codecs/audio/Resample); the input is a Types.Audio or a Decoder (codecs/audio/Pcm). New in
-- formats-luau.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Ogg = require("@formats/containers/Ogg")
local Pcm = require("@formats/codecs/Pcm")
local Resample = require("@formats/codecs/Resample")
local VorbisComment = require("@formats/codecs/VorbisComment")
local Pcm = require("@formats/codecs/audio/Pcm")
local Resample = require("@formats/codecs/audio/Resample")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
local CeltEncoder = require("@formats/audio/opus/CeltEncoder")
local Encode = {}
@@ -42,7 +42,7 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
if type(bitrate) ~= "number" or bitrate < 6000 or bitrate > 510000 then
return nil, Err.new(Err.ARG, "bitrate 6000 .. 510000")
end
-- the whole input at 48 kHz (codecs/Resample for other rates), then as floats
-- the whole input at 48 kHz (codecs/audio/Resample for other rates), then as floats
if rate ~= 48000 then
local rs, rerr = Resample.source(src, 48000)
if not rs then
+1 -1
View File
@@ -4,7 +4,7 @@
-- audio/opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over a mixed-radix complex FFT (a port of the
-- kiss_fft stages used by libopus: radix 5, 3, 4 and 2). The 48 kHz mode uses N = 1920 >> shift for
-- shift = 0..3 (FFT sizes 480, 240, 120, 60). Arrays are Luau tables of numbers, 1-based.
-- Why not codecs/Mdct (measured by the cleanup pass): the shared transform computes the full N-sample IMDCT through a
-- Why not codecs/audio/Mdct (measured by the cleanup pass): the shared transform computes the full N-sample IMDCT through a
-- DCT-IV, of which CELT keeps the middle N / 2, so routing the decoder through it made CELT decoding 2-3x slower
-- (luau: 25 -> 54-76 ms for 3 s of 32 kbps stereo) and changed the output bits (same SNR against opusdec). This
-- fused libopus port (pre-rotation, a kiss_fft with fixed factors, post-rotation, TDAC) stays private.
+1 -1
View File
@@ -14,7 +14,7 @@
--
-- Fixed-point emulation: all values are Luau numbers holding C int32 / int16 values. Products of two int32 values
-- (64-bit in C) are split so that every intermediate stays below 2^53 and therefore exact.
local RD = require("@formats/codecs/RangeCoder/Decoder")
local RD = require("@formats/codecs/entropy/RangeCoder/Decoder")
local T = require("@formats/audio/opus/SilkTables")
local icdf = RD.icdf
+6 -6
View File
@@ -24,9 +24,9 @@ local Types = require("@formats/Types")
local Ogg = require("@formats/containers/Ogg")
local Decoder = require("@formats/audio/opus/Decoder")
local Packet = require("@formats/audio/opus/Packet")
local VorbisComment = require("@formats/codecs/VorbisComment")
local Pcm = require("@formats/codecs/Pcm")
local RangeDecoder = require("@formats/codecs/RangeCoder/Decoder")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
local Pcm = require("@formats/codecs/audio/Pcm")
local RangeDecoder = require("@formats/codecs/entropy/RangeCoder/Decoder")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
local Encode = require("@formats/audio/opus/Encode")
@@ -37,7 +37,7 @@ local Opus = {
category = "audio",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/RangeCoder/Decoder", "codecs/RangeCoder/Encoder", "codecs/Pcm", "codecs/Resample", "codecs/VorbisComment" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/entropy/RangeCoder/Decoder", "codecs/entropy/RangeCoder/Encoder", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 },
}
@@ -126,7 +126,7 @@ local function parseHead(b: buffer, off: number, size: number): (Head?, string?)
return head, nil
end
-- OpusTags (RFC 7845 section 5.2) -> vendor, tags (codecs/VorbisComment: lower-case keys, repeated fields joined
-- OpusTags (RFC 7845 section 5.2) -> vendor, tags (codecs/audio/VorbisComment: lower-case keys, repeated fields joined
-- with "; "), the raw fields
local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string }, { VorbisComment.Field })
if size < 16 or buffer.readstring(b, off, 8) ~= "OpusTags" then
@@ -372,7 +372,7 @@ function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?)
vendor = vendor,
tags = tags,
comments = rawTags,
-- mapping family 1 is in Vorbis channel order; the output is WAVE order (codecs/Pcm)
-- mapping family 1 is in Vorbis channel order; the output is WAVE order (codecs/audio/Pcm)
order = if not downmix and head.mappingFamily == 1 and head.channels > 2 then Pcm.WAVE_FROM_VORBIS[head.channels] else nil,
sampleRate = SAMPLE_RATE,
channels = if downmix then 2 else head.channels,
+2 -2
View File
@@ -11,7 +11,7 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Pcm = require("@formats/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Voc = {
@@ -19,7 +19,7 @@ local Voc = {
category = "audio",
extensions = { "voc" },
mime = { "audio/x-voc" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false },
}
+4 -4
View File
@@ -3,16 +3,16 @@
--!optimize 2
-- audio/vorbis/Encode: a basic but valid Vorbis I encoder in Ogg. New code written from the Vorbis I specification
-- (no libvorbis code). Design: long blocks only (2048 samples; blocksize 0 is declared as 256 but never used), the
-- Vorbis window, the MDCT (codecs/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a
-- Vorbis window, the MDCT (codecs/audio/Mdct, scale 4/N for the decoder's unscaled IMDCT); one floor 1 per channel with a
-- fixed post list of 30 points (bisection order, multiplier 2) fitted to the spectral envelope minus a quality-
-- dependent SNR, so the residue is quantized in steps of the floor; stereo square-polar coupling of the integer
-- residues (lossless); residue type 2 with 16-values-per-channel partitions and six classes (silent, |v| <= 1, 4, 15, then
-- cascades of x16 / x256 books for larger values); a fixed codebook set whose Huffman lengths come from Laplacian
-- models computed at load time (codewords assigned exactly as the spec's decoder does). Granules are sample-exact
-- (frames centred on multiples of 1024 from sample 0; the last page's granule trims the end). Never throws.
local Mdct = require("@formats/codecs/Mdct")
local Pcm = require("@formats/codecs/Pcm")
local VorbisComment = require("@formats/codecs/VorbisComment")
local Mdct = require("@formats/codecs/audio/Mdct")
local Pcm = require("@formats/codecs/audio/Pcm")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
local Ogg = require("@formats/containers/Ogg")
local Tables = require("@formats/audio/vorbis/Tables")
+2 -2
View File
@@ -2,7 +2,7 @@
--!native
--!optimize 2
-- audio/vorbis/Packet: Vorbis audio packet decoding (Vorbis I spec sections 4.3, 7, 8): mode and window shape, floor 1
-- curves, residue types 0 / 1 / 2, inverse channel coupling, the IMDCT (codecs/Mdct), windowing and overlap-add.
-- curves, residue types 0 / 1 / 2, inverse channel coupling, the IMDCT (codecs/audio/Mdct), windowing and overlap-add.
-- Floors, residues and coupling are ported from stb_vorbis 1.22 vorbis_decode_packet_rest / decode_residue /
-- do_floor / draw_line (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt). The overlap follows libvorbis:
-- each packet after the first returns the n_prev/4 + n_cur/4 samples between the centres of the two windows, so
@@ -16,7 +16,7 @@
local Codebook = require("@formats/audio/vorbis/Codebook")
local Setup = require("@formats/audio/vorbis/Setup")
local Tables = require("@formats/audio/vorbis/Tables")
local Mdct = require("@formats/codecs/Mdct")
local Mdct = require("@formats/codecs/audio/Mdct")
local Packet = {}
+6 -6
View File
@@ -1,6 +1,6 @@
--!strict
-- audio/vorbis: Ogg Vorbis (Vorbis I specification, Xiph.Org; RFC 5215 for the Ogg mapping). The decoder is a Luau
-- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/Mdct,
-- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/audio/Mdct,
-- with libvorbis' sample-exact timing: start trimming from the first page's granule, end trimming from the last
-- page's, granule-exact seeking (bisection, then decoding forward to a page boundary to recover the position).
-- Supports: decode / open of any channel count (1..255), rates, block sizes 64..8192, floor 1, residues 0 / 1 / 2,
@@ -18,8 +18,8 @@ local Ogg = require("@formats/containers/Ogg")
local Setup = require("@formats/audio/vorbis/Setup")
local Packet = require("@formats/audio/vorbis/Packet")
local Encode = require("@formats/audio/vorbis/Encode")
local Pcm = require("@formats/codecs/Pcm")
local VorbisComment = require("@formats/codecs/VorbisComment")
local Pcm = require("@formats/codecs/audio/Pcm")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
-- ------------------------------------------------------------------------------------------------ contract
local Vorbis = {
@@ -27,7 +27,7 @@ local Vorbis = {
category = "audio",
extensions = { "ogg", "oga" },
mime = { "audio/ogg", "audio/vorbis" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct", "codecs/Pcm", "codecs/VorbisComment" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/audio/Pcm", "codecs/audio/VorbisComment" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 },
}
@@ -41,7 +41,7 @@ export type EncodeOptions = {
}
-- ------------------------------------------------------------------------------------------------ constants
-- waveOrder(channels) -> output channel c is Vorbis channel order[c] (codecs/Pcm; identity past 8 channels)
-- waveOrder(channels) -> output channel c is Vorbis channel order[c] (codecs/audio/Pcm; identity past 8 channels)
local function waveOrder(ch: number): { number }
local m = Pcm.WAVE_FROM_VORBIS[ch]
if m then
@@ -399,7 +399,7 @@ function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
tags = tags,
vendor = vendor,
ident = id,
-- WAVE channel order out (codecs/Pcm): output channel c is Vorbis channel order[c]
-- WAVE channel order out (codecs/audio/Pcm): output channel c is Vorbis channel order[c]
order = waveOrder(id.channels),
source = {
format = "vorbis",
+2 -2
View File
@@ -18,7 +18,7 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Pcm = require("@formats/codecs/audio/Pcm")
local Riff = require("@formats/containers/Riff")
local Codecs = require("@formats/audio/wav/Codecs")
@@ -28,7 +28,7 @@ local Wav = {
category = "audio",
extensions = { "wav", "wave", "rf64", "bw64" },
mime = { "audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Riff", "codecs/audio/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, rf64 = true },
}
-13
View File
@@ -1,13 +0,0 @@
--!strict
-- codecs/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt):
-- symbols range-coded from the front of a frame, raw bits from its back. Opus (CELT and SILK) uses it; LZMA, VP8 and
-- CABAC have their own (different) binary coders. Moved here from audio/opus by the cleanup pass (same code).
--
-- local RD = require("@formats/codecs/RangeCoder/Decoder") -- RD.new(buf, base, size), RD.icdf / bits / uint ...
-- local RE = require("@formats/codecs/RangeCoder/Encoder") -- RE.new(size), RE.icdf / bits / uint, RE.done
local RangeCoder = {
Decoder = require("@formats/codecs/RangeCoder/Decoder"),
Encoder = require("@formats/codecs/RangeCoder/Encoder"),
}
return RangeCoder
@@ -1,14 +1,14 @@
--!strict
--!native
--!optimize 2
-- codecs/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4): SCE / CPE / LFE / DSE / PCE /
-- codecs/audio/Aac/Decode: the AAC-LC raw_data_block decoder (ISO/IEC 14496-3 subpart 4): SCE / CPE / LFE / DSE / PCE /
-- FIL / END elements, ics_info with window grouping, section data, scalefactors (with noise energies and intensity
-- positions), pulse data, TNS, the eleven spectral codebooks with escapes, dequantisation, M/S and intensity stereo,
-- perceptual noise substitution (FFmpeg's LCG so the noise matches it), the filterbank (sine / KBD windows, the four
-- window sequences, IMDCT through codecs/Mdct, overlap-add). FIL extension payloads (SBR / PS) are reported to a hook
-- window sequences, IMDCT through codecs/audio/Mdct, overlap-add). FIL extension payloads (SBR / PS) are reported to a hook
-- and otherwise skipped. Written from the standard; no third-party code. Never throws: returns nil, message.
local Mdct = require("@formats/codecs/Mdct")
local Tables = require("@formats/codecs/Aac/Tables")
local Mdct = require("@formats/codecs/audio/Mdct")
local Tables = require("@formats/codecs/audio/Aac/Tables")
local readu32, byteswap, lshift, rshift, band = buffer.readu32, bit32.byteswap, bit32.lshift, bit32.rshift, bit32.band
local floor, sqrt, abs = math.floor, math.sqrt, math.abs
@@ -1,5 +1,5 @@
--!strict
-- codecs/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): the scalefactor and the eleven
-- codecs/audio/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): the scalefactor and the eleven
-- spectral Huffman codebooks (code, length per symbol), the scalefactor band offsets per sampling rate (1024 and 128
-- lines) and the TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code;
-- see licenses/NOTICE.md). Generated; do not edit.
@@ -1,15 +1,15 @@
--!strict
-- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
-- codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
-- config element, explicit and backward-compatible SBR signalling), ADTS headers, and raw_data_block decoding
-- (codecs/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it.
-- Written from the standard (tables: codecs/Aac/Tables); no third-party code.
-- (codecs/audio/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it.
-- Written from the standard (tables: codecs/audio/Aac/Tables); no third-party code.
-- Supports: AAC-LC (object type 2) 1 - 8 channels, all sampling rates, long / short / start / stop windows, sine and KBD
-- windows, M/S, intensity stereo, PNS, TNS, pulses. HE-AAC (SBR, PS: object types 5 / 29, or implicit SBR payloads)
-- decodes its AAC-LC core at the core rate; `decoder.onExtension` receives every FIL extension payload (the hook for a
-- later SBR / PS module), `decoder.sbr` says whether one was seen. Not supported: AAC Main prediction, LTP, SSR gain
-- control, coupling channels, 960-sample frames, ER / USAC object types (UNSUPPORTED).
--
-- local Aac = require("@formats/codecs/Aac")
-- local Aac = require("@formats/codecs/audio/Aac")
-- local dec, err = Aac.decoder(asc) -- an AudioSpecificConfig (buffer) or { objectType, sfIndex, channels }
-- local frames, err = dec:decode(buf, offset, length) -- one raw_data_block -> dec.pcm (frames * channels floats)
-- local h = Aac.adts(buf, offset, limit) -- an ADTS header: { headerSize, frameSize, objectType, sfIndex, ... }
@@ -17,7 +17,7 @@
-- Never throws: bad data returns nil, Err.
local Err = require("@formats/core/Err")
local Bits = require("@formats/core/Bits")
local Decode = require("@formats/codecs/Aac/Decode")
local Decode = require("@formats/codecs/audio/Aac/Decode")
local Aac = {}
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Alac/Decode: the ALAC frame decoder: elements SCE / CPE / LFE / DSE / FIL / END, the adaptive Golomb-Rice
-- codecs/audio/Alac/Decode: the ALAC frame decoder: elements SCE / CPE / LFE / DSE / FIL / END, the adaptive Golomb-Rice
-- residuals with zero runs, the adaptive FIR predictor (orders 0, 31 and 1 .. 30), stereo unmixing, shifted low bytes,
-- uncompressed (escape) frames, 16 / 20 / 24 / 32-bit samples. Written from the ALAC format as published by Apple
-- (ALACDecoder / ag_dec / dp_dec, Apache 2.0; behaviour, not code). Never throws: returns nil, message.
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of
-- codecs/audio/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of
-- 0 .. 4 by first-difference energy), per channel LPC coefficients (Levinson-Durbin on a windowed autocorrelation,
-- orders 4 and 8 tried, quantised with denShift 9), residuals through the same adaptive FIR the decoder runs, the
-- adaptive Golomb-Rice code with zero runs; an uncompressed (escape) frame when that is smaller. 16 / 20 / 24-bit
@@ -1,10 +1,10 @@
--!strict
-- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
-- codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
-- Written from the ALAC format as Apple published it (ALACSpecificConfig, the element syntax, adaptive Golomb-Rice
-- residuals, the adaptive FIR predictor); no third-party code. 1 - 8 channels, 16 / 20 / 24 / 32-bit decode, 16 / 20 /
-- 24-bit encode. Channels come out (and go in) in WAV order (ALAC stores C L R ... for 3+ channels).
--
-- local Alac = require("@formats/codecs/Alac")
-- local Alac = require("@formats/codecs/audio/Alac")
-- local cfg, err = Alac.config(cookie) -- the 24-byte ALACSpecificConfig (frma / alac atoms skipped)
-- local dec = Alac.decoder(cfg)
-- local frames, err = dec:decode(buf, offset, length) -- one packet -> dec.pcm (interleaved integers, WAV order)
@@ -15,8 +15,8 @@
-- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Decode = require("@formats/codecs/Alac/Decode")
local Encode = require("@formats/codecs/Alac/Encode")
local Decode = require("@formats/codecs/audio/Alac/Decode")
local Encode = require("@formats/codecs/audio/Alac/Encode")
local Alac = {}
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Mdct/Fft: mixed-radix complex FFT of any size (radix 4, 2, 3, 5 butterflies, a generic odd-radix pass for
-- codecs/audio/Mdct/Fft: mixed-radix complex FFT of any size (radix 4, 2, 3, 5 butterflies, a generic odd-radix pass for
-- other primes), self-sorting Stockham passes ping-ponging between the data and a scratch array (the FFTPACK /
-- pocketfft pass structure, written from the textbook decimation-in-frequency derivation; no third-party code).
-- Data are separate real / imaginary arrays, 1-based. Never throws.
@@ -1,8 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
-- complex FFT (codecs/Mdct/Fft, mixed radix: AAC 2048 / 256, Vorbis 64 .. 8192, CELT 1920 / 240 / ...), plus the
-- codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
-- complex FFT (codecs/audio/Mdct/Fft, mixed radix: AAC 2048 / 256, Vorbis 64 .. 8192, CELT 1920 / 240 / ...), plus the
-- DCT-IV, a plain FFT and the sine / KBD / Vorbis windows. Shared by AAC, Vorbis and Opus (decoders and encoders).
-- Written from the textbook definitions (MDCT = DCT-IV of the folded input; DCT-IV through a half-size complex FFT
-- with pre / post twiddles); no third-party code.
@@ -15,7 +15,7 @@
-- are Luau arrays; `xi` / `yi` are the 1-based index of element 0, coefficient arrays may be strided (CELT
-- interleaves its short blocks).
--
-- local Mdct = require("@formats/codecs/Mdct")
-- local Mdct = require("@formats/codecs/audio/Mdct")
-- local plan = Mdct.new(2048) -- nil when N is not a multiple of 4
-- Mdct.forward(plan, x, 1, X, 1) -- 2048 samples -> 1024 coefficients
-- Mdct.inverse(plan, X, 1, 1, y, 1, 2 / 2048) -- 1024 coefficients -> 2048 samples
@@ -23,7 +23,7 @@
--
-- Never throws: bad sizes return nil from new(); the transforms trust the plan and the array ranges (the caller
-- sizes them).
local Fft = require("@formats/codecs/Mdct/Fft")
local Fft = require("@formats/codecs/audio/Mdct/Fft")
local cos, sin, pi, sqrt = math.cos, math.sin, math.pi, math.sqrt
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/Pcm). Integers map to
-- codecs/audio/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/audio/Pcm). Integers map to
-- v / 2^(bits-1) (as ffmpeg does); encoding rounds to nearest and clips. G.711 A-law / mu-law per ITU-T G.711 (the
-- classic Sun g711.c algorithm, written from the spec).
--
@@ -1,5 +1,5 @@
--!strict
-- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
-- codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
-- An encoder accepts a Types.Audio (fully decoded) or a Types.Decoder (streamed); Pcm.source turns either into one
-- pull interface, so encoders stream in blocks without caring which they got. Uncompressed containers (aiff, au,
-- voc, ...) get their Decoder from Pcm.rawDecoder (over a sample region of the file) or Pcm.audioDecoder.
@@ -10,7 +10,7 @@
-- local dec = Pcm.rawDecoder(buf, offset, frames, channels, rate, "s16be", tags?) -- a Types.Decoder
-- local dec = Pcm.audioDecoder(audio) -- a Types.Decoder over a decoded Audio
-- local raw = Pcm.encode(src, "s24le", writer) -- every frame of src appended to a core/Bytes Writer
-- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/Pcm/Convert)
-- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/audio/Pcm/Convert)
-- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767]
-- local x = Pcm.fromInt(s16, 16) -- s / 32768
--
@@ -19,7 +19,7 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Convert = require("@formats/codecs/Pcm/Convert")
local Convert = require("@formats/codecs/audio/Pcm/Convert")
local Pcm = {}
Pcm.Convert = Convert
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or
-- codecs/audio/Resample: audio sample-rate conversion by band-limited (Kaiser-windowed sinc) interpolation, streaming or
-- whole-buffer, any channel count, interleaved f32 (the Types.Audio / Decoder layout). Used by the Opus, MP3 and MP2
-- encoders (their input rates are fixed) and ops/AudioOps.resample. New in formats-luau (the textbook polyphase
-- filter; the kernel is the one the Opus encoder carried).
@@ -22,7 +22,7 @@
-- local rs = Resample.new(44100, 48000, 2) -- nil, message for bad rates
-- local b, n = rs:process(chunk, chunkFrames) -- the output frames this input completes
-- local b2, n2 = rs:flush() -- the rest (the input end padded with zeros)
-- local src2 = Resample.source(pcmSource, 48000) -- a codecs/Pcm Source at the new rate
-- local src2 = Resample.source(pcmSource, 48000) -- a codecs/audio/Pcm Source at the new rate
--
-- Never throws: bad arguments return nil, message (the api turns them into Err.ARG).
local Resample = {}
@@ -322,7 +322,7 @@ function Resample.buffer(src: buffer, frames: number, channels: number, from: nu
return out, got
end
-- source(src, to, opts?) -> a pull source ({ sampleRate, channels, frames, tags, read, err }, the codecs/Pcm Source
-- source(src, to, opts?) -> a pull source ({ sampleRate, channels, frames, tags, read, err }, the codecs/audio/Pcm Source
-- shape) reading src (any such source: Pcm.source(audioOrDecoder)) at the rate `to` | nil, message
function Resample.source(src: any, to: number, opts: Options?): (any, string?)
if type(src) ~= "table" or type(src.read) ~= "function" then
@@ -1,11 +1,11 @@
--!strict
-- codecs/SoundFont/Fallback: the built-in General MIDI set used when no SoundFont is given. A generated SoundFont
-- codecs/audio/SoundFont/Fallback: the built-in General MIDI set used when no SoundFont is given. A generated SoundFont
-- (the same shape Parse returns, so the same synth plays it): single-cycle sine / triangle / square / saw waves and a
-- looped noise sample, one preset per GM family of 8 programs (piano, chromatic percussion, organ, guitar, bass,
-- strings, ensemble, brass, reed, pipe, lead, pad, synth fx, ethnic, percussive, sound fx) with family envelopes,
-- filters and vibrato, plus a drum kit on bank 128 (pitch-swept sine kicks and toms, filtered noise snares, hats with
-- an exclusive class, cymbals). Written for this library (no third-party code).
local Parse = require("@formats/codecs/SoundFont/Parse")
local Parse = require("@formats/codecs/audio/SoundFont/Parse")
local Fallback = {}
@@ -1,5 +1,5 @@
--!strict
-- codecs/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader. The INFO list, the sdta samples (smpl 16-bit, + sm24
-- codecs/audio/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader. The INFO list, the sdta samples (smpl 16-bit, + sm24
-- when present) as one f32 buffer, and the pdta "hydra" (phdr pbag pmod pgen inst ibag imod igen shdr), flattened
-- into playable regions per preset: the instrument global zone, the preset global zone and the preset zone's
-- generators merged the way TinySoundFont (tsf.h v0.9, MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt)
@@ -1,6 +1,6 @@
--!strict
--!native
-- codecs/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. A port of TinySoundFont (tsf.h v0.9,
-- codecs/audio/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. A port of TinySoundFont (tsf.h v0.9,
-- MIT, (c) 2017-2025 Bernhard Schelling, based on SFZero (c) 2012 Steve Folta; licenses/TinySoundFont-LICENSE.txt):
-- voices with the DAHDSR volume envelope (exponential decay / release), the modulation envelope to pitch and filter
-- cutoff, the modulation and vibrato LFOs (triangle) to pitch / filter / volume, a resonant biquad low-pass, linear
@@ -1,11 +1,11 @@
--!strict
-- codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by
-- codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by
-- music/sf2 (the file format) and music/midi (rendering). The synth is a port of TinySoundFont (tsf.h v0.9, MIT,
-- (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt); see Parse / Synth for what is covered.
-- Without a bank, fallback() is a generated General MIDI set of simple waveforms (sine / triangle / square / saw /
-- noise) with a drum kit.
--
-- local SoundFont = require("@formats/codecs/SoundFont")
-- local SoundFont = require("@formats/codecs/audio/SoundFont")
-- local sf, err = SoundFont.parse(buf) -- buffer | string | core/Bytes Reader -> SoundFont | nil, Err
-- local sf = SoundFont.fallback() -- the built-in waveform set
-- local s = SoundFont.synth(sf, 44100, { gain = 0.5 }) -- a synth State; SoundFont.Synth.midi(s, 0x90, 60, 100)
@@ -14,9 +14,9 @@
-- Never throws: bad data returns nil, Err.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Parse = require("@formats/codecs/SoundFont/Parse")
local Synth = require("@formats/codecs/SoundFont/Synth")
local Fallback = require("@formats/codecs/SoundFont/Fallback")
local Parse = require("@formats/codecs/audio/SoundFont/Parse")
local Synth = require("@formats/codecs/audio/SoundFont/Synth")
local Fallback = require("@formats/codecs/audio/SoundFont/Fallback")
local SoundFont = {}
+141
View File
@@ -0,0 +1,141 @@
--!strict
-- codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part
-- every packet-based audio format repeated: decode packets in order into a pending float block, return frames in
-- read()-sized pieces, drop the encoder priming at the start and the padding at the end (gapless), and seek by
-- finding the packet holding the target (with codec pre-roll) and dropping up to it. AAC (ADTS), CAF and M4A use it;
-- formats with their own seeking (Opus granule bisection, FLAC, MP3, Vorbis) keep their streams. New in formats-luau
-- (the loop the three formats carried).
--
-- local dec, err = Stream.packets(dec, { -- dec: the Decoder table with its fields (sampleRate, channels,
-- count = n, -- frames, duration, bitrate, tags, ...); read / seek / position
-- start = function(i) return ... end, -- are added. start(i): packet i's first frame (absolute, before
-- decode = function(i) return n, err end,-- trimming); decode(i) -> frames | nil, Err, the samples in pcm()
-- pcm = function() return floats end, -- (interleaved, 1-based) until the next decode
-- reset = function() end, -- forget codec state (before a seek)
-- skip = priming, stop = lastFrame, -- output = absolute frames [skip, stop)
-- preroll = 1, -- packets decoded before the one holding a seek target (AAC: 1)
-- })
--
-- A decode failure ends the stream and is kept in dec.error (Pcm.drain reports it); a failing first packet is
-- returned by packets() as the open error. Never throws.
local Err = require("@formats/core/Err")
local Stream = {}
export type Spec = {
count: number,
start: (i: number) -> number,
decode: (i: number) -> (number?, Err.Err?),
pcm: () -> { number },
reset: () -> (),
skip: number?, -- default 0
stop: number?, -- default start(count + 1)
preroll: number?, -- default 0
cumulative: boolean?, -- frames after a packet = frames before + its output (default: start(i) + its output)
}
-- packets(dec, spec) -> dec (with read / seek / position) | nil, Err (the first packet failed)
function Stream.packets(dec: any, spec: Spec): (any, Err.Err?)
local sr, ch = dec.sampleRate, dec.channels
local count = spec.count
local skip = spec.skip or 0
local stopAt = spec.stop or spec.start(count + 1)
local frames = math.max(0, stopAt - skip)
local preroll = spec.preroll or 0
local decodeP, pcmOf, startOf = spec.decode, spec.pcm, spec.start
local nextPacket = 1
local decoded = 0 -- absolute frame after the packets decoded so far
local pendPos, pendN = 0, 0
local dropUntil = skip
local pos = 0
local failed: Err.Err? = nil
dec.error = nil
local function fill(): boolean
while true do
if nextPacket > count or decoded >= stopAt then
return false
end
local i = nextPacket
nextPacket += 1
local first = if spec.cumulative then decoded else startOf(i)
local n, e = decodeP(i)
if not n then
failed = e or Err.new(Err.CORRUPT, "packet " .. i .. " failed")
dec.error = failed
return false
end
decoded = first + n
local a = math.max(first, dropUntil)
local b = math.min(decoded, stopAt)
if b > a then
pendPos, pendN = a - first, b - first
return true
end
end
end
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
local want = math.max(0, math.floor(n))
local need = want * ch * 4
local ob = if out and buffer.len(out) >= need then out else buffer.create(need)
local got = 0
local writef32 = buffer.writef32
while got < want do
if pendPos >= pendN then
if failed or not fill() then
break
end
end
local take = math.min(want - got, pendN - pendPos)
local src = pcmOf()
local q = got * ch * 4
local s = pendPos * ch
for k = 1, take * ch do
writef32(ob, q, src[s + k])
q += 4
end
pendPos += take
got += take
end
pos += got
return ob, got
end
function dec.seek(_self: any, seconds: number)
local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0
local target = math.clamp(math.floor(sec * sr + 0.5), 0, frames) + skip -- absolute frame
-- the last packet starting at or before the target, minus the codec's pre-roll
local lo, hi, found = 1, count, 1
while lo <= hi do
local mid = (lo + hi) // 2
if startOf(mid) <= target then
found = mid
lo = mid + 1
else
hi = mid - 1
end
end
found = math.max(1, found - preroll)
spec.reset()
nextPacket = found
decoded = if count > 0 then startOf(found) else 0
dropUntil = target
pendPos, pendN = 0, 0
failed = nil
dec.error = nil
pos = target - skip
end
function dec.position(_self: any): number
return pos / sr
end
-- prime: surface a broken first packet as an open error
if count > 0 and frames > 0 and not fill() and failed then
return nil, failed
end
return dec, nil
end
return Stream
@@ -1,10 +1,10 @@
--!strict
--!native
-- codecs/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample
-- codecs/audio/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample
-- loops (forward, ping-pong, IT sustain loops while the key is held), linear or no interpolation, the IT two-pole
-- resonant filter, and a short gain ramp per tick against clicks. Written for this library (no third-party code).
--
-- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/Tracker)
-- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/audio/Tracker)
-- validates the sample buffers' sizes.
local floor, ceil, min = math.floor, math.ceil, math.min
local readf32, writef32 = buffer.readf32, buffer.writef32
@@ -1,6 +1,6 @@
--!strict
--!native
-- codecs/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned,
-- codecs/audio/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned,
-- plain or delta coded as in XM / IT 2.15, interleaved or planar stereo) to the engine's f32 samples, and back.
--
-- Never throws: reads past the source are refused up front (decode returns nil).
@@ -1,15 +1,15 @@
--!strict
--!native
-- codecs/Tracker/Player: the sequencer of the tracker engine. One player for MOD, S3M, XM and IT: rows, orders,
-- codecs/audio/Tracker/Player: the sequencer of the tracker engine. One player for MOD, S3M, XM and IT: rows, orders,
-- speed / tempo, every effect of the four formats (interpreted per format family: ProTracker / FastTracker 2 numeric
-- effects, ScreamTracker 3 / Impulse Tracker letter effects), instruments with volume / panning / pitch envelopes,
-- fadeout and auto-vibrato, IT new note actions (background voices), duplicate checks and resonant filters, and song
-- end / loop detection. Written from the format documents (ProTracker 2.3 docs, the XM spec and FT2 behaviour notes,
-- ST3 TECH.DOC, ITTECH.TXT); no third-party code. Mixing is codecs/Tracker/Mixer.
-- ST3 TECH.DOC, ITTECH.TXT); no third-party code. Mixing is codecs/audio/Tracker/Mixer.
--
-- Never throws: the module is validated by codecs/Tracker before a player is made, and every table lookup here is
-- Never throws: the module is validated by codecs/audio/Tracker before a player is made, and every table lookup here is
-- guarded.
local Tables = require("@formats/codecs/Tracker/Tables")
local Tables = require("@formats/codecs/audio/Tracker/Tables")
local wave64, autoWave = Tables.wave64, Tables.autoWave
local AMIGA = Tables.AMIGA
@@ -322,7 +322,7 @@ local function advanceRow(st: any)
end
-- ------------------------------------------------------------------------------------------------ pitch
-- the period of a note for a sample (see codecs/Tracker for the two period spaces)
-- the period of a note for a sample (see codecs/audio/Tracker for the two period spaces)
local function notePeriod(st: any, note: number, smp: any, ft: number?): (number, number)
local base, ref, tr
if st.fmt == MOD or st.fmt == XM then
@@ -1,6 +1,6 @@
--!strict
--!native
-- codecs/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the
-- codecs/audio/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the
-- auto-vibrato, the ProTracker period table (finetune 0, used to map MOD periods to notes and back) and the IT / S3M
-- volume-column tone-portamento and retrigger tables. All values are from the public format documents (ProTracker
-- 2.3 effect docs, FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT).
@@ -1,10 +1,10 @@
--!strict
-- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
-- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
-- their files into one Module structure (below); render(module, opts) plays any of them through the standard audio
-- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM
-- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests.
--
-- local Tracker = require("@formats/codecs/Tracker")
-- local Tracker = require("@formats/codecs/audio/Tracker")
-- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder
-- local seconds = Tracker.duration(module) -- one pass, song loops detected
--
@@ -48,10 +48,10 @@
-- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Player = require("@formats/codecs/Tracker/Player")
local Mixer = require("@formats/codecs/Tracker/Mixer")
local Pcm = require("@formats/codecs/Tracker/Pcm")
local Tables = require("@formats/codecs/Tracker/Tables")
local Player = require("@formats/codecs/audio/Tracker/Player")
local Mixer = require("@formats/codecs/audio/Tracker/Mixer")
local Pcm = require("@formats/codecs/audio/Tracker/Pcm")
local Tables = require("@formats/codecs/audio/Tracker/Tables")
local Tracker = {}
@@ -1,5 +1,5 @@
--!strict
-- codecs/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags.
-- codecs/audio/VorbisComment: Vorbis comment fields ("KEY=value", the tag block of Vorbis, Opus and FLAC) <-> Types.Tags.
-- Tag keys are lower case everywhere in formats-luau (the same names ID3 / MP4 / RIFF INFO map to): title, artist,
-- album, albumartist, date, genre, track, tracktotal, disc, disctotal, comment, composer, ...; TRACKNUMBER becomes
-- track, DISCNUMBER disc, DESCRIPTION comment, other fields their lower-cased name. Repeated fields are joined with
@@ -52,7 +52,7 @@ function VorbisComment.fields(tags: { [any]: any }): { string }
end
end
table.sort(keys)
local out = table.create(#keys)
local out: { string } = table.create(#keys) :: any
for i, k in keys do
out[i] = VorbisComment.fieldName(k) .. "=" .. tags[k]
end
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Brotli/Decode: a Brotli (RFC 7932) decoder over a whole in-memory stream. Written from the RFC, with the
-- codecs/compress/Brotli/Decode: a Brotli (RFC 7932) decoder over a whole in-memory stream. Written from the RFC, with the
-- reference decoder (google/brotli c/dec/decode.c, MIT) as the authority on edge cases (simple prefix code alphabet
-- widths, repeat codes, padding checks, the large-window extension). Supports every meta-block kind (compressed,
-- uncompressed, metadata), block types / counts, the four literal context modes, context maps with RLE and inverse
@@ -1,5 +1,5 @@
--!strict
-- codecs/Brotli/Static: GENERATED by tools/brotli_static.py from the brotli C sources (MIT, Google; see
-- codecs/compress/Brotli/Static: GENERATED by tools/brotli_static.py from the brotli C sources (MIT, Google; see
-- licenses/brotli-LICENSE.txt) - do not edit. The RFC 7932 static dictionary (122784 bytes, deflated, base64),
-- the context lookup table (Appendix B, 4 modes x 512) and the 121 word transforms (Appendix B).
return {
@@ -1,12 +1,12 @@
--!strict
-- codecs/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written
-- from the RFC (decoder in codecs/Brotli/Decode); the static dictionary, context table and word transforms come from
-- google/brotli (MIT, licenses/brotli-LICENSE.txt) through codecs/Brotli/Static (tools/brotli_static.py).
-- codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written
-- from the RFC (decoder in codecs/compress/Brotli/Decode); the static dictionary, context table and word transforms come from
-- google/brotli (MIT, licenses/brotli-LICENSE.txt) through codecs/compress/Brotli/Static (tools/brotli_static.py).
-- Supports every RFC 7932 stream (window sizes 10..24, metadata / uncompressed / compressed meta-blocks, the static
-- dictionary with all 121 transforms) and the large-window extension (opts.largeWindow). Not supported: compression,
-- shared / compound dictionaries (draft "shared brotli").
--
-- local Brotli = require("@formats/codecs/Brotli")
-- local Brotli = require("@formats/codecs/compress/Brotli")
-- local out, consumedEnd = Brotli.decompress(buf) -- buffer | string
-- local out, err = Brotli.decompress(buf, offset, length, { maxBytes = 2^24 })
--
@@ -15,9 +15,9 @@ local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Base64 = require("@formats/core/Base64")
local Deflate = require("@formats/codecs/Deflate")
local Decode = require("@formats/codecs/Brotli/Decode")
local StaticData = require("@formats/codecs/Brotli/Static")
local Deflate = require("@formats/codecs/compress/Deflate")
local Decode = require("@formats/codecs/compress/Brotli/Decode")
local StaticData = require("@formats/codecs/compress/Brotli/Static")
local Brotli = {}
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Bzip2/Decode: bzip2 stream decoder (Julian Seward's format, as documented by the bzip2 1.0.x sources and
-- codecs/compress/Bzip2/Decode: bzip2 stream decoder (Julian Seward's format, as documented by the bzip2 1.0.x sources and
-- Joe Tsai's "bzip2 format specification"). Written from the format description; no third-party code.
-- Per block: MSB-first bit reader on a local 32-bit bit buffer, Huffman groups (10-bit lookup + canonical fallback for
-- codes up to 20 bits), MTF + RUNA/RUNB, inverse BWT through one u32 vector (byte in the low 8 bits, next index
@@ -1,17 +1,17 @@
--!strict
-- codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec
-- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec
-- (layer 3): archive/bz2 and tar.bz2 build on it. Written from the format description (no third-party code).
-- Supports: block sizes 1..9, every Huffman group layout, block and stream CRCs, concatenated streams (as bzip2 -d).
-- Not supported: randomised blocks (bzip2 0.9.0 and older; Err.UNSUPPORTED), compression.
--
-- local Bzip2 = require("@formats/codecs/Bzip2")
-- local Bzip2 = require("@formats/codecs/compress/Bzip2")
-- local out, consumedEnd = Bzip2.decompress(buf) -- | nil, Err
-- local out = Bzip2.decompress(buf, offset, length, { maxBytes = 2^24 })
--
-- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / LIMIT / ARG).
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Decode = require("@formats/codecs/Bzip2/Decode")
local Decode = require("@formats/codecs/compress/Bzip2/Decode")
local Bzip2 = {}
@@ -1,12 +1,12 @@
--!strict
--!native
--!optimize 2
-- codecs/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth
-- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (core/Huffman
-- codecs/compress/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth
-- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (codecs/entropy/Huffman
-- length-limited codes). Level 0 = stored blocks only.
--
-- raw(buf, off, len, level) -> buffer. Never throws (the caller validated the arguments).
local Huffman = require("@formats/core/Huffman")
local Huffman = require("@formats/codecs/entropy/Huffman")
local readu8, writeu8, writeu16 = buffer.readu8, buffer.writeu8, buffer.writeu16
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
@@ -1,17 +1,17 @@
--!strict
--!native
--!optimize 2
-- codecs/Deflate/Inflate: raw DEFLATE (RFC 1951) decoder: stored, fixed-Huffman and dynamic-Huffman blocks.
-- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author); the table builder moved to core/Huffman, whose
-- codecs/compress/Deflate/Inflate: raw DEFLATE (RFC 1951) decoder: stored, fixed-Huffman and dynamic-Huffman blocks.
-- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author); the table builder moved to codecs/entropy/Huffman, whose
-- entries are symbol * 32 + length (5 length bits instead of 4).
--
-- Bits are read LSB first into a 32-bit bit buffer (refilled 4 bytes at a time with one readu32 while the input
-- lasts). Huffman codes decode through a core/Huffman LSB table indexed by the next LITBITS / DISTBITS bits; a longer
-- lasts). Huffman codes decode through a codecs/entropy/Huffman LSB table indexed by the next LITBITS / DISTBITS bits; a longer
-- code's primary slot links to a subtable, so a symbol is one or two table reads.
--
-- Nothing in this module throws on any input: every buffer read and write is bounds-checked, and corrupt data
-- returns nil, message. (Native code must never throw: it crashes Roblox Studio.)
local Huffman = require("@formats/core/Huffman")
local Huffman = require("@formats/codecs/entropy/Huffman")
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
@@ -1,9 +1,9 @@
--!strict
-- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
-- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
-- A codec (layer 1), not a format: png, zip, gzip, woff, tiff, ... build on it. Absorbed from deflate-luau 1.0.0
-- (same author; no third-party code); the compressor is new.
--
-- local Deflate = require("@formats/codecs/Deflate")
-- local Deflate = require("@formats/codecs/compress/Deflate")
-- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err
-- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known
-- local out, err = Deflate.zlib(buf) -- checks the Adler-32
@@ -15,8 +15,8 @@ local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Adler32 = require("@formats/core/Adler32")
local Inflate = require("@formats/codecs/Deflate/Inflate")
local Compress = require("@formats/codecs/Deflate/Compress")
local Inflate = require("@formats/codecs/compress/Deflate/Inflate")
local Compress = require("@formats/codecs/compress/Deflate/Compress")
local Deflate = {}
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), the xz check type 4. The 64-bit
-- codecs/compress/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), the xz check type 4. The 64-bit
-- value is kept as two u32 halves (hi, lo). Written from the xz file format specification. Never throws.
local band, bxor, rshift, lshift, bor = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift, bit32.bor
local readu8 = buffer.readu8
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by raw LZMA (.lzma, 7z) and LZMA2 (xz, 7z).
-- codecs/compress/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by raw LZMA (.lzma, 7z) and LZMA2 (xz, 7z).
-- Written from the LZMA specification and its reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain); the
-- structure (probability model layout, state transitions, distance / length decoding) follows that document.
--
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Lzma/Filters: the branch-call-jump (BCJ) and delta decoding filters of xz and 7z, run in place over a whole
-- codecs/compress/Lzma/Filters: the branch-call-jump (BCJ) and delta decoding filters of xz and 7z, run in place over a whole
-- decoded buffer range. Written from the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin,
-- public domain): x86, ARM, ARM-Thumb, PowerPC, SPARC, ARM64 and delta. Not supported: IA-64, RISC-V.
-- Never throws: every access is inside [o, o + n).
@@ -1,10 +1,10 @@
--!strict
-- codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
-- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
-- archive/xz, archive/7z (and anything else holding LZMA data) build on it. Decode only.
-- Written from the LZMA specification (LzmaSpec.cpp, Igor Pavlov, public domain) and the xz file format specification
-- 1.2 (Lasse Collin / Igor Pavlov, public domain); the BCJ filters follow xz-embedded (public domain).
--
-- local Lzma = require("@formats/codecs/Lzma")
-- local Lzma = require("@formats/codecs/compress/Lzma")
-- local out, e = Lzma.lzma(buf, off, len, props, unpackSize?, opts?) -- raw LZMA; props = 5-byte buffer / string
-- -- or { lc, lp, pb, dictSize }
-- local out, e = Lzma.lzma2(buf, off, len, dictSize?, unpackSize?, opts?) -- raw LZMA2 chunks
@@ -19,9 +19,9 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Decode = require("@formats/codecs/Lzma/Decode")
local Filters = require("@formats/codecs/Lzma/Filters")
local Crc64 = require("@formats/codecs/Lzma/Crc64")
local Decode = require("@formats/codecs/compress/Lzma/Decode")
local Filters = require("@formats/codecs/compress/Lzma/Filters")
local Crc64 = require("@formats/codecs/compress/Lzma/Crc64")
local readu8, readu32 = buffer.readu8, buffer.readu32
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
-- codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
-- image/tiff build on it. New code (no port), written from the GIF89a spec (appendix F) and TIFF 6.0 section 13.
-- gif LSB-first codes, a minimum code size 1..11 (2..8 in GIF), clear = 2^min, EOI = clear + 1, the code width
-- grows when the next free code reaches 2^width (max 12 bits; a full table stays frozen until a clear).
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no code copied from the
-- codecs/compress/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no code copied from the
-- BSD reference implementation). Frames (any number, concatenated), skippable frames, raw / RLE / compressed blocks,
-- Huffman literals (1 or 4 streams, new or repeated table), FSE sequence tables (predefined / RLE / compressed /
-- repeat), repeat offsets, the XXH64 content checksum. Not supported: dictionaries (a non-zero dictionary ID).
@@ -11,7 +11,7 @@
-- byte (o - n) / 8, bits before the stream start read as zeros.
--
-- Nothing here throws on any input: every read is bounds-checked; failures return nil, code, message, offset.
local Xxh64 = require("@formats/codecs/Zstd/Xxh64")
local Xxh64 = require("@formats/codecs/compress/Zstd/Xxh64")
local band, lshift, rshift = bit32.band, bit32.lshift, bit32.rshift
local readu8, readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Zstd/Xxh64: XXH64 (seed 0) of a buffer range, computed on 32-bit halves held in doubles (Luau and LuaJIT have
-- codecs/compress/Zstd/Xxh64: XXH64 (seed 0) of a buffer range, computed on 32-bit halves held in doubles (Luau and LuaJIT have
-- no 64-bit integers). 64 x 64 -> 64 products split the low operand into 16-bit limbs so every partial product is
-- exact below 2^53. From the xxHash specification (Yann Collet, BSD-2); no code copied. zstd stores the low 32 bits
-- of the hash as the frame content checksum. Never throws (the caller passes an in-range buffer slice).
@@ -1,18 +1,18 @@
--!strict
-- codecs/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd
-- codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd
-- data build on it. Written from the specification. Supports every frame feature a dictionary-less stream uses:
-- concatenated and skippable frames, raw / RLE / compressed blocks, Huffman literals (1 / 4 streams, repeated tables),
-- predefined / RLE / compressed / repeated FSE tables, repeat offsets, the XXH64 content checksum (verified).
-- Not supported: dictionaries (Err.UNSUPPORTED), compression.
--
-- local Zstd = require("@formats/codecs/Zstd")
-- local Zstd = require("@formats/codecs/compress/Zstd")
-- local out, err = Zstd.decompress(buf) -- -> buffer, consumedEnd | nil, Err
-- local out, err = Zstd.decompress(buf, off, len, { maxBytes = 2^24, verify = false })
--
-- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / UNSUPPORTED / LIMIT / ARG).
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Decode = require("@formats/codecs/Zstd/Decode")
local Decode = require("@formats/codecs/compress/Zstd/Decode")
local Zstd = {}
@@ -1,6 +1,6 @@
--!strict
--!native
-- core/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders.
-- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders.
--
-- Decoding tables (built by buildLsb / buildMsb) are u32 buffers, indexed by the next P bits of the stream:
-- entry = symbol * 32 + length a code of `length` <= P bits
@@ -8,7 +8,7 @@
-- entry = 0 no code (incomplete code set): the stream is corrupt
-- so a symbol is one or two table reads. LSB tables (DEFLATE, VP8L) are indexed by bit-reversed codes, MSB tables
-- (JPEG, MPEG) by the code itself. Code lengths are 1..MAXLEN (16), symbols < 2^27.
-- The hot loops (codecs/Deflate/Inflate) inline the lookup on their own bit buffer; decodeLsb / decodeMsb do it on a
-- The hot loops (codecs/compress/Deflate/Inflate) inline the lookup on their own bit buffer; decodeLsb / decodeMsb do it on a
-- core/Bits reader.
--
-- Encoding: lengths(freqs, maxLen) -> length-limited code lengths; codes(lengths) -> canonical code values.
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/RangeCoder/Decoder: the Opus range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus
-- codecs/entropy/RangeCoder/Decoder: the Opus range decoder (RFC 6716 section 4.1, libopus celt/entdec.c). Reads one Opus
-- frame from a `buffer` slice [base, base + storage). Raw bits (ec_dec_bits) are read from the end of the slice
-- backwards.
-- All values stay below 2^32, so plain Luau numbers hold them exactly; floor division is exact below 2^52.
@@ -1,8 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/RangeCoder/Encoder: the Opus range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD:
-- licenses/libopus-BSD.txt), the mirror of codecs/RangeCoder/Decoder. Writes one fixed-size frame: the range-coded
-- codecs/entropy/RangeCoder/Encoder: the Opus range encoder (RFC 6716 section 5.1), a port of libopus celt/entenc.c (BSD:
-- licenses/libopus-BSD.txt), the mirror of codecs/entropy/RangeCoder/Decoder. Writes one fixed-size frame: the range-coded
-- symbols from the front, the raw bits (ec_enc_bits) from the back, zeros between. Values stay below 2^32 as plain
-- numbers. Never throws: running out of room sets `error`.
local RangeEncoder = {}
@@ -0,0 +1,13 @@
--!strict
-- codecs/entropy/RangeCoder: the RFC 6716 range coder (libopus celt/entdec.c + entenc.c, BSD: licenses/libopus-BSD.txt):
-- symbols range-coded from the front of a frame, raw bits from its back. Opus (CELT and SILK) uses it; LZMA, VP8 and
-- CABAC have their own (different) binary coders. Moved here from audio/opus by the cleanup pass (same code).
--
-- local RD = require("@formats/codecs/entropy/RangeCoder/Decoder") -- RD.new(buf, base, size), RD.icdf / bits / uint ...
-- local RE = require("@formats/codecs/entropy/RangeCoder/Encoder") -- RE.new(size), RE.icdf / bits / uint, RE.done
local RangeCoder = {
Decoder = require("@formats/codecs/entropy/RangeCoder/Decoder"),
Encoder = require("@formats/codecs/entropy/RangeCoder/Encoder"),
}
return RangeCoder
@@ -1,5 +1,5 @@
--!strict
-- codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
-- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
-- with a "CFF " table (.otf). Parses the header, the INDEXes, the Top / Private DICTs (name-keyed and CID-keyed
-- fonts with FDArray / FDSelect formats 0 and 3), local and global subroutines, and runs charstrings to path commands
-- (moveTo / lineTo / cubicTo / close, font units, y up). The charstring interpreter is ported from stb_truetype 1.26
@@ -1,5 +1,5 @@
--!strict
-- codecs/TrueType/Glyf: TrueType glyph outlines (the glyf / loca tables): simple glyphs (contours of on- and
-- codecs/font/TrueType/Glyf: TrueType glyph outlines (the glyf / loca tables): simple glyphs (contours of on- and
-- off-curve points, with the implied on-curve midpoints) and composite glyphs (offsets or point matching, scale /
-- x-y scale / 2x2 transforms, SCALED_COMPONENT_OFFSET, nesting up to 8 levels). Ported from stb_truetype 1.26
-- (public domain / MIT, Sean Barrett) through imgui-luau's imstb_truetype.lua, made bounds-checked, with point
@@ -320,7 +320,7 @@ contours = function(f: Face, g: number, depth: number): ({ Contour }?, string?)
return composite(f, o, len, depth)
end
-- outline(f, g) -> path commands (codecs/Raster format, font units, y up) | nil, message
-- outline(f, g) -> path commands (codecs/image/Raster format, font units, y up) | nil, message
function Glyf.outline(f: Face, g: number): ({ any }?, string?)
local cs, err = contours(f, g, 0)
if not cs then
@@ -1,5 +1,5 @@
--!strict
-- codecs/TrueType/Tables: the sfnt tables besides the outlines: cmap (formats 0, 4, 6, 10, 12, 13; the best Unicode
-- codecs/font/TrueType/Tables: the sfnt tables besides the outlines: cmap (formats 0, 4, 6, 10, 12, 13; the best Unicode
-- subtable, symbol fonts through U+F000), kern (Microsoft version 0 and Apple version 1, format 0 pairs), GPOS pair
-- kerning (lookup type 2 formats 1 and 2, reached through the 'kern' feature, including extension lookups, type 9),
-- name (UTF-16BE and Mac Roman strings) and OS/2. Written from the OpenType spec, with stb_truetype 1.26 (public
@@ -1,10 +1,10 @@
--!strict
-- codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed
-- codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed
-- into the standard Font value (Types.Font): metrics (head / hhea / hmtx / OS/2 / post), cmap lookups, glyph outlines
-- (codecs/TrueType/Glyf for glyf, codecs/Cff for "CFF "), kerning ('kern' table and GPOS 'kern' pair adjustments),
-- names, and rasterize(glyph, px) through codecs/Raster. A codec, not a format: font/ttf, font/woff and font/woff2 all
-- (codecs/font/TrueType/Glyf for glyf, codecs/font/Cff for "CFF "), kerning ('kern' table and GPOS 'kern' pair adjustments),
-- names, and rasterize(glyph, px) through codecs/image/Raster. A codec, not a format: font/ttf, font/woff and font/woff2 all
-- build an sfnt and call TrueType.font(). Ported and modernised from stb_truetype 1.26 (public domain / MIT, Sean
-- Barrett and contributors) through imgui-luau's imstb_truetype.lua; the rasterizer is codecs/Raster instead of stb's.
-- Barrett and contributors) through imgui-luau's imstb_truetype.lua; the rasterizer is codecs/image/Raster instead of stb's.
-- Not supported: hinting, variable fonts (fvar / gvar / CFF2), vertical metrics, bitmap strikes (EBDT / CBDT / sbix),
-- colour layers (COLR), GSUB substitutions.
--
@@ -17,10 +17,10 @@
-- Never throws: malformed fonts return nil, Err from font(), and nil from the per-glyph methods.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Raster = require("@formats/codecs/Raster")
local Cff = require("@formats/codecs/Cff")
local Glyf = require("@formats/codecs/TrueType/Glyf")
local Tables = require("@formats/codecs/TrueType/Tables")
local Raster = require("@formats/codecs/image/Raster")
local Cff = require("@formats/codecs/font/Cff")
local Glyf = require("@formats/codecs/font/TrueType/Glyf")
local Tables = require("@formats/codecs/font/TrueType/Tables")
local TrueType = {}
@@ -1,6 +1,6 @@
--!strict
--!native
-- codecs/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable
-- codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable
-- blend modes of the W3C Compositing and Blending Level 1 spec (the Photoshop / Aseprite set), opacity, a grey layer
-- mask, clipping (source-atop: the backdrop keeps its alpha) and dissolve. Shared by ops/LayerOps (flatten) and the
-- layered formats that must write a composite (layered/psd). Never throws: rectangles are clipped to both buffers.
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws).
-- codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws).
-- Inverse: libjpeg's islow (jidctint.c: the Loeffler-Ligtenberg-Moschytz algorithm, 13-bit constants, two passes with
-- PASS1_BITS of scaling between them), plus the reduced 4x4 / 2x2 / 1x1 IDCTs for scaled decodes (jidctred.c); the
-- results match libjpeg-turbo's djpeg bit for bit. Absorbed from jpeg-luau 1.0 src/Jpeg/Idct.luau (same author).
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised
-- codecs/image/Jpeg/Arith: arithmetic-coded scans (ITU T.81 annex D / F.1.4, sequential and progressive) into quantised
-- DCT coefficients (native; never throws). A Luau translation of libjpeg-turbo's jdarith.c (Guido Vollbeding's
-- decoder, IJG licence: licenses/libjpeg-turbo-LICENSE.md) and the jaricom.c probability table.
--
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never
-- codecs/image/Jpeg/Color: chroma upsampling and colour conversion to RGBA8, one output row at a time (native; never
-- throws). Absorbed from jpeg-luau 1.0 src/Jpeg/Color.luau (same author); a Luau translation of libjpeg-turbo's
-- jdsample.c / jdcolor.c (IJG licence: licenses/libjpeg-turbo-LICENSE.md).
--
@@ -1,16 +1,16 @@
--!strict
-- codecs/Jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan /
-- codecs/image/Jpeg/Decode: the JPEG marker parser and output stage (interpreted; it validates everything the native Scan /
-- Arith / Dct / Color / Yuv loops index). Absorbed from jpeg-luau 1.0 src/Jpeg/init.luau (same author) and extended:
-- arithmetic-coded frames (SOF9 / SOF10, DAC), a byte range instead of a whole buffer, APP1 EXIF / APP2 ICC / COM
-- / JFIF density collected for meta, the AVI1 APP0 field polarity and the end of the image (Motion-JPEG), and a
-- yuv420p output straight from the IDCT planes (outputYuv). The IDCT size choice for scaled decodes follows
-- libjpeg-turbo's jdmaster.c. Moved from image/jpeg/Decode to codecs/Jpeg/Decode for the video formats.
local Scan = require("@formats/codecs/Jpeg/Scan")
local Arith = require("@formats/codecs/Jpeg/Arith")
local Color = require("@formats/codecs/Jpeg/Color")
local Tables = require("@formats/codecs/Jpeg/Tables")
local Yuv = require("@formats/codecs/Jpeg/Yuv")
local Dct = require("@formats/codecs/Dct")
-- libjpeg-turbo's jdmaster.c. Moved from image/jpeg/Decode to codecs/image/Jpeg/Decode for the video formats.
local Scan = require("@formats/codecs/image/Jpeg/Scan")
local Arith = require("@formats/codecs/image/Jpeg/Arith")
local Color = require("@formats/codecs/image/Jpeg/Color")
local Tables = require("@formats/codecs/image/Jpeg/Tables")
local Yuv = require("@formats/codecs/image/Jpeg/Yuv")
local Dct = require("@formats/codecs/image/Dct")
local readu8 = buffer.readu8
local band, rshift = bit32.band, bit32.rshift
@@ -1,16 +1,16 @@
--!strict
--!native
--!optimize 2
-- codecs/Jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman
-- codecs/image/Jpeg/Encode: the JPEG encoder (native; never throws). Baseline (SOF0) with the standard or optimised Huffman
-- tables and progressive (SOF2, libjpeg's jpeg_simple_progression script, optimised tables per scan); grey or YCbCr
-- 4:4:4 / 4:2:2 / 4:2:0, or yuv420p planes coded as they are (4:2:0, no colour conversion: the Motion-JPEG
-- encoders); restart intervals. Moved from image/jpeg/Encode to codecs/Jpeg/Encode. It follows libjpeg-turbo's
-- encoders); restart intervals. Moved from image/jpeg/Encode to codecs/image/Jpeg/Encode. It follows libjpeg-turbo's
-- encoder step for step so that its output is byte-identical to cjpeg's for the same settings: jccolor.c
-- (fixed-point RGB -> YCbCr), jcsample.c (box downsampling with alternating rounding bias, right-edge replication),
-- jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c (codecs/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs,
-- jccoefct.c (dummy edge blocks), jfdctint.c + jcdctmgr.c (codecs/image/Dct), jchuff.c (sequential coding, jpeg_gen_optimal_table) and jcphuff.c (progressive coding: EOB runs,
-- correction-bit buffering). Luau translation of IJG code: licenses/libjpeg-turbo-LICENSE.md.
local Dct = require("@formats/codecs/Dct")
local Tables = require("@formats/codecs/Jpeg/Tables")
local Dct = require("@formats/codecs/image/Dct")
local Tables = require("@formats/codecs/image/Jpeg/Tables")
local readu8, writeu8, readi16, writei16, readu16, writeu16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16, buffer.readu16, buffer.writeu16
local band, countlz = bit32.band, bit32.countlz
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from
-- codecs/image/Jpeg/Scan: Huffman-coded scan decoding into quantised DCT coefficients (native; never throws). Absorbed from
-- jpeg-luau 1.0 src/Jpeg/Scan.luau (same author); unchanged but for this header.
--
-- `destuff` copies one scan's entropy-coded bytes into a clean buffer: it drops the stuffed 0x00 after each 0xFF,
@@ -1,5 +1,5 @@
--!strict
-- codecs/Jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline
-- codecs/image/Jpeg/Tables: the standard tables of ITU T.81 annex K: the example Huffman tables (K.3, which every baseline
-- encoder without optimisation writes and Motion-JPEG frames leave out) and the luminance / chrominance quantisation
-- tables (K.1) with libjpeg's quality scaling (jcparam.c jpeg_quality_scaling / jpeg_add_quant_table).
local Tables = {}
@@ -1,10 +1,10 @@
--!strict
--!native
--!optimize 2
-- codecs/Jpeg/Yuv: the yuv420p output of the JPEG decoder (native; never throws): the IDCT output planes (u16
-- codecs/image/Jpeg/Yuv: the yuv420p output of the JPEG decoder (native; never throws): the IDCT output planes (u16
-- samples, block-padded) cropped into u8 yuv420p planes without colour conversion or upsampling, 4:2:2 / 4:4:4
-- chroma reduced to 4:2:0 by averaging, and the interleaving of two fields (AVI1 interlaced Motion-JPEG).
-- The callers (codecs/Jpeg/Decode, codecs/Jpeg) size every buffer; each loop reads and writes inside those sizes.
-- The callers (codecs/image/Jpeg/Decode, codecs/image/Jpeg) size every buffer; each loop reads and writes inside those sizes.
local readu16, writeu8, readu32, writeu32 = buffer.readu16, buffer.writeu8, buffer.readu32, buffer.writeu32
local Yuv = {}
@@ -1,7 +1,7 @@
--!strict
-- codecs/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG
-- codecs/image/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG
-- video tracks (AVI / Matroska / QuickTime) decode and encode their frames with it. The engine (Huffman and
-- arithmetic scan decoding, IDCTs through codecs/Dct, libjpeg-turbo's upsampling and colour conversion, the encoder)
-- arithmetic scan decoding, IDCTs through codecs/image/Dct, libjpeg-turbo's upsampling and colour conversion, the encoder)
-- was absorbed from jpeg-luau 1.0 (same author) into image/jpeg and moved down here; it is bit-exact with libjpeg-turbo's
-- djpeg and byte-identical with cjpeg. IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md.
--
@@ -31,9 +31,9 @@
-- Never throws: bad data or arguments return nil, Err.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Decode = require("@formats/codecs/Jpeg/Decode")
local Encode = require("@formats/codecs/Jpeg/Encode")
local Yuv = require("@formats/codecs/Jpeg/Yuv")
local Decode = require("@formats/codecs/image/Jpeg/Decode")
local Encode = require("@formats/codecs/image/Jpeg/Encode")
local Yuv = require("@formats/codecs/image/Jpeg/Yuv")
local Jpeg = {}
@@ -1,11 +1,13 @@
--!strict
--!native
--!optimize 2
-- image/bmp/Pixels: the pixel loops (native), decode and encode. Absorbed from bmp-luau b86aed6 (same author, no
-- third-party code); the encoder loops are new. They never throw: the caller (init.luau) validates every size first, and
-- hands in a source buffer that holds every byte an uncompressed loop can read (a truncated file is copied into a
-- zero-padded buffer). The RLE loop checks each read against its end offset. Output: RGBA8, top-down rows, one
-- u32 per pixel (R | G << 8 | B << 16 | A << 24, little-endian = bytes R, G, B, A).
-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP,
-- the DIBs inside ICO / CUR, ...): 1 / 2 / 4 / 8-bit indexes through a palette, BGR / BGRA, 5-5-5, bit-masked 16 /
-- 24 / 32-bit pixels, RLE4 / RLE8, rows bottom-up or top-down; and the encoder direction (rgba8 -> BGR / BGRA /
-- 8-bit indexes, bottom-up). Absorbed from bmp-luau b86aed6 (same author, no third-party code); the encoder loops
-- are new. They never throw: the caller validates every size first and hands in a source buffer that holds every
-- byte an uncompressed loop can read (a truncated file is copied into a zero-padded buffer); the RLE loop checks each
-- read against its end offset. Output: rgba8, top-down rows, one u32 per pixel (bytes R, G, B, A).
local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8
local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift
@@ -39,6 +41,19 @@ function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number,
end
end
-- 16 bpp X-R-G-B 1-5-5-5 (BI_RGB 16-bit), opaque; 5-bit channels scaled to 8 bits with rounding
function Pixels.rgb555(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean)
for r = 0, h - 1 do
local so = base + r * stride
local d = (if topDown then r else h - 1 - r) * w * 4
for x = 0, w - 1 do
local s = readu16(src, so + x * 2)
local cr, cg, cb = band(rshift(s, 10), 31), band(rshift(s, 5), 31), band(s, 31)
writeu32(dst, d + x * 4, (cr * 255 + 15) // 31 + ((cg * 255 + 15) // 31) * 256 + ((cb * 255 + 15) // 31) * 65536 + 0xFF000000)
end
end
end
-- 24 bpp BI_RGB: B, G, R
function Pixels.bgr24(src: buffer, base: number, stride: number, dst: buffer, w: number, h: number, topDown: boolean)
for r = 0, h - 1 do
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette
-- codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette
-- writer) builds on it. New code: Heckbert's median cut and Gervautz-Purgathofer octree, both over a 5-bit-per-channel
-- weighted histogram (palette colours are the exact means of the pixels they cover), nearest-colour mapping with
-- optional Floyd-Steinberg error diffusion. Deterministic: the same palette and indexes on every runtime (no table
@@ -1,14 +1,14 @@
--!strict
--!native
--!optimize 2
-- codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
-- codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
-- transform, with the nonzero and even-odd fill rules, plus a polygon stroker. Used by the fonts (glyph outlines) and
-- by vector/svg. New code; the coverage accumulation is the signed-area method of font-rs (Raph Levien, Apache-2.0 /
-- MIT, an algorithm description, no code copied) and of stb_truetype v2: every edge adds its exact signed area to an
-- accumulation row; a running sum along the row gives the winding coverage of each pixel. The rules map the summed
-- coverage a as FreeType does: nonzero = min(1, |a|), even-odd = |a| folded modulo 2.
--
-- local R = require("@formats/codecs/Raster")
-- local R = require("@formats/codecs/image/Raster")
-- local p = R.path():moveTo(0, 0):lineTo(10, 0):quadTo(10, 10, 0, 10):close() -- or a plain command list:
-- local cmds = { { op = "moveTo", 0, 0 }, { op = "lineTo", 10, 0 }, { op = "cubicTo", 12, 2, 12, 8, 10, 10 },
-- { op = "close" } } -- (the Font:outline() format)
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Vp8/Decode: the VP8 frame decoder (RFC 6386): the boolean entropy decoder, frame / segment / filter /
-- codecs/image/Vp8/Decode: the VP8 frame decoder (RFC 6386): the boolean entropy decoder, frame / segment / filter /
-- quantizer headers, token probability updates, intra modes, residual tokens, the inverse WHT and DCT, intra
-- prediction (16x16, 4x4, chroma), and the normal and simple loop filters: a port of libwebp 1.6 src/dec/vp8_dec.c,
-- tree_dec.c, quant_dec.c, frame_dec.c, src/dsp/dec.c and src/utils/bit_reader* (BSD-3-Clause,
@@ -9,15 +9,15 @@
-- vp8/common/findnearmv.c, vp8_loopfilter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt): reference updates and sign
-- bias, the frame context saved around frames that do not refresh it, persistent segment maps and loop filter deltas,
-- inter modes from the near vectors, motion vectors, split macroblocks, intra macroblocks in inter frames, per
-- reference / mode loop filter levels; the prediction itself is codecs/Vp8/Predict. Bit-exact with libvpx / ffmpeg
-- reference / mode loop filter levels; the prediction itself is codecs/image/Vp8/Predict. Bit-exact with libvpx / ffmpeg
-- (and with libwebp on key frames). Where libvpx and ffmpeg disagree on streams no encoder writes (an intermediate
-- clamp of segment filter levels, copying golden to altref and altref to golden in one frame), this follows ffmpeg.
--
-- The decoder state (Decode.new) keeps what persists between frames: the frame context, segment / filter headers, the
-- segment map, the last / golden / altref frames. Never throws: bad data returns nil, "message" ("truncated: ..." when
-- the data ends early).
local Tables = require("@formats/codecs/Vp8/Tables")
local Predict = require("@formats/codecs/Vp8/Predict")
local Tables = require("@formats/codecs/image/Vp8/Tables")
local Predict = require("@formats/codecs/image/Vp8/Predict")
local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
local readu8, writeu8, readi16, writei16 = buffer.readu8, buffer.writeu8, buffer.readi16, buffer.writei16
@@ -1,14 +1,14 @@
--!strict
--!native
--!optimize 2
-- codecs/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the
-- codecs/image/Vp8/Predict: VP8 inter prediction (RFC 6386 section 18): the six-tap sub-pixel filters (version 0), the
-- bilinear ones (versions 1-3; version 3 also rounds chroma vectors to full pixels), chroma vectors derived from the
-- luma ones, split macroblocks, and the reference frame borders. After libvpx 1.17 vp8/common/reconinter.c and
-- filter.c (BSD-3-Clause, licenses/libvpx-LICENSE.txt). Out-of-frame motion reads the reference as if its edge pixels
-- extended forever, which is exactly what libvpx computes with its 32 pixel border plus its motion vector clamping (the
-- clamps only kick in once every tap is in the border). The planes keep a BORDER pixel border filled by extend(); a
-- block whose taps leave it is first copied with clamped coordinates. Never throws.
local Tables = require("@formats/codecs/Vp8/Tables")
local Tables = require("@formats/codecs/image/Vp8/Tables")
local readu8, writeu8, bcopy, bcreate, bfill = buffer.readu8, buffer.writeu8, buffer.copy, buffer.create, buffer.fill
local readu32, writeu32 = buffer.readu32, buffer.writeu32
@@ -20,7 +20,7 @@ local Predict = {}
local BORDER = 32
Predict.BORDER = BORDER
-- the work buffer stride (codecs/Vp8/Decode: BPS)
-- the work buffer stride (codecs/image/Vp8/Decode: BPS)
local BPS = 32
local emu = bcreate(32 * 32) -- a block with its taps, edges replicated
@@ -1,5 +1,5 @@
--!strict
-- codecs/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6
-- codecs/image/Vp8/Tables: the constant VP8 tables of RFC 6386 (sections 13.5, 13.4, 11.5, 14.1), copied from libwebp 1.6
-- src/dec/tree_dec.c and src/dec/quant_dec.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); the inter frame tables
-- (sections 16-18: mode / motion vector probabilities, mode contexts, split partitions, sub-pixel filters) from
-- libvpx 1.17 vp8/common (entropymode.c, vp8_entropymodedata.h, entropymv.c, modecont.c, decodemv.c, filter.c;
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Vp8/Yuv: 4:2:0 Y'CbCr (BT.601, limited range) to rgba8 the way libwebp's decoder does it, bit-exact: the
-- codecs/image/Vp8/Yuv: 4:2:0 Y'CbCr (BT.601, limited range) to rgba8 the way libwebp's decoder does it, bit-exact: the
-- 14-bit fixed-point VP8YuvToRgb of src/dsp/yuv.h, with either the "fancy" upsampler (src/dsp/upsampling.c: a 9-3-3-1
-- bilinear filter on the chroma, libwebp's default) or point sampling (dwebp -nofancy). A port of libwebp 1.6
-- (BSD-3-Clause, licenses/libwebp-LICENSE.txt).
@@ -1,5 +1,5 @@
--!strict
-- codecs/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
-- codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the
-- WebM / Matroska and IVF video tracks use its decoder object. Key frames are a port of libwebp 1.6 (BSD-3-Clause,
-- licenses/libwebp-LICENSE.txt), bit-exact with libwebp: the yuv420p planes equal `dwebp -yuv`, and toRgba equals
-- `dwebp -pam` (fancy upsampling) or `dwebp -nofancy -pam`. Inter frames follow libvpx 1.17 (BSD-3-Clause,
@@ -12,7 +12,7 @@
-- Speed (one Zen 5 core): 640x480 inter frames ~190 fps under luau --codegen, ~220 fps under LuaJIT with the trace
-- limits the host module sets (maxtrace=8000; with LuaJIT's default 1000 traces the decoder thrashes: ~70 fps).
--
-- local Vp8 = require("@formats/codecs/Vp8")
-- local Vp8 = require("@formats/codecs/image/Vp8")
-- local frame, err = Vp8.decodeFrame(buf, off, len) -- one key frame: a yuv420p Types.Image
-- local rgba = Vp8.toRgba(frame) -- rgba8 Image (libwebp's fancy upsampling)
-- local dec = Vp8.newDecoder() -- a stream (WebM, IVF): key and inter frames
@@ -22,8 +22,8 @@
-- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT / ARG).
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Decode = require("@formats/codecs/Vp8/Decode")
local Yuv = require("@formats/codecs/Vp8/Yuv")
local Decode = require("@formats/codecs/image/Vp8/Decode")
local Yuv = require("@formats/codecs/image/Vp8/Yuv")
local Vp8 = {}
Loaded 100 of 283 files, more files were not shown because too many files have changed in this diff. Show more