diff --git a/README.md b/README.md index 4c5c37e..d47d4c1 100644 --- a/README.md +++ b/README.md @@ -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) + // 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, /.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#`). +on PATH or runs them with `nix shell nixpkgs#`); 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/ - // ops/ -compat/luajit.lua tools/ tests/ (T.luau, /.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 diff --git a/docs/API.md b/docs/API.md index 5e6b861..7c2318a 100644 --- a/docs/API.md +++ b/docs/API.md @@ -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 diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 8a551f7..13962b1 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -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. diff --git a/docs/STYLE.md b/docs/STYLE.md index 9d52919..11654b8 100644 --- a/docs/STYLE.md +++ b/docs/STYLE.md @@ -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, ...) // 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// 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//`); `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/")` (tests and tools may also use `require("@tests/")`). 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//` or `containers/`) instead of +copying. + ## 3. Tests `tests//.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/")`; 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///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//` 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). diff --git a/docs/video.md b/docs/video.md index ce04b20..184ca45 100644 --- a/docs/video.md +++ b/docs/video.md @@ -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/` | 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`: diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 79b5789..d5cf13f 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -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") diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index b40147b..9060244 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -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? } diff --git a/src/Formats/archive/7z/init.luau b/src/Formats/archive/7z/init.luau index 653195a..4691ae7 100644 --- a/src/Formats/archive/7z/init.luau +++ b/src/Formats/archive/7z/init.luau @@ -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 }, } diff --git a/src/Formats/archive/br/init.luau b/src/Formats/archive/br/init.luau index 6949a02..f67d16d 100644 --- a/src/Formats/archive/br/init.luau +++ b/src/Formats/archive/br/init.luau @@ -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 }, } diff --git a/src/Formats/archive/bz2/init.luau b/src/Formats/archive/bz2/init.luau index 074bdc2..224aa33 100644 --- a/src/Formats/archive/bz2/init.luau +++ b/src/Formats/archive/bz2/init.luau @@ -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 }, } diff --git a/src/Formats/archive/gzip/init.luau b/src/Formats/archive/gzip/init.luau index e5210ea..848ca95 100644 --- a/src/Formats/archive/gzip/init.luau +++ b/src/Formats/archive/gzip/init.luau @@ -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 }, } diff --git a/src/Formats/archive/xz/init.luau b/src/Formats/archive/xz/init.luau index cb0a07c..0f86278 100644 --- a/src/Formats/archive/xz/init.luau +++ b/src/Formats/archive/xz/init.luau @@ -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" } }, } diff --git a/src/Formats/archive/zip/init.luau b/src/Formats/archive/zip/init.luau index 081a7e0..1aa8000 100644 --- a/src/Formats/archive/zip/init.luau +++ b/src/Formats/archive/zip/init.luau @@ -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. -- diff --git a/src/Formats/archive/zst/init.luau b/src/Formats/archive/zst/init.luau index af5eef6..e336e30 100644 --- a/src/Formats/archive/zst/init.luau +++ b/src/Formats/archive/zst/init.luau @@ -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 }, } diff --git a/src/Formats/audio/aac/init.luau b/src/Formats/audio/aac/init.luau index 21deaf5..9219ccd 100644 --- a/src/Formats/audio/aac/init.luau +++ b/src/Formats/audio/aac/init.luau @@ -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?) diff --git a/src/Formats/audio/aiff/init.luau b/src/Formats/audio/aiff/init.luau index baf8ad2..a0a4a8c 100644 --- a/src/Formats/audio/aiff/init.luau +++ b/src/Formats/audio/aiff/init.luau @@ -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) diff --git a/src/Formats/audio/au/init.luau b/src/Formats/audio/au/init.luau index 08a45ab..dd52cff 100644 --- a/src/Formats/audio/au/init.luau +++ b/src/Formats/audio/au/init.luau @@ -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 }, } diff --git a/src/Formats/audio/caf/init.luau b/src/Formats/audio/caf/init.luau index 48769f9..fd46e96 100644 --- a/src/Formats/audio/caf/init.luau +++ b/src/Formats/audio/caf/init.luau @@ -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?) diff --git a/src/Formats/audio/flac/Encode.luau b/src/Formats/audio/flac/Encode.luau index ecc187c..3b3c99b 100644 --- a/src/Formats/audio/flac/Encode.luau +++ b/src/Formats/audio/flac/Encode.luau @@ -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 = {} diff --git a/src/Formats/audio/flac/Meta.luau b/src/Formats/audio/flac/Meta.luau index 1b1508b..ff4abdb 100644 --- a/src/Formats/audio/flac/Meta.luau +++ b/src/Formats/audio/flac/Meta.luau @@ -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 diff --git a/src/Formats/audio/flac/init.luau b/src/Formats/audio/flac/init.luau index 26e321c..d3b7048 100644 --- a/src/Formats/audio/flac/init.luau +++ b/src/Formats/audio/flac/init.luau @@ -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 }, } diff --git a/src/Formats/audio/m4a/init.luau b/src/Formats/audio/m4a/init.luau index babc9bd..0a455e7 100644 --- a/src/Formats/audio/m4a/init.luau +++ b/src/Formats/audio/m4a/init.luau @@ -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) diff --git a/src/Formats/audio/mp3/init.luau b/src/Formats/audio/mp3/init.luau index 5029c4e..a281cf3 100644 --- a/src/Formats/audio/mp3/init.luau +++ b/src/Formats/audio/mp3/init.luau @@ -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))) diff --git a/src/Formats/audio/opus/Celt.luau b/src/Formats/audio/opus/Celt.luau index 81a6c68..f979aca 100644 --- a/src/Formats/audio/opus/Celt.luau +++ b/src/Formats/audio/opus/Celt.luau @@ -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") diff --git a/src/Formats/audio/opus/CeltEncoder.luau b/src/Formats/audio/opus/CeltEncoder.luau index b4891a8..662bd69 100644 --- a/src/Formats/audio/opus/CeltEncoder.luau +++ b/src/Formats/audio/opus/CeltEncoder.luau @@ -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 = {} diff --git a/src/Formats/audio/opus/Decoder.luau b/src/Formats/audio/opus/Decoder.luau index c4fc928..b93f0c1 100644 --- a/src/Formats/audio/opus/Decoder.luau +++ b/src/Formats/audio/opus/Decoder.luau @@ -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") diff --git a/src/Formats/audio/opus/Encode.luau b/src/Formats/audio/opus/Encode.luau index 971d872..f214abd 100644 --- a/src/Formats/audio/opus/Encode.luau +++ b/src/Formats/audio/opus/Encode.luau @@ -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 diff --git a/src/Formats/audio/opus/Mdct.luau b/src/Formats/audio/opus/Mdct.luau index 9143cb5..4fff2ca 100644 --- a/src/Formats/audio/opus/Mdct.luau +++ b/src/Formats/audio/opus/Mdct.luau @@ -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. diff --git a/src/Formats/audio/opus/Silk.luau b/src/Formats/audio/opus/Silk.luau index 7c76401..f85d798 100644 --- a/src/Formats/audio/opus/Silk.luau +++ b/src/Formats/audio/opus/Silk.luau @@ -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 diff --git a/src/Formats/audio/opus/init.luau b/src/Formats/audio/opus/init.luau index b1d213d..6a98cea 100644 --- a/src/Formats/audio/opus/init.luau +++ b/src/Formats/audio/opus/init.luau @@ -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, diff --git a/src/Formats/audio/voc/init.luau b/src/Formats/audio/voc/init.luau index 3feca49..66e72ac 100644 --- a/src/Formats/audio/voc/init.luau +++ b/src/Formats/audio/voc/init.luau @@ -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 }, } diff --git a/src/Formats/audio/vorbis/Encode.luau b/src/Formats/audio/vorbis/Encode.luau index e1ce3ad..5483130 100644 --- a/src/Formats/audio/vorbis/Encode.luau +++ b/src/Formats/audio/vorbis/Encode.luau @@ -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") diff --git a/src/Formats/audio/vorbis/Packet.luau b/src/Formats/audio/vorbis/Packet.luau index ca69d79..791745a 100644 --- a/src/Formats/audio/vorbis/Packet.luau +++ b/src/Formats/audio/vorbis/Packet.luau @@ -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 = {} diff --git a/src/Formats/audio/vorbis/init.luau b/src/Formats/audio/vorbis/init.luau index 8081e1c..917ad9f 100644 --- a/src/Formats/audio/vorbis/init.luau +++ b/src/Formats/audio/vorbis/init.luau @@ -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", diff --git a/src/Formats/audio/wav/init.luau b/src/Formats/audio/wav/init.luau index 1c1f60b..cf5e65c 100644 --- a/src/Formats/audio/wav/init.luau +++ b/src/Formats/audio/wav/init.luau @@ -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 }, } diff --git a/src/Formats/codecs/RangeCoder/init.luau b/src/Formats/codecs/RangeCoder/init.luau deleted file mode 100644 index 6affd3e..0000000 --- a/src/Formats/codecs/RangeCoder/init.luau +++ /dev/null @@ -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 diff --git a/src/Formats/codecs/Aac/Decode.luau b/src/Formats/codecs/audio/Aac/Decode.luau similarity index 98% rename from src/Formats/codecs/Aac/Decode.luau rename to src/Formats/codecs/audio/Aac/Decode.luau index 48ec969..fc51318 100644 --- a/src/Formats/codecs/Aac/Decode.luau +++ b/src/Formats/codecs/audio/Aac/Decode.luau @@ -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 diff --git a/src/Formats/codecs/Aac/Tables.luau b/src/Formats/codecs/audio/Aac/Tables.luau similarity index 99% rename from src/Formats/codecs/Aac/Tables.luau rename to src/Formats/codecs/audio/Aac/Tables.luau index 65305fb..71bf6bc 100644 --- a/src/Formats/codecs/Aac/Tables.luau +++ b/src/Formats/codecs/audio/Aac/Tables.luau @@ -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. diff --git a/src/Formats/codecs/Aac/init.luau b/src/Formats/codecs/audio/Aac/init.luau similarity index 95% rename from src/Formats/codecs/Aac/init.luau rename to src/Formats/codecs/audio/Aac/init.luau index 15e586e..f6066fb 100644 --- a/src/Formats/codecs/Aac/init.luau +++ b/src/Formats/codecs/audio/Aac/init.luau @@ -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 = {} diff --git a/src/Formats/codecs/Alac/Decode.luau b/src/Formats/codecs/audio/Alac/Decode.luau similarity index 98% rename from src/Formats/codecs/Alac/Decode.luau rename to src/Formats/codecs/audio/Alac/Decode.luau index 4b0a71c..031613a 100644 --- a/src/Formats/codecs/Alac/Decode.luau +++ b/src/Formats/codecs/audio/Alac/Decode.luau @@ -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. diff --git a/src/Formats/codecs/Alac/Encode.luau b/src/Formats/codecs/audio/Alac/Encode.luau similarity index 98% rename from src/Formats/codecs/Alac/Encode.luau rename to src/Formats/codecs/audio/Alac/Encode.luau index 4309bd5..2543e77 100644 --- a/src/Formats/codecs/Alac/Encode.luau +++ b/src/Formats/codecs/audio/Alac/Encode.luau @@ -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 diff --git a/src/Formats/codecs/Alac/init.luau b/src/Formats/codecs/audio/Alac/init.luau similarity index 96% rename from src/Formats/codecs/Alac/init.luau rename to src/Formats/codecs/audio/Alac/init.luau index 7af082b..302d6b5 100644 --- a/src/Formats/codecs/Alac/init.luau +++ b/src/Formats/codecs/audio/Alac/init.luau @@ -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 = {} diff --git a/src/Formats/codecs/Mdct/Fft.luau b/src/Formats/codecs/audio/Mdct/Fft.luau similarity index 98% rename from src/Formats/codecs/Mdct/Fft.luau rename to src/Formats/codecs/audio/Mdct/Fft.luau index b4900df..a995706 100644 --- a/src/Formats/codecs/Mdct/Fft.luau +++ b/src/Formats/codecs/audio/Mdct/Fft.luau @@ -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. diff --git a/src/Formats/codecs/Mdct/init.luau b/src/Formats/codecs/audio/Mdct/init.luau similarity index 94% rename from src/Formats/codecs/Mdct/init.luau rename to src/Formats/codecs/audio/Mdct/init.luau index 316bc21..0713427 100644 --- a/src/Formats/codecs/Mdct/init.luau +++ b/src/Formats/codecs/audio/Mdct/init.luau @@ -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 diff --git a/src/Formats/codecs/Pcm/Convert.luau b/src/Formats/codecs/audio/Pcm/Convert.luau similarity index 98% rename from src/Formats/codecs/Pcm/Convert.luau rename to src/Formats/codecs/audio/Pcm/Convert.luau index 5d88d6e..3d15128 100644 --- a/src/Formats/codecs/Pcm/Convert.luau +++ b/src/Formats/codecs/audio/Pcm/Convert.luau @@ -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). -- diff --git a/src/Formats/codecs/Pcm/init.luau b/src/Formats/codecs/audio/Pcm/init.luau similarity index 97% rename from src/Formats/codecs/Pcm/init.luau rename to src/Formats/codecs/audio/Pcm/init.luau index 6faadec..3b8118c 100644 --- a/src/Formats/codecs/Pcm/init.luau +++ b/src/Formats/codecs/audio/Pcm/init.luau @@ -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 diff --git a/src/Formats/codecs/Resample/init.luau b/src/Formats/codecs/audio/Resample/init.luau similarity index 98% rename from src/Formats/codecs/Resample/init.luau rename to src/Formats/codecs/audio/Resample/init.luau index 1096060..a2e636b 100644 --- a/src/Formats/codecs/Resample/init.luau +++ b/src/Formats/codecs/audio/Resample/init.luau @@ -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 diff --git a/src/Formats/codecs/SoundFont/Fallback.luau b/src/Formats/codecs/audio/SoundFont/Fallback.luau similarity index 97% rename from src/Formats/codecs/SoundFont/Fallback.luau rename to src/Formats/codecs/audio/SoundFont/Fallback.luau index ae8f8ca..2df195d 100644 --- a/src/Formats/codecs/SoundFont/Fallback.luau +++ b/src/Formats/codecs/audio/SoundFont/Fallback.luau @@ -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 = {} diff --git a/src/Formats/codecs/SoundFont/Parse.luau b/src/Formats/codecs/audio/SoundFont/Parse.luau similarity index 99% rename from src/Formats/codecs/SoundFont/Parse.luau rename to src/Formats/codecs/audio/SoundFont/Parse.luau index df39807..aab2b5f 100644 --- a/src/Formats/codecs/SoundFont/Parse.luau +++ b/src/Formats/codecs/audio/SoundFont/Parse.luau @@ -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) diff --git a/src/Formats/codecs/SoundFont/Synth.luau b/src/Formats/codecs/audio/SoundFont/Synth.luau similarity index 99% rename from src/Formats/codecs/SoundFont/Synth.luau rename to src/Formats/codecs/audio/SoundFont/Synth.luau index c133423..d868f0c 100644 --- a/src/Formats/codecs/SoundFont/Synth.luau +++ b/src/Formats/codecs/audio/SoundFont/Synth.luau @@ -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 diff --git a/src/Formats/codecs/SoundFont/init.luau b/src/Formats/codecs/audio/SoundFont/init.luau similarity index 87% rename from src/Formats/codecs/SoundFont/init.luau rename to src/Formats/codecs/audio/SoundFont/init.luau index a1c8feb..e3c2a9d 100644 --- a/src/Formats/codecs/SoundFont/init.luau +++ b/src/Formats/codecs/audio/SoundFont/init.luau @@ -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 = {} diff --git a/src/Formats/codecs/audio/Stream.luau b/src/Formats/codecs/audio/Stream.luau new file mode 100644 index 0000000..ef69611 --- /dev/null +++ b/src/Formats/codecs/audio/Stream.luau @@ -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 diff --git a/src/Formats/codecs/Tracker/Mixer.luau b/src/Formats/codecs/audio/Tracker/Mixer.luau similarity index 95% rename from src/Formats/codecs/Tracker/Mixer.luau rename to src/Formats/codecs/audio/Tracker/Mixer.luau index 193a034..9cedf6b 100644 --- a/src/Formats/codecs/Tracker/Mixer.luau +++ b/src/Formats/codecs/audio/Tracker/Mixer.luau @@ -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 diff --git a/src/Formats/codecs/Tracker/Pcm.luau b/src/Formats/codecs/audio/Tracker/Pcm.luau similarity index 96% rename from src/Formats/codecs/Tracker/Pcm.luau rename to src/Formats/codecs/audio/Tracker/Pcm.luau index 30c59c8..cdbc496 100644 --- a/src/Formats/codecs/Tracker/Pcm.luau +++ b/src/Formats/codecs/audio/Tracker/Pcm.luau @@ -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). diff --git a/src/Formats/codecs/Tracker/Player.luau b/src/Formats/codecs/audio/Tracker/Player.luau similarity index 99% rename from src/Formats/codecs/Tracker/Player.luau rename to src/Formats/codecs/audio/Tracker/Player.luau index 84d2079..62df8b3 100644 --- a/src/Formats/codecs/Tracker/Player.luau +++ b/src/Formats/codecs/audio/Tracker/Player.luau @@ -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 diff --git a/src/Formats/codecs/Tracker/Tables.luau b/src/Formats/codecs/audio/Tracker/Tables.luau similarity index 97% rename from src/Formats/codecs/Tracker/Tables.luau rename to src/Formats/codecs/audio/Tracker/Tables.luau index c621ec1..90e78d8 100644 --- a/src/Formats/codecs/Tracker/Tables.luau +++ b/src/Formats/codecs/audio/Tracker/Tables.luau @@ -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). diff --git a/src/Formats/codecs/Tracker/init.luau b/src/Formats/codecs/audio/Tracker/init.luau similarity index 97% rename from src/Formats/codecs/Tracker/init.luau rename to src/Formats/codecs/audio/Tracker/init.luau index 391ea94..55056f6 100644 --- a/src/Formats/codecs/Tracker/init.luau +++ b/src/Formats/codecs/audio/Tracker/init.luau @@ -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 = {} diff --git a/src/Formats/codecs/VorbisComment.luau b/src/Formats/codecs/audio/VorbisComment.luau similarity index 93% rename from src/Formats/codecs/VorbisComment.luau rename to src/Formats/codecs/audio/VorbisComment.luau index 118be05..74ca09e 100644 --- a/src/Formats/codecs/VorbisComment.luau +++ b/src/Formats/codecs/audio/VorbisComment.luau @@ -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 diff --git a/src/Formats/codecs/Brotli/Decode.luau b/src/Formats/codecs/compress/Brotli/Decode.luau similarity index 99% rename from src/Formats/codecs/Brotli/Decode.luau rename to src/Formats/codecs/compress/Brotli/Decode.luau index e17e7d8..08f7705 100644 --- a/src/Formats/codecs/Brotli/Decode.luau +++ b/src/Formats/codecs/compress/Brotli/Decode.luau @@ -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 diff --git a/src/Formats/codecs/Brotli/Static.luau b/src/Formats/codecs/compress/Brotli/Static.luau similarity index 99% rename from src/Formats/codecs/Brotli/Static.luau rename to src/Formats/codecs/compress/Brotli/Static.luau index d9170fa..6cd704d 100644 --- a/src/Formats/codecs/Brotli/Static.luau +++ b/src/Formats/codecs/compress/Brotli/Static.luau @@ -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 { diff --git a/src/Formats/codecs/Brotli/init.luau b/src/Formats/codecs/compress/Brotli/init.luau similarity index 86% rename from src/Formats/codecs/Brotli/init.luau rename to src/Formats/codecs/compress/Brotli/init.luau index 9d50131..eebd8db 100644 --- a/src/Formats/codecs/Brotli/init.luau +++ b/src/Formats/codecs/compress/Brotli/init.luau @@ -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 = {} diff --git a/src/Formats/codecs/Bzip2/Decode.luau b/src/Formats/codecs/compress/Bzip2/Decode.luau similarity index 99% rename from src/Formats/codecs/Bzip2/Decode.luau rename to src/Formats/codecs/compress/Bzip2/Decode.luau index 720973d..873bd19 100644 --- a/src/Formats/codecs/Bzip2/Decode.luau +++ b/src/Formats/codecs/compress/Bzip2/Decode.luau @@ -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 diff --git a/src/Formats/codecs/Bzip2/init.luau b/src/Formats/codecs/compress/Bzip2/init.luau similarity index 89% rename from src/Formats/codecs/Bzip2/init.luau rename to src/Formats/codecs/compress/Bzip2/init.luau index 86c72db..00d903e 100644 --- a/src/Formats/codecs/Bzip2/init.luau +++ b/src/Formats/codecs/compress/Bzip2/init.luau @@ -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 = {} diff --git a/src/Formats/codecs/Deflate/Compress.luau b/src/Formats/codecs/compress/Deflate/Compress.luau similarity index 97% rename from src/Formats/codecs/Deflate/Compress.luau rename to src/Formats/codecs/compress/Deflate/Compress.luau index d5d508f..f3c60f6 100644 --- a/src/Formats/codecs/Deflate/Compress.luau +++ b/src/Formats/codecs/compress/Deflate/Compress.luau @@ -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 diff --git a/src/Formats/codecs/Deflate/Inflate.luau b/src/Formats/codecs/compress/Deflate/Inflate.luau similarity index 97% rename from src/Formats/codecs/Deflate/Inflate.luau rename to src/Formats/codecs/compress/Deflate/Inflate.luau index ab9a237..449e1db 100644 --- a/src/Formats/codecs/Deflate/Inflate.luau +++ b/src/Formats/codecs/compress/Deflate/Inflate.luau @@ -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 diff --git a/src/Formats/codecs/Deflate/init.luau b/src/Formats/codecs/compress/Deflate/init.luau similarity index 96% rename from src/Formats/codecs/Deflate/init.luau rename to src/Formats/codecs/compress/Deflate/init.luau index 8308056..37a529b 100644 --- a/src/Formats/codecs/Deflate/init.luau +++ b/src/Formats/codecs/compress/Deflate/init.luau @@ -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 = {} diff --git a/src/Formats/codecs/Lzma/Crc64.luau b/src/Formats/codecs/compress/Lzma/Crc64.luau similarity index 89% rename from src/Formats/codecs/Lzma/Crc64.luau rename to src/Formats/codecs/compress/Lzma/Crc64.luau index 19f682f..bd39f30 100644 --- a/src/Formats/codecs/Lzma/Crc64.luau +++ b/src/Formats/codecs/compress/Lzma/Crc64.luau @@ -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 diff --git a/src/Formats/codecs/Lzma/Decode.luau b/src/Formats/codecs/compress/Lzma/Decode.luau similarity index 98% rename from src/Formats/codecs/Lzma/Decode.luau rename to src/Formats/codecs/compress/Lzma/Decode.luau index 51be654..dfbb956 100644 --- a/src/Formats/codecs/Lzma/Decode.luau +++ b/src/Formats/codecs/compress/Lzma/Decode.luau @@ -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. -- diff --git a/src/Formats/codecs/Lzma/Filters.luau b/src/Formats/codecs/compress/Lzma/Filters.luau similarity index 97% rename from src/Formats/codecs/Lzma/Filters.luau rename to src/Formats/codecs/compress/Lzma/Filters.luau index 60a5d59..5cc2e2f 100644 --- a/src/Formats/codecs/Lzma/Filters.luau +++ b/src/Formats/codecs/compress/Lzma/Filters.luau @@ -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). diff --git a/src/Formats/codecs/Lzma/init.luau b/src/Formats/codecs/compress/Lzma/init.luau similarity index 98% rename from src/Formats/codecs/Lzma/init.luau rename to src/Formats/codecs/compress/Lzma/init.luau index f160319..667b2ad 100644 --- a/src/Formats/codecs/Lzma/init.luau +++ b/src/Formats/codecs/compress/Lzma/init.luau @@ -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 diff --git a/src/Formats/codecs/Lzw/init.luau b/src/Formats/codecs/compress/Lzw/init.luau similarity index 98% rename from src/Formats/codecs/Lzw/init.luau rename to src/Formats/codecs/compress/Lzw/init.luau index 168ded4..a399b9f 100644 --- a/src/Formats/codecs/Lzw/init.luau +++ b/src/Formats/codecs/compress/Lzw/init.luau @@ -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). diff --git a/src/Formats/codecs/Zstd/Decode.luau b/src/Formats/codecs/compress/Zstd/Decode.luau similarity index 99% rename from src/Formats/codecs/Zstd/Decode.luau rename to src/Formats/codecs/compress/Zstd/Decode.luau index 7ad77d5..71961f8 100644 --- a/src/Formats/codecs/Zstd/Decode.luau +++ b/src/Formats/codecs/compress/Zstd/Decode.luau @@ -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 diff --git a/src/Formats/codecs/Zstd/Xxh64.luau b/src/Formats/codecs/compress/Zstd/Xxh64.luau similarity index 97% rename from src/Formats/codecs/Zstd/Xxh64.luau rename to src/Formats/codecs/compress/Zstd/Xxh64.luau index c189970..7e29fec 100644 --- a/src/Formats/codecs/Zstd/Xxh64.luau +++ b/src/Formats/codecs/compress/Zstd/Xxh64.luau @@ -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). diff --git a/src/Formats/codecs/Zstd/init.luau b/src/Formats/codecs/compress/Zstd/init.luau similarity index 92% rename from src/Formats/codecs/Zstd/init.luau rename to src/Formats/codecs/compress/Zstd/init.luau index 2d9cb04..a7a3e7b 100644 --- a/src/Formats/codecs/Zstd/init.luau +++ b/src/Formats/codecs/compress/Zstd/init.luau @@ -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 = {} diff --git a/src/Formats/core/Huffman.luau b/src/Formats/codecs/entropy/Huffman.luau similarity index 97% rename from src/Formats/core/Huffman.luau rename to src/Formats/codecs/entropy/Huffman.luau index 5d200d8..4e2243c 100644 --- a/src/Formats/core/Huffman.luau +++ b/src/Formats/codecs/entropy/Huffman.luau @@ -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. diff --git a/src/Formats/codecs/RangeCoder/Decoder.luau b/src/Formats/codecs/entropy/RangeCoder/Decoder.luau similarity index 97% rename from src/Formats/codecs/RangeCoder/Decoder.luau rename to src/Formats/codecs/entropy/RangeCoder/Decoder.luau index 2c64ec3..6073941 100644 --- a/src/Formats/codecs/RangeCoder/Decoder.luau +++ b/src/Formats/codecs/entropy/RangeCoder/Decoder.luau @@ -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. diff --git a/src/Formats/codecs/RangeCoder/Encoder.luau b/src/Formats/codecs/entropy/RangeCoder/Encoder.luau similarity index 95% rename from src/Formats/codecs/RangeCoder/Encoder.luau rename to src/Formats/codecs/entropy/RangeCoder/Encoder.luau index 05e9815..0ddb202 100644 --- a/src/Formats/codecs/RangeCoder/Encoder.luau +++ b/src/Formats/codecs/entropy/RangeCoder/Encoder.luau @@ -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 = {} diff --git a/src/Formats/codecs/entropy/RangeCoder/init.luau b/src/Formats/codecs/entropy/RangeCoder/init.luau new file mode 100644 index 0000000..de65aa5 --- /dev/null +++ b/src/Formats/codecs/entropy/RangeCoder/init.luau @@ -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 diff --git a/src/Formats/codecs/Cff/init.luau b/src/Formats/codecs/font/Cff/init.luau similarity index 99% rename from src/Formats/codecs/Cff/init.luau rename to src/Formats/codecs/font/Cff/init.luau index 48d855a..a4cebb6 100644 --- a/src/Formats/codecs/Cff/init.luau +++ b/src/Formats/codecs/font/Cff/init.luau @@ -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 diff --git a/src/Formats/codecs/TrueType/Glyf.luau b/src/Formats/codecs/font/TrueType/Glyf.luau similarity index 97% rename from src/Formats/codecs/TrueType/Glyf.luau rename to src/Formats/codecs/font/TrueType/Glyf.luau index 5d598a9..ce08e9f 100644 --- a/src/Formats/codecs/TrueType/Glyf.luau +++ b/src/Formats/codecs/font/TrueType/Glyf.luau @@ -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 diff --git a/src/Formats/codecs/TrueType/Tables.luau b/src/Formats/codecs/font/TrueType/Tables.luau similarity index 99% rename from src/Formats/codecs/TrueType/Tables.luau rename to src/Formats/codecs/font/TrueType/Tables.luau index 7287007..9086053 100644 --- a/src/Formats/codecs/TrueType/Tables.luau +++ b/src/Formats/codecs/font/TrueType/Tables.luau @@ -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 diff --git a/src/Formats/codecs/TrueType/init.luau b/src/Formats/codecs/font/TrueType/init.luau similarity index 94% rename from src/Formats/codecs/TrueType/init.luau rename to src/Formats/codecs/font/TrueType/init.luau index 3752c3f..b3584fd 100644 --- a/src/Formats/codecs/TrueType/init.luau +++ b/src/Formats/codecs/font/TrueType/init.luau @@ -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 = {} diff --git a/src/Formats/codecs/Blend.luau b/src/Formats/codecs/image/Blend.luau similarity index 99% rename from src/Formats/codecs/Blend.luau rename to src/Formats/codecs/image/Blend.luau index d8b2f6a..162ec6f 100644 --- a/src/Formats/codecs/Blend.luau +++ b/src/Formats/codecs/image/Blend.luau @@ -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. diff --git a/src/Formats/codecs/Dct/init.luau b/src/Formats/codecs/image/Dct/init.luau similarity index 99% rename from src/Formats/codecs/Dct/init.luau rename to src/Formats/codecs/image/Dct/init.luau index cb643bb..b84aed6 100644 --- a/src/Formats/codecs/Dct/init.luau +++ b/src/Formats/codecs/image/Dct/init.luau @@ -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). diff --git a/src/Formats/codecs/Jpeg/Arith.luau b/src/Formats/codecs/image/Jpeg/Arith.luau similarity index 98% rename from src/Formats/codecs/Jpeg/Arith.luau rename to src/Formats/codecs/image/Jpeg/Arith.luau index 984c8a5..4dcf84f 100644 --- a/src/Formats/codecs/Jpeg/Arith.luau +++ b/src/Formats/codecs/image/Jpeg/Arith.luau @@ -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. -- diff --git a/src/Formats/codecs/Jpeg/Color.luau b/src/Formats/codecs/image/Jpeg/Color.luau similarity index 98% rename from src/Formats/codecs/Jpeg/Color.luau rename to src/Formats/codecs/image/Jpeg/Color.luau index 46e1cf8..86e7d13 100644 --- a/src/Formats/codecs/Jpeg/Color.luau +++ b/src/Formats/codecs/image/Jpeg/Color.luau @@ -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). -- diff --git a/src/Formats/codecs/Jpeg/Decode.luau b/src/Formats/codecs/image/Jpeg/Decode.luau similarity index 97% rename from src/Formats/codecs/Jpeg/Decode.luau rename to src/Formats/codecs/image/Jpeg/Decode.luau index 833e66f..efb1a64 100644 --- a/src/Formats/codecs/Jpeg/Decode.luau +++ b/src/Formats/codecs/image/Jpeg/Decode.luau @@ -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 diff --git a/src/Formats/codecs/Jpeg/Encode.luau b/src/Formats/codecs/image/Jpeg/Encode.luau similarity index 98% rename from src/Formats/codecs/Jpeg/Encode.luau rename to src/Formats/codecs/image/Jpeg/Encode.luau index 49e003e..4c0ef60 100644 --- a/src/Formats/codecs/Jpeg/Encode.luau +++ b/src/Formats/codecs/image/Jpeg/Encode.luau @@ -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 diff --git a/src/Formats/codecs/Jpeg/Scan.luau b/src/Formats/codecs/image/Jpeg/Scan.luau similarity index 99% rename from src/Formats/codecs/Jpeg/Scan.luau rename to src/Formats/codecs/image/Jpeg/Scan.luau index f8f62eb..fe5a3d9 100644 --- a/src/Formats/codecs/Jpeg/Scan.luau +++ b/src/Formats/codecs/image/Jpeg/Scan.luau @@ -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, diff --git a/src/Formats/codecs/Jpeg/Tables.luau b/src/Formats/codecs/image/Jpeg/Tables.luau similarity index 96% rename from src/Formats/codecs/Jpeg/Tables.luau rename to src/Formats/codecs/image/Jpeg/Tables.luau index 9e9c4df..35c5af6 100644 --- a/src/Formats/codecs/Jpeg/Tables.luau +++ b/src/Formats/codecs/image/Jpeg/Tables.luau @@ -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 = {} diff --git a/src/Formats/codecs/Jpeg/Yuv.luau b/src/Formats/codecs/image/Jpeg/Yuv.luau similarity index 92% rename from src/Formats/codecs/Jpeg/Yuv.luau rename to src/Formats/codecs/image/Jpeg/Yuv.luau index edb2778..b9b0925 100644 --- a/src/Formats/codecs/Jpeg/Yuv.luau +++ b/src/Formats/codecs/image/Jpeg/Yuv.luau @@ -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 = {} diff --git a/src/Formats/codecs/Jpeg/init.luau b/src/Formats/codecs/image/Jpeg/init.luau similarity index 97% rename from src/Formats/codecs/Jpeg/init.luau rename to src/Formats/codecs/image/Jpeg/init.luau index de75b4c..32710ae 100644 --- a/src/Formats/codecs/Jpeg/init.luau +++ b/src/Formats/codecs/image/Jpeg/init.luau @@ -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 = {} diff --git a/src/Formats/image/bmp/Pixels.luau b/src/Formats/codecs/image/Pixels.luau similarity index 84% rename from src/Formats/image/bmp/Pixels.luau rename to src/Formats/codecs/image/Pixels.luau index 331b198..49cd14f 100644 --- a/src/Formats/image/bmp/Pixels.luau +++ b/src/Formats/codecs/image/Pixels.luau @@ -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 diff --git a/src/Formats/codecs/Quantize/init.luau b/src/Formats/codecs/image/Quantize/init.luau similarity index 99% rename from src/Formats/codecs/Quantize/init.luau rename to src/Formats/codecs/image/Quantize/init.luau index 3086d63..b9edac5 100644 --- a/src/Formats/codecs/Quantize/init.luau +++ b/src/Formats/codecs/image/Quantize/init.luau @@ -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 diff --git a/src/Formats/codecs/Raster.luau b/src/Formats/codecs/image/Raster.luau similarity index 99% rename from src/Formats/codecs/Raster.luau rename to src/Formats/codecs/image/Raster.luau index ba93fda..6f9be0d 100644 --- a/src/Formats/codecs/Raster.luau +++ b/src/Formats/codecs/image/Raster.luau @@ -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) diff --git a/src/Formats/codecs/Vp8/Decode.luau b/src/Formats/codecs/image/Vp8/Decode.luau similarity index 99% rename from src/Formats/codecs/Vp8/Decode.luau rename to src/Formats/codecs/image/Vp8/Decode.luau index 88f5652..b51d8b2 100644 --- a/src/Formats/codecs/Vp8/Decode.luau +++ b/src/Formats/codecs/image/Vp8/Decode.luau @@ -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 diff --git a/src/Formats/codecs/Vp8/Predict.luau b/src/Formats/codecs/image/Vp8/Predict.luau similarity index 97% rename from src/Formats/codecs/Vp8/Predict.luau rename to src/Formats/codecs/image/Vp8/Predict.luau index 536ddea..c6f4de8 100644 --- a/src/Formats/codecs/Vp8/Predict.luau +++ b/src/Formats/codecs/image/Vp8/Predict.luau @@ -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 diff --git a/src/Formats/codecs/Vp8/Tables.luau b/src/Formats/codecs/image/Vp8/Tables.luau similarity index 99% rename from src/Formats/codecs/Vp8/Tables.luau rename to src/Formats/codecs/image/Vp8/Tables.luau index 21dc1cf..7bbdb4a 100644 --- a/src/Formats/codecs/Vp8/Tables.luau +++ b/src/Formats/codecs/image/Vp8/Tables.luau @@ -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; diff --git a/src/Formats/codecs/Vp8/Yuv.luau b/src/Formats/codecs/image/Vp8/Yuv.luau similarity index 97% rename from src/Formats/codecs/Vp8/Yuv.luau rename to src/Formats/codecs/image/Vp8/Yuv.luau index 5668738..720fe65 100644 --- a/src/Formats/codecs/Vp8/Yuv.luau +++ b/src/Formats/codecs/image/Vp8/Yuv.luau @@ -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). diff --git a/src/Formats/codecs/Vp8/init.luau b/src/Formats/codecs/image/Vp8/init.luau similarity index 96% rename from src/Formats/codecs/Vp8/init.luau rename to src/Formats/codecs/image/Vp8/init.luau index d9a6f2a..bfff1b1 100644 --- a/src/Formats/codecs/Vp8/init.luau +++ b/src/Formats/codecs/image/Vp8/init.luau @@ -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 = {} diff --git a/src/Formats/codecs/Vp8L/Decode.luau b/src/Formats/codecs/image/Vp8L/Decode.luau similarity index 99% rename from src/Formats/codecs/Vp8L/Decode.luau rename to src/Formats/codecs/image/Vp8L/Decode.luau index 547167c..a8b202c 100644 --- a/src/Formats/codecs/Vp8L/Decode.luau +++ b/src/Formats/codecs/image/Vp8L/Decode.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder: prefix codes (two-level tables), meta prefix codes, +-- codecs/image/Vp8L/Decode: the WebP lossless (VP8L) bitstream decoder: prefix codes (two-level tables), meta prefix codes, -- LZ77 backward references with the 2-D distance map, the colour cache, and the four inverse transforms (predictor, -- cross colour, subtract green, colour indexing with pixel bundling). A port of libwebp 1.6 src/dec/vp8l_dec.c, -- src/utils/huffman_utils.c and src/dsp/lossless.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt); bit-exact with it. diff --git a/src/Formats/codecs/Vp8L/Encode.luau b/src/Formats/codecs/image/Vp8L/Encode.luau similarity index 99% rename from src/Formats/codecs/Vp8L/Encode.luau rename to src/Formats/codecs/image/Vp8L/Encode.luau index 1eff41a..9f15934 100644 --- a/src/Formats/codecs/Vp8L/Encode.luau +++ b/src/Formats/codecs/image/Vp8L/Encode.luau @@ -1,13 +1,13 @@ --!strict --!native --!optimize 2 --- codecs/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from the specification (RFC 9649 section 3). +-- codecs/image/Vp8L/Encode: a WebP lossless (VP8L) encoder, new code written from the specification (RFC 9649 section 3). -- Transforms: colour indexing with pixel bundling (<= 256 colours), else subtract green + predictor (per-tile mode -- chosen from a residual cost) + cross colour (per-tile least-squares multipliers). Entropy coding: LZ77 with hash -- chains, the left / up run candidates and the 2-D distance codes, a colour cache whose size is chosen by an entropy --- estimate, one prefix code group per image, code lengths limited to 15 bits (core/Huffman) and run-length coded. +-- estimate, one prefix code group per image, code lengths limited to 15 bits (codecs/entropy/Huffman) and run-length coded. -- Never throws (the init module validates the arguments). -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 readu32, writeu8, writeu32 = buffer.readu32, buffer.writeu8, buffer.writeu32 @@ -143,7 +143,7 @@ local function half(x: number, y: number): number return clip255(x + (if dd >= 0 then rshift(dd, 1) else -rshift(-dd, 1))) end --- predict(mode, L, T, TR, TL): the decoder's predictors (codecs/Vp8L/Decode) +-- predict(mode, L, T, TR, TL): the decoder's predictors (codecs/image/Vp8L/Decode) local function predict(mode: number, L: number, T: number, TR: number, TL: number): number if mode == 1 then return L diff --git a/src/Formats/codecs/Vp8L/init.luau b/src/Formats/codecs/image/Vp8L/init.luau similarity index 94% rename from src/Formats/codecs/Vp8L/init.luau rename to src/Formats/codecs/image/Vp8L/init.luau index d35d7e1..1edd539 100644 --- a/src/Formats/codecs/Vp8L/init.luau +++ b/src/Formats/codecs/image/Vp8L/init.luau @@ -1,20 +1,20 @@ --!strict --- codecs/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): +-- codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): -- image/webp uses it for VP8L frames and for compressed ALPH planes; other containers may carry it too. -- Decoder: a port of libwebp 1.6 (BSD-3-Clause, licenses/libwebp-LICENSE.txt), bit-exact with it. Encoder: new -- (subtract green, predictor and cross-colour transforms with per-tile mode search, colour indexing with pixel -- bundling for <= 256 colours, LZ77 with hash chains and the 2-D distance codes, a colour cache chosen by entropy, -- one prefix code group per image or meta codes for big images). -- --- local Vp8L = require("@formats/codecs/Vp8L") +-- local Vp8L = require("@formats/codecs/image/Vp8L") -- local rgba, w, h, alpha = Vp8L.decode(buf, off, len) -- a VP8L bitstream (0x2f signature) -> rgba8 -- local a8 = Vp8L.decodeAlpha(buf, off, len, w, h) -- a headerless stream's green channel (ALPH) -- local bits = Vp8L.encode(rgba, w, h, { effort = 4 }) -- rgba8 -> a VP8L bitstream -- -- Never throws: bad data returns nil, Err (core/Err codes TRUNCATED / CORRUPT / LIMIT / ARG). local Err = require("@formats/core/Err") -local Decode = require("@formats/codecs/Vp8L/Decode") -local Encode = require("@formats/codecs/Vp8L/Encode") +local Decode = require("@formats/codecs/image/Vp8L/Decode") +local Encode = require("@formats/codecs/image/Vp8L/Encode") local Vp8L = {} diff --git a/src/Formats/codecs/Yuv.luau b/src/Formats/codecs/image/Yuv.luau similarity index 98% rename from src/Formats/codecs/Yuv.luau rename to src/Formats/codecs/image/Yuv.luau index cfa8258..fe331ee 100644 --- a/src/Formats/codecs/Yuv.luau +++ b/src/Formats/codecs/image/Yuv.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or +-- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or -- BT.709 matrices, limited ("tv", 16..235 / 16..240: VP8, MPEG-1, H.264) or full ("pc", 0..255: MJPEG / JPEG) range. -- yuv -> rgb uses nearest chroma and 16-bit fixed point with swscale's default (non-accurate) coefficients, so the -- result is within about one level of `ffmpeg -pix_fmt rgba`; rgb -> yuv averages each 2x2 block for the chroma diff --git a/src/Formats/codecs/model/Mat4.luau b/src/Formats/codecs/model/Mat4.luau new file mode 100644 index 0000000..59b63ff --- /dev/null +++ b/src/Formats/codecs/model/Mat4.luau @@ -0,0 +1,282 @@ +--!strict +-- codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 +-- (glTF / FBX / Types.Scene layout: translation at 13..15), quaternions { x, y, z, w }, angles in degrees where a +-- format stores degrees. Shared by FBX, Collada, USD and MeshOps instead of a copy in each. New in formats-luau (the +-- functions come from the former model/fbx/Xform, model/dae/Math and model/usda/Build helpers). +-- +-- local m = Mat4.compose({ 1, 2, 3 }, quat, { 2, 2, 2 }) -- T * R * S +-- local t, r, s = Mat4.decompose(m) -- (decomposeStrict: nil for shear / projective / singular) +-- local w = Mat4.mul(parent, m) -- = Types.Scene.mul +-- local inv = Mat4.inverse(m) -- affine inverse | nil +-- local x, y, z = Mat4.point(m, px, py, pz) +local Types = require("@formats/Types") + +local Mat4 = {} + +export type M4 = { number } + +local sqrt, abs, sin, cos, rad = math.sqrt, math.abs, math.sin, math.cos, math.rad + +function Mat4.identity(): M4 + return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } +end + +-- mul(a, b) -> a * b +Mat4.mul = Types.Scene.mul + +function Mat4.translation(x: number, y: number, z: number): M4 + return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } +end + +function Mat4.scaling(x: number, y: number, z: number): M4 + return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } +end + +-- rotation(axis, degrees) -> the rotation about axis 1 (X), 2 (Y) or 3 (Z) +function Mat4.rotation(axis: number, degrees: number): M4 + local a = rad(degrees) + local c, s = cos(a), sin(a) + if axis == 1 then + return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 } + elseif axis == 2 then + return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 } + end + return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } +end + +local AXIS = { x = 1, y = 2, z = 3 } +-- euler(x, y, z, order?) -> the rotation applying the axes in order (default "xyz": R = Rz * Ry * Rx), degrees +function Mat4.euler(x: number, y: number, z: number, order: string?): M4 + local o = order or "xyz" + local deg = { x = x, y = y, z = z } + local m = Mat4.identity() + for i = 1, 3 do + local a = string.sub(o, i, i) + m = Mat4.mul(Mat4.rotation(AXIS[a] or i, deg[a] or 0), m) + end + return m +end + +-- axisAngle(x, y, z, degrees) -> quaternion +function Mat4.axisAngle(x: number, y: number, z: number, degrees: number): { number } + local l = sqrt(x * x + y * y + z * z) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + local h = rad(degrees) / 2 + local s = sin(h) / l + return { x * s, y * s, z * s, cos(h) } +end + +-- fromQuat(q) -> the rotation matrix of a quaternion +function Mat4.fromQuat(q: { number }): M4 + local x, y, z, w = q[1], q[2], q[3], q[4] + local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z + return { + 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0, + 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0, + 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0, + 0, 0, 0, 1, + } +end + +-- quat(m) -> the unit quaternion of the rotation in m's upper 3x3 (columns assumed orthonormal) +function Mat4.quat(m: M4): { number } + local m00, m01, m02 = m[1], m[5], m[9] + local m10, m11, m12 = m[2], m[6], m[10] + local m20, m21, m22 = m[3], m[7], m[11] + local tr = m00 + m11 + m22 + local x, y, z, w + if tr > 0 then + local s = sqrt(tr + 1) * 2 + w, x, y, z = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s + elseif m00 > m11 and m00 > m22 then + local s = sqrt(math.max(1 + m00 - m11 - m22, 1e-30)) * 2 + w, x, y, z = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s + elseif m11 > m22 then + local s = sqrt(math.max(1 + m11 - m00 - m22, 1e-30)) * 2 + w, x, y, z = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s + else + local s = sqrt(math.max(1 + m22 - m00 - m11, 1e-30)) * 2 + w, x, y, z = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4 + end + local n = sqrt(x * x + y * y + z * z + w * w) + if n == 0 or n ~= n then + return { 0, 0, 0, 1 } + end + return { x / n, y / n, z / n, w / n } +end + +-- eulerXYZ(q) -> Euler XYZ degrees (R = Rz * Ry * Rx) of a quaternion +function Mat4.eulerXYZ(q: { number }): { number } + local m = Mat4.fromQuat(q) + local sy = math.clamp(-m[3], -1, 1) -- m[3] = r20 = -sin(y) + local y = math.asin(sy) + local x, z + if abs(sy) < 0.9999999 then + x = math.atan2(m[7], m[11]) + z = math.atan2(m[2], m[1]) + else + x = math.atan2(-m[10], m[6]) + z = 0 + end + return { math.deg(x), math.deg(y), math.deg(z) } +end + +-- compose(t?, r?, s?) -> T * R * S (glTF node semantics) +function Mat4.compose(t: { number }?, r: { number }?, s: { number }?): M4 + local m = if r then Mat4.fromQuat(r) else Mat4.identity() + if s then + for k = 0, 2 do + m[k * 4 + 1] *= s[k + 1] + m[k * 4 + 2] *= s[k + 1] + m[k * 4 + 3] *= s[k + 1] + end + end + if t then + m[13], m[14], m[15] = t[1], t[2], t[3] + end + return m +end + +local function det3(m: M4): number + return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3]) +end + +local function split(m: M4, strict: boolean): ({ number }?, { number }?, { number }?) + if strict and (abs(m[4]) > 1e-6 or abs(m[8]) > 1e-6 or abs(m[12]) > 1e-6 or abs(m[16] - 1) > 1e-6) then + return nil, nil, nil + end + local sx = sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3]) + local sy = sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7]) + local sz = sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11]) + if strict and (sx < 1e-12 or sy < 1e-12 or sz < 1e-12) then + return nil, nil, nil + end + if det3(m) < 0 then + sx = -sx + end + local ix = if sx ~= 0 then 1 / sx else 0 + local iy = if sy ~= 0 then 1 / sy else 0 + local iz = if sz ~= 0 then 1 / sz else 0 + local r = { m[1] * ix, m[2] * ix, m[3] * ix, 0, m[5] * iy, m[6] * iy, m[7] * iy, 0, m[9] * iz, m[10] * iz, m[11] * iz, 0, 0, 0, 0, 1 } + if strict then + local dxy = r[1] * r[5] + r[2] * r[6] + r[3] * r[7] + local dxz = r[1] * r[9] + r[2] * r[10] + r[3] * r[11] + local dyz = r[5] * r[9] + r[6] * r[10] + r[7] * r[11] + if abs(dxy) > 1e-4 or abs(dxz) > 1e-4 or abs(dyz) > 1e-4 then + return nil, nil, nil + end + end + return { m[13], m[14], m[15] }, Mat4.quat(r), { sx, sy, sz } +end + +-- decompose(m) -> translation, rotation (quaternion), scale (a negative determinant flips the x scale; shear is lost) +function Mat4.decompose(m: M4): ({ number }, { number }, { number }) + local t, r, s = split(m, false) + return t :: { number }, r :: { number }, s :: { number } +end + +-- decomposeStrict(m) -> translation, rotation, scale | nil for matrices TRS cannot express (a projective row, shear, +-- a zero scale) +function Mat4.decomposeStrict(m: M4): ({ number }?, { number }?, { number }?) + return split(m, true) +end + +-- inverse(m) -> the inverse of an affine matrix (general upper 3x3) | nil when singular +function Mat4.inverse(m: M4): M4? + local a, b, c = m[1], m[5], m[9] + local d, e, f = m[2], m[6], m[10] + local g, h, i = m[3], m[7], m[11] + local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g + local det = a * A + b * B + c * C + if det == 0 or det ~= det then + return nil + end + local k = 1 / det + local r = { + A * k, B * k, C * k, 0, + -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0, + (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0, + 0, 0, 0, 1, + } + local tx, ty, tz = m[13], m[14], m[15] + r[13] = -(r[1] * tx + r[5] * ty + r[9] * tz) + r[14] = -(r[2] * tx + r[6] * ty + r[10] * tz) + r[15] = -(r[3] * tx + r[7] * ty + r[11] * tz) + return r +end + +-- inverseFull(m) -> the inverse of any invertible 4x4 (projective rows too) | nil when singular +function Mat4.inverseFull(m: M4): M4? + local a = m + local inv = table.create(16, 0) + inv[1] = a[6] * a[11] * a[16] - a[6] * a[12] * a[15] - a[10] * a[7] * a[16] + a[10] * a[8] * a[15] + a[14] * a[7] * a[12] - a[14] * a[8] * a[11] + inv[5] = -a[5] * a[11] * a[16] + a[5] * a[12] * a[15] + a[9] * a[7] * a[16] - a[9] * a[8] * a[15] - a[13] * a[7] * a[12] + a[13] * a[8] * a[11] + inv[9] = a[5] * a[10] * a[16] - a[5] * a[12] * a[14] - a[9] * a[6] * a[16] + a[9] * a[8] * a[14] + a[13] * a[6] * a[12] - a[13] * a[8] * a[10] + inv[13] = -a[5] * a[10] * a[15] + a[5] * a[11] * a[14] + a[9] * a[6] * a[15] - a[9] * a[7] * a[14] - a[13] * a[6] * a[11] + a[13] * a[7] * a[10] + inv[2] = -a[2] * a[11] * a[16] + a[2] * a[12] * a[15] + a[10] * a[3] * a[16] - a[10] * a[4] * a[15] - a[14] * a[3] * a[12] + a[14] * a[4] * a[11] + inv[6] = a[1] * a[11] * a[16] - a[1] * a[12] * a[15] - a[9] * a[3] * a[16] + a[9] * a[4] * a[15] + a[13] * a[3] * a[12] - a[13] * a[4] * a[11] + inv[10] = -a[1] * a[10] * a[16] + a[1] * a[12] * a[14] + a[9] * a[2] * a[16] - a[9] * a[4] * a[14] - a[13] * a[2] * a[12] + a[13] * a[4] * a[10] + inv[14] = a[1] * a[10] * a[15] - a[1] * a[11] * a[14] - a[9] * a[2] * a[15] + a[9] * a[3] * a[14] + a[13] * a[2] * a[11] - a[13] * a[3] * a[10] + inv[3] = a[2] * a[7] * a[16] - a[2] * a[8] * a[15] - a[6] * a[3] * a[16] + a[6] * a[4] * a[15] + a[14] * a[3] * a[8] - a[14] * a[4] * a[7] + inv[7] = -a[1] * a[7] * a[16] + a[1] * a[8] * a[15] + a[5] * a[3] * a[16] - a[5] * a[4] * a[15] - a[13] * a[3] * a[8] + a[13] * a[4] * a[7] + inv[11] = a[1] * a[6] * a[16] - a[1] * a[8] * a[14] - a[5] * a[2] * a[16] + a[5] * a[4] * a[14] + a[13] * a[2] * a[8] - a[13] * a[4] * a[6] + inv[15] = -a[1] * a[6] * a[15] + a[1] * a[7] * a[14] + a[5] * a[2] * a[15] - a[5] * a[3] * a[14] - a[13] * a[2] * a[7] + a[13] * a[3] * a[6] + inv[4] = -a[2] * a[7] * a[12] + a[2] * a[8] * a[11] + a[6] * a[3] * a[12] - a[6] * a[4] * a[11] - a[10] * a[3] * a[8] + a[10] * a[4] * a[7] + inv[8] = a[1] * a[7] * a[12] - a[1] * a[8] * a[11] - a[5] * a[3] * a[12] + a[5] * a[4] * a[11] + a[9] * a[3] * a[8] - a[9] * a[4] * a[7] + inv[12] = -a[1] * a[6] * a[12] + a[1] * a[8] * a[10] + a[5] * a[2] * a[12] - a[5] * a[4] * a[10] - a[9] * a[2] * a[8] + a[9] * a[4] * a[6] + inv[16] = a[1] * a[6] * a[11] - a[1] * a[7] * a[10] - a[5] * a[2] * a[11] + a[5] * a[3] * a[10] + a[9] * a[2] * a[7] - a[9] * a[3] * a[6] + local det = a[1] * inv[1] + a[2] * inv[5] + a[3] * inv[9] + a[4] * inv[13] + if det == 0 or det ~= det then + return nil + end + for k = 1, 16 do + inv[k] /= det + end + return inv +end + +-- transpose3(m) -> m with its upper 3x3 transposed and no translation (the inverse of a pure rotation) +function Mat4.transpose3(m: M4): M4 + return { m[1], m[5], m[9], 0, m[2], m[6], m[10], 0, m[3], m[7], m[11], 0, 0, 0, 0, 1 } +end + +-- fromRows(v, at?) -> column-major from 16 row-major values at v[at] (default 1; missing values: identity) +function Mat4.fromRows(v: { number }, at: number?): M4 + local o = (at or 1) - 1 + local m = table.create(16, 0) + for r = 0, 3 do + for c = 0, 3 do + m[c * 4 + r + 1] = v[o + r * 4 + c + 1] or (if r == c then 1 else 0) + end + end + return m +end + +-- toRows(m) -> the 16 values row-major +function Mat4.toRows(m: M4): { number } + local v = table.create(16, 0) + for r = 0, 3 do + for c = 0, 3 do + v[r * 4 + c + 1] = m[c * 4 + r + 1] + end + end + return v +end + +-- point(m, x, y, z) -> m * (x, y, z, 1) +function Mat4.point(m: M4, x: number, y: number, z: number): (number, number, number) + return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] +end + +-- normalMatrix(m) -> the inverse transpose of the upper 3x3 (for normals) as a 4x4 (identity when singular) +function Mat4.normalMatrix(m: M4): M4 + local inv = Mat4.inverse({ m[1], m[2], m[3], 0, m[5], m[6], m[7], 0, m[9], m[10], m[11], 0, 0, 0, 0, 1 }) + if not inv then + return Mat4.identity() + end + return Mat4.transpose3(inv) +end + +return Mat4 diff --git a/src/Formats/codecs/MeshFlatten.luau b/src/Formats/codecs/model/MeshFlatten.luau similarity index 99% rename from src/Formats/codecs/MeshFlatten.luau rename to src/Formats/codecs/model/MeshFlatten.luau index 8d2ab73..3c26fc6 100644 --- a/src/Formats/codecs/MeshFlatten.luau +++ b/src/Formats/codecs/model/MeshFlatten.luau @@ -1,5 +1,5 @@ --!strict --- codecs/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks +-- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks -- scene.roots recursively (TRS or column-major `matrix` per node; a scene without nodes uses its meshes as they are), -- applies the transforms to POSITION (and the inverse transpose to NORMAL), reverses the winding under mirroring -- transforms, reads every accessor type to numbers and concatenates all primitives (triangles with or without indices, diff --git a/src/Formats/codecs/Json/Decode.luau b/src/Formats/codecs/text/Json/Decode.luau similarity index 98% rename from src/Formats/codecs/Json/Decode.luau rename to src/Formats/codecs/text/Json/Decode.luau index 4d97f82..eb58b45 100644 --- a/src/Formats/codecs/Json/Decode.luau +++ b/src/Formats/codecs/text/Json/Decode.luau @@ -1,10 +1,10 @@ --!strict --!native --- codecs/Json/Decode: the RFC 8259 parser behind codecs/Json. Iterative (an explicit container stack, so deep nesting +-- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json. Iterative (an explicit container stack, so deep nesting -- is a LIMIT error, never a stack overflow), strict grammar (no comments, trailing commas, leading zeros, NaN, single -- quotes or raw control characters), \u escapes with surrogate pairs (lone surrogates become WTF-8 bytes). Also the -- pull tokenizer behind Json.events. Never throws: failures return nil, message, offset (0-based byte offset). -local Text = require("@formats/codecs/Text") +local Text = require("@formats/codecs/text/Text") local Types = require("@formats/Types") local Decode = {} diff --git a/src/Formats/codecs/Json/Encode.luau b/src/Formats/codecs/text/Json/Encode.luau similarity index 98% rename from src/Formats/codecs/Json/Encode.luau rename to src/Formats/codecs/text/Json/Encode.luau index 78d0ac5..6e7fdce 100644 --- a/src/Formats/codecs/Json/Encode.luau +++ b/src/Formats/codecs/text/Json/Encode.luau @@ -1,6 +1,6 @@ --!strict --!native --- codecs/Json/Encode: the serializer behind codecs/Json. Compact or pretty (indent), objects in their Types.object key +-- codecs/text/Json/Encode: the serializer behind codecs/text/Json. Compact or pretty (indent), objects in their Types.object key -- order (plain tables: sorted keys), arrays for tables with keys 1..n, shortest round-trip number text, optional -- ASCII-only output. Never throws: bad values (cycles, NaN / inf, functions, non-string keys that are not numbers) -- return nil, message. diff --git a/src/Formats/codecs/Json/init.luau b/src/Formats/codecs/text/Json/init.luau similarity index 96% rename from src/Formats/codecs/Json/init.luau rename to src/Formats/codecs/text/Json/init.luau index f9b6204..fd50051 100644 --- a/src/Formats/codecs/Json/init.luau +++ b/src/Formats/codecs/text/Json/init.luau @@ -1,10 +1,10 @@ --!strict --- codecs/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. +-- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. -- Values are plain Luau: objects -> tables (string keys), arrays -> arrays, null -> Types.null (opts.null), numbers -- -> doubles (opts.bigInts = "string" keeps integers past 2^53 as their text). Empty objects are Types.object() so -- they write back as {}; opts.ordered makes every object a Types.object with its key order. -- --- local Json = require("@formats/codecs/Json") +-- local Json = require("@formats/codecs/text/Json") -- local v, err = Json.decode('{"a": [1, 2, null]}') -- string | buffer; nil, Err on bad input -- local s = Json.encode(v, { indent = 2 }) -- string | nil, Err -- for ev, x in Json.events(text) do ... end -- pull events without building the tree @@ -15,8 +15,8 @@ -- writer() builds output incrementally and flush() hands back the text so far. Never throws. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Decode = require("@formats/codecs/Json/Decode") -local Encode = require("@formats/codecs/Json/Encode") +local Decode = require("@formats/codecs/text/Json/Decode") +local Encode = require("@formats/codecs/text/Json/Encode") local Json = {} diff --git a/src/Formats/codecs/Text/init.luau b/src/Formats/codecs/text/Text/init.luau similarity index 94% rename from src/Formats/codecs/Text/init.luau rename to src/Formats/codecs/text/Text/init.luau index 74f86fb..6980e96 100644 --- a/src/Formats/codecs/Text/init.luau +++ b/src/Formats/codecs/text/Text/init.luau @@ -1,6 +1,6 @@ --!strict --!optimize 2 --- codecs/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is +-- codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is -- read as Windows-1252 (classic .m3u / .pls / .ini / .srt files), lines split on CRLF / CR / LF, trim. Absorbed from -- playlist-luau 3fc7fd3 (same author, no third-party code). Never throws. local Text = {} diff --git a/src/Formats/codecs/Url/init.luau b/src/Formats/codecs/text/Url/init.luau similarity index 98% rename from src/Formats/codecs/Url/init.luau rename to src/Formats/codecs/text/Url/init.luau index 026ecb5..19b359b 100644 --- a/src/Formats/codecs/Url/init.luau +++ b/src/Formats/codecs/text/Url/init.luau @@ -1,6 +1,6 @@ --!strict --!optimize 2 --- codecs/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, +-- codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, -- Windows / UNC / POSIX local path, relative reference) and percent-encoding of bytes that may not appear in a URI -- (raw spaces and UTF-8 in playlists). Shared by the playlist formats (m3u / HLS, pls, xspf); later DASH / glTF URIs. -- Absorbed from playlist-luau 3fc7fd3 (same author, no third-party code): Url.luau, plus locate / base from its diff --git a/src/Formats/codecs/Xml/Parse.luau b/src/Formats/codecs/text/Xml/Parse.luau similarity index 99% rename from src/Formats/codecs/Xml/Parse.luau rename to src/Formats/codecs/text/Xml/Parse.luau index cf39eca..57aa477 100644 --- a/src/Formats/codecs/Xml/Parse.luau +++ b/src/Formats/codecs/text/Xml/Parse.luau @@ -1,13 +1,13 @@ --!strict --!native --- codecs/Xml/Parse: the XML 1.0 pull parser behind codecs/Xml. Input decoding (UTF-8, UTF-16 LE / BE by BOM or +-- codecs/text/Xml/Parse: the XML 1.0 pull parser behind codecs/text/Xml. Input decoding (UTF-8, UTF-16 LE / BE by BOM or -- by the first bytes, ISO-8859-1 / US-ASCII / Windows-1252 by the declaration), line-ending normalization, the -- well-formedness rules that matter (one root, matched tags, unique attributes, quoted values, no '<' in values, -- legal names, character references in range, no "--" in comments, no "]]>" in text), the five predefined entities, -- character references and internal general entities from the DOCTYPE (with an expansion limit). Not supported: -- external entities / DTDs (references to them are errors), entity values containing markup (taken as text), -- validation. Never throws: errors are events. -local Text = require("@formats/codecs/Text") +local Text = require("@formats/codecs/text/Text") local Types = require("@formats/Types") local Parse = {} diff --git a/src/Formats/codecs/Xml/init.luau b/src/Formats/codecs/text/Xml/init.luau similarity index 97% rename from src/Formats/codecs/Xml/init.luau rename to src/Formats/codecs/text/Xml/init.luau index fcb574b..3ec2855 100644 --- a/src/Formats/codecs/Xml/init.luau +++ b/src/Formats/codecs/text/Xml/init.luau @@ -1,11 +1,11 @@ --!strict --- codecs/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... +-- codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... -- use. New code. Supports: UTF-8 / UTF-16 / Latin-1 input, the predefined entities, character references, internal -- DOCTYPE entities (expansion limited), CDATA, comments, processing instructions, the XML declaration, namespaces -- (names stay qualified "prefix:local"; opts.namespaces adds each element's URI as node.ns; Xml.clark gives -- "{uri}local"), xml:space. Not supported: external entities / DTDs, validation, entity values containing markup. -- --- local Xml = require("@formats/codecs/Xml") +-- local Xml = require("@formats/codecs/text/Xml") -- local doc, err = Xml.decode(text) -- a "#document" node; doc.root is the root element -- for _, item in Xml.children(doc.root, "item") do print(item.attrs.id, Xml.text(item)) end -- for ev, a, b in Xml.events(text) do ... end -- "start" name attrs / "end" name / "text" s / ... (SAX-like) @@ -18,7 +18,7 @@ -- target); otherwise CDATA merges into the text and the others are dropped. Never throws. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Parse = require("@formats/codecs/Xml/Parse") +local Parse = require("@formats/codecs/text/Xml/Parse") local Xml = {} @@ -57,7 +57,7 @@ local function errCode(msg: string, at: number, n: number): string return Err.CORRUPT end --- events(src, opts?) -> iterator: event, a, b, c (see codecs/Xml/Parse: "decl", "doctype", "start" name attrs ns, +-- events(src, opts?) -> iterator: event, a, b, c (see codecs/text/Xml/Parse: "decl", "doctype", "start" name attrs ns, -- "end" name, "text" s, "cdata" s, "comment" s, "pi" target data, and on bad input "error" Err as the last event) function Xml.events(src: string | buffer, opts: Parse.Options?): () -> (string?, any, any, any) local s, terr = text(src) diff --git a/src/Formats/codecs/H264/Bitstream.luau b/src/Formats/codecs/video/H264/Bitstream.luau similarity index 98% rename from src/Formats/codecs/H264/Bitstream.luau rename to src/Formats/codecs/video/H264/Bitstream.luau index acdeda9..9750fde 100644 --- a/src/Formats/codecs/H264/Bitstream.luau +++ b/src/Formats/codecs/video/H264/Bitstream.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/H264/Bitstream: NAL unit framing and the RBSP bit reader of ITU-T H.264 (7.3 / 7.4 / 9.1): Annex B start +-- codecs/video/H264/Bitstream: NAL unit framing and the RBSP bit reader of ITU-T H.264 (7.3 / 7.4 / 9.1): Annex B start -- code splitting, AVCC length-prefixed samples, avcC (AVCDecoderConfigurationRecord, ISO/IEC 14496-15 5.3.3) -- parsing, emulation-prevention removal, and the u(n) / ue(v) / se(v) / te(v) readers. Written from the spec. -- Never throws: reads past the end of an RBSP return zero bits (the buffer carries 8 zero bytes of padding and every diff --git a/src/Formats/codecs/H264/Cabac.luau b/src/Formats/codecs/video/H264/Cabac.luau similarity index 98% rename from src/Formats/codecs/H264/Cabac.luau rename to src/Formats/codecs/video/H264/Cabac.luau index ceb74d5..910ffa8 100644 --- a/src/Formats/codecs/H264/Cabac.luau +++ b/src/Formats/codecs/video/H264/Cabac.luau @@ -1,15 +1,15 @@ --!strict --!native --!optimize 2 --- codecs/H264/Cabac: slice data and macroblock layer with CABAC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.3): the +-- codecs/video/H264/Cabac: slice data and macroblock layer with CABAC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.3): the -- arithmetic decoding engine (9.3.1.2 / 9.3.3.2), context initialisation (9.3.1.1), the binarizations and context -- index increments of every syntax element (9.3.2 / 9.3.3.1) and residual_block_cabac for 4x4, 8x8 and DC blocks. -- Coefficients are dequantised as they are placed. Written from the spec; tables from Tables. -- The engine keeps codIOffset with `nb` look-ahead bits (low = offset * 2^nb + next bits), so renormalisation is one -- multiply and bytes are fetched one at a time. Never throws: returns false, "message" on bad data. -local Bitstream = require("@formats/codecs/H264/Bitstream") -local Tables = require("@formats/codecs/H264/Tables") -local Mb = require("@formats/codecs/H264/Mb") +local Bitstream = require("@formats/codecs/video/H264/Bitstream") +local Tables = require("@formats/codecs/video/H264/Tables") +local Mb = require("@formats/codecs/video/H264/Mb") local readu8 = buffer.readu8 local min = math.min diff --git a/src/Formats/codecs/H264/Cavlc.luau b/src/Formats/codecs/video/H264/Cavlc.luau similarity index 98% rename from src/Formats/codecs/H264/Cavlc.luau rename to src/Formats/codecs/video/H264/Cavlc.luau index f14e42e..9a6ecdb 100644 --- a/src/Formats/codecs/H264/Cavlc.luau +++ b/src/Formats/codecs/video/H264/Cavlc.luau @@ -1,14 +1,14 @@ --!strict --!native --!optimize 2 --- codecs/H264/Cavlc: slice data and macroblock layer with CAVLC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.2): +-- codecs/video/H264/Cavlc: slice data and macroblock layer with CAVLC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.2): -- mb_skip_run, mb_type / sub_mb_type, intra modes, ref_idx (te), mvd, coded_block_pattern (me), mb_qp_delta and -- residual_block_cavlc (coeff_token, level_prefix / suffix, total_zeros, run_before) with the 8x8 interleaving. -- Coefficients are dequantised as they are placed. Written from the spec; VLC tables from Tables. -- Never throws: returns false, "message" on bad data. -local Bitstream = require("@formats/codecs/H264/Bitstream") -local Tables = require("@formats/codecs/H264/Tables") -local Mb = require("@formats/codecs/H264/Mb") +local Bitstream = require("@formats/codecs/video/H264/Bitstream") +local Tables = require("@formats/codecs/video/H264/Tables") +local Mb = require("@formats/codecs/video/H264/Mb") local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se diff --git a/src/Formats/codecs/H264/Deblock.luau b/src/Formats/codecs/video/H264/Deblock.luau similarity index 97% rename from src/Formats/codecs/H264/Deblock.luau rename to src/Formats/codecs/video/H264/Deblock.luau index ffc1051..519c0a2 100644 --- a/src/Formats/codecs/H264/Deblock.luau +++ b/src/Formats/codecs/video/H264/Deblock.luau @@ -1,13 +1,13 @@ --!strict --!native --!optimize 2 --- codecs/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0: +-- codecs/video/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0: -- boundary strengths (8.7.2.1, from the per-4x4 intra / coefficient / reference / motion grids), alpha / beta / tC0 -- (tables 8-16 / 8-17), the bS < 4 and bS = 4 luma and chroma filters, disable_deblocking_filter_idc 0 / 1 / 2 and the -- slice alpha / beta offsets. Written from the spec. Runs over the whole picture in macroblock order once all its -- slices are decoded (the result equals filtering each macroblock as it is decoded). -- Never throws. -local Tables = require("@formats/codecs/H264/Tables") +local Tables = require("@formats/codecs/video/H264/Tables") local readu8, writeu8 = buffer.readu8, buffer.writeu8 local ALPHA, BETA, TC0 = Tables.ALPHA, Tables.BETA, Tables.TC0 diff --git a/src/Formats/codecs/H264/Decoder.luau b/src/Formats/codecs/video/H264/Decoder.luau similarity index 97% rename from src/Formats/codecs/H264/Decoder.luau rename to src/Formats/codecs/video/H264/Decoder.luau index 963c91d..fb099fb 100644 --- a/src/Formats/codecs/H264/Decoder.luau +++ b/src/Formats/codecs/video/H264/Decoder.luau @@ -1,19 +1,19 @@ --!strict --- codecs/H264/Decoder: the decoding process above the macroblock layer (ITU-T H.264 8.1, 8.2, C.4): NAL unit +-- codecs/video/H264/Decoder: the decoding process above the macroblock layer (ITU-T H.264 8.1, 8.2, C.4): NAL unit -- dispatch, picture boundaries (7.4.1.2.4), picture order count types 0 / 1 / 2 (8.2.1), frame_num gaps (8.2.5.2), -- reference picture lists with modification (8.2.4), sliding window and adaptive (MMCO 1-6) marking (8.2.5), output -- in POC order through a reorder buffer (num_reorder_frames, else the DPB size), concealment of lost macroblocks, -- deblocking and border extension. Written from the spec. -- Never throws: errors are returned (a corrupt slice is skipped and its macroblocks concealed). -local Bitstream = require("@formats/codecs/H264/Bitstream") -local Params = require("@formats/codecs/H264/Params") -local Slice = require("@formats/codecs/H264/Slice") -local Tables = require("@formats/codecs/H264/Tables") -local Mb = require("@formats/codecs/H264/Mb") -local Cavlc = require("@formats/codecs/H264/Cavlc") -local Cabac = require("@formats/codecs/H264/Cabac") -local Deblock = require("@formats/codecs/H264/Deblock") -local Inter = require("@formats/codecs/H264/Inter") +local Bitstream = require("@formats/codecs/video/H264/Bitstream") +local Params = require("@formats/codecs/video/H264/Params") +local Slice = require("@formats/codecs/video/H264/Slice") +local Tables = require("@formats/codecs/video/H264/Tables") +local Mb = require("@formats/codecs/video/H264/Mb") +local Cavlc = require("@formats/codecs/video/H264/Cavlc") +local Cabac = require("@formats/codecs/video/H264/Cabac") +local Deblock = require("@formats/codecs/video/H264/Deblock") +local Inter = require("@formats/codecs/video/H264/Inter") local Types = require("@formats/Types") local PAD, PADC = Inter.PAD, Inter.PADC diff --git a/src/Formats/codecs/H264/Inter.luau b/src/Formats/codecs/video/H264/Inter.luau similarity index 98% rename from src/Formats/codecs/H264/Inter.luau rename to src/Formats/codecs/video/H264/Inter.luau index 7dbe10b..6dc0a8e 100644 --- a/src/Formats/codecs/H264/Inter.luau +++ b/src/Formats/codecs/video/H264/Inter.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3): the 6-tap +-- codecs/video/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3): the 6-tap -- quarter-sample luma filter, eighth-sample bilinear chroma, default / explicit / implicit weighted sample -- prediction, and the picture border extension that makes out-of-picture reference reads equal to the clamped -- sample positions of 8.4.2.2.1. Written from the spec. diff --git a/src/Formats/codecs/H264/Intra.luau b/src/Formats/codecs/video/H264/Intra.luau similarity index 98% rename from src/Formats/codecs/H264/Intra.luau rename to src/Formats/codecs/video/H264/Intra.luau index 4543050..f63dead 100644 --- a/src/Formats/codecs/H264/Intra.luau +++ b/src/Formats/codecs/video/H264/Intra.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (nine directional modes, with the +-- codecs/video/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (nine directional modes, with the -- 8x8 reference sample filter of 8.3.2.2.1), Intra_16x16 and chroma (DC / horizontal / vertical / plane), 8-bit. -- Written from the spec. Predictions are written straight into the picture plane (row stride `s`, block origin `o`). -- Never throws: every sample read is inside the padded plane (callers pass availability for the edges). diff --git a/src/Formats/codecs/H264/Mb.luau b/src/Formats/codecs/video/H264/Mb.luau similarity index 98% rename from src/Formats/codecs/H264/Mb.luau rename to src/Formats/codecs/video/H264/Mb.luau index 428e088..ac6d983 100644 --- a/src/Formats/codecs/H264/Mb.luau +++ b/src/Formats/codecs/video/H264/Mb.luau @@ -1,15 +1,15 @@ --!strict --!native --!optimize 2 --- codecs/H264/Mb: macroblock reconstruction shared by the CAVLC and CABAC parsers (ITU-T H.264 8.3 - 8.5): +-- codecs/video/H264/Mb: macroblock reconstruction shared by the CAVLC and CABAC parsers (ITU-T H.264 8.3 - 8.5): -- neighbour availability (6.4.11), Intra4x4 / Intra8x8 mode prediction (8.3.1.1 / 8.3.2.1), motion vector prediction -- (8.4.1.3), P_Skip (8.4.1.1), B direct spatial and temporal (8.4.1.2), motion compensation with weighting, intra -- prediction and the residual. Written from the spec; the per-4x4 motion / mode grids follow the usual decoder layout -- (picture-wide arrays, one entry per 4x4 luma block, 1-based). -- Never throws: every index is in range by construction; reference indices past the list use the first entry. -local Intra = require("@formats/codecs/H264/Intra") -local Transform = require("@formats/codecs/H264/Transform") -local Inter = require("@formats/codecs/H264/Inter") +local Intra = require("@formats/codecs/video/H264/Intra") +local Transform = require("@formats/codecs/video/H264/Transform") +local Inter = require("@formats/codecs/video/H264/Inter") local Mb = {} diff --git a/src/Formats/codecs/H264/Params.luau b/src/Formats/codecs/video/H264/Params.luau similarity index 98% rename from src/Formats/codecs/H264/Params.luau rename to src/Formats/codecs/video/H264/Params.luau index 04c2682..b97d9c4 100644 --- a/src/Formats/codecs/H264/Params.luau +++ b/src/Formats/codecs/video/H264/Params.luau @@ -1,11 +1,11 @@ --!strict --!native --- codecs/H264/Params: sequence and picture parameter sets (ITU-T H.264 7.3.2.1 / 7.3.2.2 / E.1), scaling lists with +-- codecs/video/H264/Params: sequence and picture parameter sets (ITU-T H.264 7.3.2.1 / 7.3.2.2 / E.1), scaling lists with -- the fall-back rules A and B (7.4.2.1.1 / table 7-2), and the dequantisation tables built from them (8.5.9: the -- LevelScale4x4 / LevelScale8x8 functions, premultiplied by 2^(qP / 6)). Written from the spec. -- Never throws: parse functions return nil, "message". -local Bitstream = require("@formats/codecs/H264/Bitstream") -local Tables = require("@formats/codecs/H264/Tables") +local Bitstream = require("@formats/codecs/video/H264/Bitstream") +local Tables = require("@formats/codecs/video/H264/Tables") local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se diff --git a/src/Formats/codecs/H264/Slice.luau b/src/Formats/codecs/video/H264/Slice.luau similarity index 97% rename from src/Formats/codecs/H264/Slice.luau rename to src/Formats/codecs/video/H264/Slice.luau index 8aa9acd..a64cb93 100644 --- a/src/Formats/codecs/H264/Slice.luau +++ b/src/Formats/codecs/video/H264/Slice.luau @@ -1,10 +1,10 @@ --!strict --!native --- codecs/H264/Slice: the slice header (ITU-T H.264 7.3.3): ref_pic_list_modification, pred_weight_table and +-- codecs/video/H264/Slice: the slice header (ITU-T H.264 7.3.3): ref_pic_list_modification, pred_weight_table and -- dec_ref_pic_marking. Written from the spec. Frame coding only: field pictures (field_pic_flag = 1), MBAFF, -- SP / SI slices, separate colour planes and redundant pictures return "unsupported: ...". -- Never throws: header() returns nil, "message". -local Bitstream = require("@formats/codecs/H264/Bitstream") +local Bitstream = require("@formats/codecs/video/H264/Bitstream") local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se diff --git a/src/Formats/codecs/H264/Tables.luau b/src/Formats/codecs/video/H264/Tables.luau similarity index 99% rename from src/Formats/codecs/H264/Tables.luau rename to src/Formats/codecs/video/H264/Tables.luau index fdcaec1..d2b1679 100644 --- a/src/Formats/codecs/H264/Tables.luau +++ b/src/Formats/codecs/video/H264/Tables.luau @@ -1,6 +1,6 @@ --!strict --!native --- codecs/H264/Tables: the constant tables of ITU-T H.264 (CAVLC code tables 9-5, 9-7, 9-8, 9-9, 9-10; CABAC context +-- codecs/video/H264/Tables: the constant tables of ITU-T H.264 (CAVLC code tables 9-5, 9-7, 9-8, 9-9, 9-10; CABAC context -- initialisation tables 9-12..9-24, rangeTabLPS 9-44 and the state transitions 9-45; the chroma QP table 8-15; the -- me(v) coded_block_pattern mapping 9-4; default scaling lists 7-3 / 7-4; zig-zag scans 8-12 / 8-13; table 9-43; the -- deblocking alpha / beta / tC0 tables 8-16 / 8-17). Values extracted from openh264 2.x (BSD-2-Clause, diff --git a/src/Formats/codecs/H264/Transform.luau b/src/Formats/codecs/video/H264/Transform.luau similarity index 97% rename from src/Formats/codecs/H264/Transform.luau rename to src/Formats/codecs/video/H264/Transform.luau index 6fd463d..b631624 100644 --- a/src/Formats/codecs/H264/Transform.luau +++ b/src/Formats/codecs/video/H264/Transform.luau @@ -1,7 +1,7 @@ --!strict --!native --!optimize 2 --- codecs/H264/Transform: the inverse transforms of ITU-T H.264 8.5: the 4x4 and 8x8 integer IDCTs with the residual +-- codecs/video/H264/Transform: the inverse transforms of ITU-T H.264 8.5: the 4x4 and 8x8 integer IDCTs with the residual -- added to the prediction in the plane (8.5.12.2 / 8.5.13.2 / 8.5.14), the 4x4 luma DC and 2x2 chroma DC Hadamard -- transforms with their scaling (8.5.10 / 8.5.11.2). Written from the spec. Coefficients are dequantised already -- (Params.dequant), raster order, in a 1-based table at `base + 1 ...`; the functions zero what they read. diff --git a/src/Formats/codecs/H264/init.luau b/src/Formats/codecs/video/H264/init.luau similarity index 97% rename from src/Formats/codecs/H264/init.luau rename to src/Formats/codecs/video/H264/init.luau index 1dcfd90..501652f 100644 --- a/src/Formats/codecs/H264/init.luau +++ b/src/Formats/codecs/video/H264/init.luau @@ -1,5 +1,5 @@ --!strict --- 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/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the -- video/h264 format (raw Annex B streams) and the MP4 / MKV / AVI / TS video tracks use it. Clean-room, written from the -- spec; constant tables taken from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). Bit-exact with the -- reference decoder (checked against ffmpeg per frame). @@ -14,7 +14,7 @@ -- lossless (transform bypass), FMO / ASO slice groups, SP / SI slices, data partitioning, SVC / MVC enhancement layers -- (their NAL units are ignored). -- --- local H264 = require("@formats/codecs/H264") +-- local H264 = require("@formats/codecs/video/H264") -- local dec = H264.newDecoder() -- or { avcC = buffer } for MP4 samples (length-prefixed) -- for _, au in accessUnits do -- local frames, err = dec:decode(au, pts) -- frames: { { image (yuv420p Types.Image), pts, poc, keyframe } } @@ -29,9 +29,9 @@ -- concealed (dec.errors counts them, dec.lastError says why). local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Bitstream = require("@formats/codecs/H264/Bitstream") -local Decoder = require("@formats/codecs/H264/Decoder") -local Params = require("@formats/codecs/H264/Params") +local Bitstream = require("@formats/codecs/video/H264/Bitstream") +local Decoder = require("@formats/codecs/video/H264/Decoder") +local Params = require("@formats/codecs/video/H264/Params") local H264 = {} @@ -201,7 +201,7 @@ function H264.parseAvcC(data: any): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ video layer --- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/Video registry entry for "h264"): +-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video registry entry for "h264"): -- track.config = avcC (MP4 / Matroska; packets length-prefixed) or nil (Annex B packets: MPEG-TS, AVI, raw .h264). -- Pictures come out in display order with the packet timestamps sorted (display order); a track with -- `ptsInOutputOrder` (raw Annex B, no timestamps) numbers them in output order instead. diff --git a/src/Formats/codecs/Mpeg1/Decoder.luau b/src/Formats/codecs/video/Mpeg1/Decoder.luau similarity index 98% rename from src/Formats/codecs/Mpeg1/Decoder.luau rename to src/Formats/codecs/video/Mpeg1/Decoder.luau index c9a054c..5fcdb1f 100644 --- a/src/Formats/codecs/Mpeg1/Decoder.luau +++ b/src/Formats/codecs/video/Mpeg1/Decoder.luau @@ -1,6 +1,6 @@ --!strict --!native --- codecs/Mpeg1/Decoder: the MPEG-1 video decoding core (ISO/IEC 11172-2; native, never throws): I, P and B pictures, +-- codecs/video/Mpeg1/Decoder: the MPEG-1 video decoding core (ISO/IEC 11172-2; native, never throws): I, P and B pictures, -- half-pel motion compensation, custom quantiser matrices, sequence headers anywhere in the stream. Absorbed from -- mpeg1-luau e2e2898 (same author; src/Mpeg1/Decoder.luau, unchanged but for this header and the requires), a port -- of jsmpeg's decoder (src/mpeg1.js by Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt) with these changes for @@ -13,7 +13,7 @@ -- * motion compensation four bytes at a time (SWAR rounding averages); -- * BT.601 limited-range YCbCr -> RGBA8 (jsmpeg's canvas path treats Y as full range). -- --- The IDCT is not codecs/Dct's: it computes the same islow transform (its put mode is bit-identical to +-- The IDCT is not codecs/image/Dct's: it computes the same islow transform (its put mode is bit-identical to -- Dct.idctBlock with a unit quantiser and no level shift, checked on 20000 random blocks), but MPEG-1 adds the -- residual of P / B blocks to the prediction before clamping, dequantises into i32 coefficients itself (MPEG -- rounding and oddification, not JPEG's q multiply) and writes u8 samples four per writeu32, where Dct clamps to @@ -23,8 +23,8 @@ -- Native code must never throw (an error unwinding through native code crashes Roblox Studio): every read -- position is checked against the data end (plus a zero pad that bounds the overrun of one macroblock), motion -- vectors are clamped to the reference picture, and bad data ends the slice instead of raising. -local V = require("@formats/codecs/Mpeg1/Vlc") -local T = require("@formats/codecs/Mpeg1/Tables") +local V = require("@formats/codecs/video/Mpeg1/Vlc") +local T = require("@formats/codecs/video/Mpeg1/Tables") local readu8 = buffer.readu8 local writeu8 = buffer.writeu8 diff --git a/src/Formats/codecs/Mpeg1/Tables.luau b/src/Formats/codecs/video/Mpeg1/Tables.luau similarity index 98% rename from src/Formats/codecs/Mpeg1/Tables.luau rename to src/Formats/codecs/video/Mpeg1/Tables.luau index 3e330ef..1cad194 100644 --- a/src/Formats/codecs/Mpeg1/Tables.luau +++ b/src/Formats/codecs/video/Mpeg1/Tables.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Mpeg1/Tables: the constant tables of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, +-- codecs/video/Mpeg1/Tables: the constant tables of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, -- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from -- mpeg1-luau e2e2898). Lists are 0-based like the JS arrays. local T = {} diff --git a/src/Formats/codecs/Mpeg1/Vlc.luau b/src/Formats/codecs/video/Mpeg1/Vlc.luau similarity index 94% rename from src/Formats/codecs/Mpeg1/Vlc.luau rename to src/Formats/codecs/video/Mpeg1/Vlc.luau index 8d34e39..b4799aa 100644 --- a/src/Formats/codecs/Mpeg1/Vlc.luau +++ b/src/Formats/codecs/video/Mpeg1/Vlc.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Mpeg1/Vlc: lookup tables for the MPEG-1 variable-length codes, built at load time from jsmpeg's binary trees (Tables.luau). +-- codecs/video/Mpeg1/Vlc: lookup tables for the MPEG-1 variable-length codes, built at load time from jsmpeg's binary trees (Tables.luau). -- -- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds -- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level @@ -8,7 +8,7 @@ -- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one -- more bit); DCT_FIRST keeps "1" as run 0 / level 1. Absorbed from mpeg1-luau e2e2898 (same author), unchanged but -- for this header and the require. -local T = require("@formats/codecs/Mpeg1/Tables") +local T = require("@formats/codecs/video/Mpeg1/Tables") local V = {} diff --git a/src/Formats/codecs/Mpeg1/init.luau b/src/Formats/codecs/video/Mpeg1/init.luau similarity index 97% rename from src/Formats/codecs/Mpeg1/init.luau rename to src/Formats/codecs/video/Mpeg1/init.luau index 2ff3118..25c7d10 100644 --- a/src/Formats/codecs/Mpeg1/init.luau +++ b/src/Formats/codecs/video/Mpeg1/init.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from +-- codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from -- mpeg1-luau e2e2898 (same author; README, docs/api.md and docs/performance.md there), a port of jsmpeg's decoder -- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt) extended with B-pictures, -- an islow integer IDCT, table-driven VLC decoding and BT.601 RGBA8 output; added here: frameImage. @@ -17,7 +17,7 @@ -- -- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau). local Types = require("@formats/Types") -local D = require("@formats/codecs/Mpeg1/Decoder") +local D = require("@formats/codecs/video/Mpeg1/Decoder") local Mpeg1 = {} diff --git a/src/Formats/codecs/Video/Source.luau b/src/Formats/codecs/video/Video/Source.luau similarity index 97% rename from src/Formats/codecs/Video/Source.luau rename to src/Formats/codecs/video/Video/Source.luau index 2779bf5..532312b 100644 --- a/src/Formats/codecs/Video/Source.luau +++ b/src/Formats/codecs/video/Video/Source.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given: +-- codecs/video/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given: -- a VideoDecoder (F.load / F.video.open of any video or animated image) or a Demuxer. Each output stream is either -- copied (the source track's packets, when the target container takes that codec: remuxing, e.g. VP8 into WebM, -- since VP8 is decode-only) or produced (decoded frames encoded with a registered encoder such as MJPEG, raw @@ -13,7 +13,7 @@ -- -- track, packets = { { pts, duration (seconds), keyframe, data } } } local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Yuv = require("@formats/codecs/Yuv") +local Yuv = require("@formats/codecs/image/Yuv") local Source = {} @@ -77,7 +77,7 @@ end local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err?) local encode: ((img: Types.Image, opts: any) -> (buffer?, Err.Err?))? = nil if codec ~= "rawvideo" then - local Video = require("@formats/codecs/Video") + local Video = require("@formats/codecs/video/Video") local e = Video.entry(codec) encode = e and e.encode if not encode then diff --git a/src/Formats/codecs/Video/init.luau b/src/Formats/codecs/video/Video/init.luau similarity index 97% rename from src/Formats/codecs/Video/init.luau rename to src/Formats/codecs/video/Video/init.luau index 1c99bb2..0960b9b 100644 --- a/src/Formats/codecs/Video/init.luau +++ b/src/Formats/codecs/video/Video/init.luau @@ -1,5 +1,5 @@ --!strict --- codecs/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. +-- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. -- -- Registry: our codec ids ("vp8", "mjpeg", "mpeg1", "h264", "rawvideo", ...) with the containers' names for them -- (AVI / MOV FourCCs, Matroska CodecIDs, MPEG stream types) and, for the codecs we can decode, a constructor of a @@ -7,7 +7,7 @@ -- Video.fromMatroska so a track's codec is known even without a decoder (remuxing still works). Another codec plugs -- in with one line in BUILTIN (static: Roblox has no dynamic require) or at run time with Video.register(entry). -- --- local Video = require("@formats/codecs/Video") +-- local Video = require("@formats/codecs/video/Video") -- Video.fromFourcc("MJPG") --> "mjpeg" Video.fromMatroska("V_VP8") --> "vp8" -- local dec = Video.decoder(track, opts) -- a VideoCodecDecoder | nil, Err (UNSUPPORTED: no decoder) -- local v = Video.open(demuxer, opts) -- a Types.VideoDecoder over a Types.Demuxer (formats' open()) @@ -16,7 +16,7 @@ -- Never throws: bad data / missing codecs come back as nil, Err. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Yuv = require("@formats/codecs/Yuv") +local Yuv = require("@formats/codecs/image/Yuv") local Video = {} @@ -190,7 +190,7 @@ local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDec end local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) - local Vp8 = require("@formats/codecs/Vp8") + local Vp8 = require("@formats/codecs/image/Vp8") local dec = Vp8.newDecoder() local o = { maxPixels = opts and opts.maxPixels } return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) @@ -216,7 +216,7 @@ end -- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout -- allows, else rgba8 local function mjpegDecoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) - local Jpeg = require("@formats/codecs/Jpeg") + local Jpeg = require("@formats/codecs/image/Jpeg") local o: Jpeg.DecodeOptions = { yuv = true, maxPixels = opts and opts.maxPixels } return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) local img, err = Jpeg.decode(data, 0, buffer.len(data), o) @@ -229,7 +229,7 @@ end -- the MJPEG encoder (writers): JPEG is full-range, so limited-range yuv420p frames are remapped first local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?) - local Jpeg = require("@formats/codecs/Jpeg") + local Jpeg = require("@formats/codecs/image/Jpeg") local src = img if img.format == "yuv420p" then local range = Yuv.info(img) @@ -242,7 +242,7 @@ end -- MPEG-1 video: pictures in decode order, reordered for display (the packet's pts travels with its picture) local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) - local Mpeg1 = require("@formats/codecs/Mpeg1") + local Mpeg1 = require("@formats/codecs/video/Mpeg1") local dec = Mpeg1.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels }) local queue: { any } = {} local function push(f: any) @@ -287,10 +287,10 @@ local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecD return self :: any, nil end --- H.264 / AVC (codecs/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264); +-- H.264 / AVC (codecs/video/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264); -- pictures in display order with the pts of their packet local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) - local H264 = require("@formats/codecs/H264") + local H264 = require("@formats/codecs/video/H264") return H264.newVideoDecoder(track, opts) end diff --git a/src/Formats/containers/Chunks.luau b/src/Formats/containers/Chunks.luau new file mode 100644 index 0000000..dda7836 --- /dev/null +++ b/src/Formats/containers/Chunks.luau @@ -0,0 +1,142 @@ +--!strict +-- containers/Chunks: the generic walker for chunked files (a 4-byte id and a byte size per chunk, the body, optional +-- trailer and padding): RIFF / RIFX / RF64 (containers/Riff builds on it), IFF / AIFF / AIFC, PNG (size first, a +-- CRC trailer), CAF (64-bit sizes). Formats list their chunk handlers over the walked list instead of each writing +-- the loop. New in formats-luau (the RIFF leniency comes from containers/Riff, absorbed from wav-luau). +-- +-- local list = Chunks.walk(buf, from, limit, Chunks.IFF) -- { Chunk } (offsets absolute in buf) +-- local list = Chunks.walk(buf, from, limit, { sizeFirst = true, bigEndian = true, trailer = 4 }) -- PNG +-- for _, c in list do if c.id == "COMM" then ... c.offset, c.size, c.avail ... end end +-- local c = Chunks.find(list, "SSND") +-- +-- A chunk declared past the end keeps what is there (avail < size, truncated = true) and ends the walk; ids in +-- layout.openEnded with a size of 0 / 0xFFFFFFFF / past the end run to the end of the data (streamed writers). +-- layout.lenientPad: an odd-sized chunk written without its pad byte is detected (the next id is printable only one +-- byte earlier). layout.resize(id, declared) can replace a declared size (RF64's ds64). Never throws. +local Chunks = {} + +export type Chunk = { + id: string, + start: number, -- the chunk header's offset + offset: number, -- the body's offset + size: number, -- the body size (after layout.resize / open-ended handling) + declared: number, -- the size field as written + avail: number, -- body bytes actually present (= size unless truncated) + truncated: boolean, + streamed: boolean, -- an open-ended chunk with size 0 / 0xFFFFFFFF +} + +export type Layout = { + bigEndian: boolean?, -- size fields big-endian (default little) + sizeFirst: boolean?, -- the size comes before the id (PNG) + sizeBytes: number?, -- 4 (default) or 8 + trailer: number?, -- bytes after the body that belong to the chunk (PNG: the 4-byte CRC) + pad: number?, -- bodies are padded to a multiple of this (RIFF / IFF: 2; default 1) + lenientPad: boolean?, -- detect odd bodies written without their pad byte + openEnded: { [string]: boolean }?, + resize: ((id: string, declared: number) -> number?)?, + maxChunks: number?, -- default 100000 +} + +Chunks.RIFF = table.freeze({ pad = 2, lenientPad = true }) :: Layout +Chunks.RIFX = table.freeze({ pad = 2, lenientPad = true, bigEndian = true }) :: Layout +Chunks.IFF = table.freeze({ pad = 2, bigEndian = true }) :: Layout +Chunks.PNG = table.freeze({ sizeFirst = true, bigEndian = true, trailer = 4 }) :: Layout +Chunks.CAF = table.freeze({ bigEndian = true, sizeBytes = 8 }) :: Layout + +local readu8, readu32, readstring = buffer.readu8, buffer.readu32, buffer.readstring + +local function printable4(b: buffer, p: number, limit: number): boolean + if p + 4 > limit then + return false + end + for i = 0, 3 do + local c = readu8(b, p + i) + if c < 32 or c > 126 then + return false + end + end + return true +end +Chunks.printable4 = printable4 + +local function u32(b: buffer, o: number, be: boolean): number + local v = readu32(b, o) + return if be then bit32.byteswap(v) else v +end + +-- walk(b, p, limit, layout?) -> { Chunk } of [p, limit) +function Chunks.walk(b: buffer, p: number, limit: number, layout: Layout?): { Chunk } + local L: Layout = layout or Chunks.RIFF + local be = L.bigEndian == true + local sizeBytes = L.sizeBytes or 4 + local head = 4 + sizeBytes + local trailer = L.trailer or 0 + local pad = L.pad or 1 + local openEnded = L.openEnded + local resize = L.resize + local maxChunks = L.maxChunks or 100000 + local list: { Chunk } = {} + limit = math.min(limit, buffer.len(b)) + while p + head <= limit and #list < maxChunks do + local idAt = if L.sizeFirst then p + sizeBytes else p + local sizeAt = if L.sizeFirst then p else p + 4 + local id = readstring(b, idAt, 4) + local declared + if sizeBytes == 8 then + local hi, lo = u32(b, sizeAt, be), u32(b, sizeAt + 4, be) + if not be then + hi, lo = lo, hi + end + declared = hi * 4294967296 + lo + else + declared = u32(b, sizeAt, be) + end + local size = declared + if resize then + size = resize(id, declared) or declared + end + local body = p + head + local avail = limit - body + local c: Chunk = { + id = id, + start = p, + offset = body, + size = size, + declared = declared, + avail = math.min(size, avail), + truncated = false, + streamed = false, + } + table.insert(list, c) + if openEnded and openEnded[id] and (size == 0 or size == 0xFFFFFFFF or size > avail) then + c.streamed = size == 0 or size == 0xFFFFFFFF + c.truncated = not c.streamed + c.size, c.avail = avail, avail + break + end + if size + trailer > avail then + c.truncated = true -- (the body or its trailer runs past the end) + break + end + local rem = size % pad + local nextPos = body + size + trailer + (if rem > 0 then pad - rem else 0) + if L.lenientPad and rem > 0 and not printable4(b, nextPos, limit) and printable4(b, body + size + trailer, limit) then + nextPos = body + size + trailer + end + p = nextPos + end + return list +end + +-- find(list, id, from?) -> the first chunk with that id at index >= from (default 1), its index +function Chunks.find(list: { Chunk }, id: string, from: number?): (Chunk?, number?) + for i = from or 1, #list do + if list[i].id == id then + return list[i], i + end + end + return nil, nil +end + +return Chunks diff --git a/src/Formats/containers/Riff/init.luau b/src/Formats/containers/Riff/init.luau index 63fd4d1..464e88e 100644 --- a/src/Formats/containers/Riff/init.luau +++ b/src/Formats/containers/Riff/init.luau @@ -1,7 +1,7 @@ --!strict -- containers/Riff: the RIFF chunk container (RIFF, RIFX big-endian, RF64 / BW64 with the ds64 chunk), read leniently -- and written. Shared by audio/wav and the other RIFF forms (AVI, WebP, ANI, ...). The chunk walker comes from --- wav-luau fd9a909 (same author, no third-party code); the writer is new. +-- wav-luau fd9a909 (same author, no third-party code), now the RIFF layout of containers/Chunks; the writer is new. -- -- local f, err = Riff.read(r, { openEnded = { data = true } }) -- r: a core/Bytes Reader or a buffer -- f.container, f.form, f.bigEndian -- "RIFF" | "RIFX" | "RF64", "WAVE", false @@ -20,6 +20,7 @@ -- 0xFFFFFFFF come from the ds64 chunk (and its table). Never throws: bad data returns nil, Err. local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") +local Chunks = require("@formats/containers/Chunks") local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring @@ -27,6 +28,7 @@ local Riff = {} export type Chunk = { id: string, + start: number, -- absolute offset of the chunk header offset: number, -- absolute offset of the body in the file's buffer size: number, -- declared size (ds64-resolved), or what is available for open-ended / truncated chunks declared: number, -- the raw size field @@ -51,19 +53,6 @@ export type ReadOptions = { } -- ------------------------------------------------------------------------------------------------ read -local function printable4(b: buffer, p: number, limit: number): boolean - if p + 4 > limit then - return false - end - for i = 0, 3 do - local c = readu8(b, p + i) - if c < 32 or c > 126 then - return false - end - end - return true -end - local function u32(b: buffer, o: number, be: boolean): number local v = readu32(b, o) return if be then bit32.byteswap(v) else v @@ -79,43 +68,25 @@ function Riff.sniff(r: any): string? return if #form == 4 then form else nil end --- walk the chunks of [p, limit) into list; returns the list -local function walk(b: buffer, p: number, limit: number, be: boolean, opts: ReadOptions?, ds64: any, list: { Chunk }): { Chunk } - local openEnded = opts and opts.openEnded - local maxChunks = opts and opts.maxChunks or 100000 - while p + 8 <= limit and #list < maxChunks do - local id = readstring(b, p, 4) - local declared = u32(b, p + 4, be) - local size = declared - local body = p + 8 - local avail = limit - body - if declared == 0xFFFFFFFF and ds64 then - if id == "data" then - size = ds64.dataSize - elseif ds64.table[id] then - size = ds64.table[id] +-- walk(b, p, limit, be, opts, ds64) -> the chunks of [p, limit): containers/Chunks with the RIFF layout (padding to 2, +-- lenient missing pad bytes, open-ended ids, RF64 sizes from ds64) +local function walk(b: buffer, p: number, limit: number, be: boolean, opts: ReadOptions?, ds64: any): { Chunk } + local layout: Chunks.Layout = { + bigEndian = be, + pad = 2, + lenientPad = true, + openEnded = opts and opts.openEnded, + maxChunks = opts and opts.maxChunks, + resize = if ds64 + then function(id: string, declared: number): number? + if declared ~= 0xFFFFFFFF then + return nil + end + return if id == "data" then ds64.dataSize else ds64.table[id] end - end - local c: Chunk = { id = id, offset = body, size = size, declared = declared, avail = math.min(size, avail), truncated = false, streamed = false } - table.insert(list, c) - if openEnded and openEnded[id] and (size == 0 or size == 0xFFFFFFFF or size > avail) then - c.streamed = size == 0 or size == 0xFFFFFFFF - c.truncated = not c.streamed - c.size, c.avail = avail, avail - break - end - if size > avail then - c.truncated = true - break - end - local nextPos = body + size + size % 2 - -- an odd-sized chunk written without its pad byte: the next id starts right after the body - if size % 2 == 1 and not printable4(b, nextPos, limit) and printable4(b, body + size, limit) then - nextPos = body + size - end - p = nextPos - end - return list + else nil, + } + return Chunks.walk(b, p, limit, layout) :: any end -- read(src, opts?) -> File | nil, Err. src: a core/Bytes Reader (its range) or a buffer. @@ -172,7 +143,7 @@ function Riff.read(src: any, opts: ReadOptions?): (File?, Err.Err?) end end end - walk(b, base + 12, limit, be, opts, f.ds64, f.chunks) + f.chunks = walk(b, base + 12, limit, be, opts, f.ds64) return f, nil end @@ -199,7 +170,7 @@ function Riff.list(f: File, c: Chunk, opts: ReadOptions?): { Chunk } if c.avail < 4 then return {} end - return walk(f.buf, c.offset + 4, c.offset + c.avail, f.bigEndian, opts, nil, {}) + return walk(f.buf, c.offset + 4, c.offset + c.avail, f.bigEndian, opts, nil) end -- body(file, chunk) -> a Reader over the chunk's available body diff --git a/src/Formats/containers/Zip/init.luau b/src/Formats/containers/Zip/init.luau index df38c88..0fcf385 100644 --- a/src/Formats/containers/Zip/init.luau +++ b/src/Formats/containers/Zip/init.luau @@ -5,7 +5,7 @@ -- archive comment), the central directory, ZIP64 (records, locator, extra fields), a prefix shift (self-extractor -- stubs), stored and deflated entries with a CRC-32 check, data descriptors, a wrong local header fallback, -- case-insensitive / basename lookup that skips __MACOSX. The DEFLATE codec is now required directly --- (codecs/Deflate) instead of injected. The writer is new: stored / deflated entries (codecs/Deflate compress, stored +-- (codecs/compress/Deflate) instead of injected. The writer is new: stored / deflated entries (codecs/compress/Deflate compress, stored -- when that is not smaller), UTF-8 names, DOS times, raw copies of existing entries, ZIP64 when needed. -- -- local zip, err = Zip.open(buf) -- buffer, string or core/Bytes Reader @@ -21,7 +21,7 @@ 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 Zip = {} Zip.version = "1.1.0" diff --git a/src/Formats/core/Bits.luau b/src/Formats/core/Bits.luau index ca79f13..f844466 100644 --- a/src/Formats/core/Bits.luau +++ b/src/Formats/core/Bits.luau @@ -5,7 +5,7 @@ -- -- Plain arithmetic on an accumulator of at most 31 bits (no bit32 calls), exact on doubles, cheap on both runtimes. -- These are the generic, convenient readers: a codec's innermost loop usually keeps its own local bit buffer (see --- codecs/Deflate/Inflate) and uses these for headers. +-- codecs/compress/Deflate/Inflate) and uses these for headers. -- -- Never throws: reading past the end returns zero bits and sets the sticky `err` (Err.TRUNCATED). -- diff --git a/src/Formats/core/Err.luau b/src/Formats/core/Err.luau index 784a545..f5d8337 100644 --- a/src/Formats/core/Err.luau +++ b/src/Formats/core/Err.luau @@ -56,7 +56,7 @@ function Err.from(message: any, offset: number?, kind: string?): Err return message end local msg = if message == nil then "failed" else tostring(message) - local code = kind and KIND[kind] + local code: string? = kind and KIND[kind] if not code then local head, rest = string.match(msg, "^(%a+):%s*(.*)$") if head and KIND[head] then @@ -71,7 +71,7 @@ function Err.from(message: any, offset: number?, kind: string?): Err code = Err.CORRUPT end end - return Err.new(code, msg, offset) + return Err.new(code :: string, msg, offset) end -- is(v) -> true when v is an Err diff --git a/src/Formats/data/csv/init.luau b/src/Formats/data/csv/init.luau index 8bab313..8a9f4a3 100644 --- a/src/Formats/data/csv/init.luau +++ b/src/Formats/data/csv/init.luau @@ -11,7 +11,7 @@ local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Json = require("@formats/codecs/Json") +local Json = require("@formats/codecs/text/Json") -- ------------------------------------------------------------------------------------------------ contract local Csv = { @@ -19,7 +19,7 @@ local Csv = { category = "data", 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 }, } diff --git a/src/Formats/data/ini/init.luau b/src/Formats/data/ini/init.luau index 14a94c8..bb6f788 100644 --- a/src/Formats/data/ini/init.luau +++ b/src/Formats/data/ini/init.luau @@ -12,7 +12,7 @@ local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Json = require("@formats/codecs/Json") +local Json = require("@formats/codecs/text/Json") -- ------------------------------------------------------------------------------------------------ contract local Ini = { @@ -20,7 +20,7 @@ local Ini = { category = "data", 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 }, } diff --git a/src/Formats/data/json/init.luau b/src/Formats/data/json/init.luau index 78a4df7..e66a95a 100644 --- a/src/Formats/data/json/init.luau +++ b/src/Formats/data/json/init.luau @@ -1,13 +1,13 @@ --!strict --- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/Json (which see for the value mapping and options). +-- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/text/Json (which see for the value mapping and options). -- Supports: decode to plain Luau values (Types.null, ordered keys and bigInts as strings by option), encode compact or --- pretty. JSON Lines through codecs/Json.lines. Not supported: JSON5 / comments / trailing commas. +-- pretty. JSON Lines through codecs/text/Json.lines. Not supported: JSON5 / comments / trailing commas. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") -local Json = require("@formats/codecs/Json") +local Json = require("@formats/codecs/text/Json") -- ------------------------------------------------------------------------------------------------ contract local JsonFormat = { @@ -15,7 +15,7 @@ local JsonFormat = { category = "data", 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 }, } diff --git a/src/Formats/data/plist/init.luau b/src/Formats/data/plist/init.luau index 6f46277..8184dd9 100644 --- a/src/Formats/data/plist/init.luau +++ b/src/Formats/data/plist/init.luau @@ -1,5 +1,5 @@ --!strict --- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/Xml; the write is +-- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/text/Xml; the write is -- byte-identical to Python's plistlib for the same key order) and binary plists ("bplist00", read). Values: dict -> -- Types.object (key order kept), array, string, integer / real -> number, true / false, date -> Types.Date, data -> -- buffer, UID (binary) -> Plist.uid(n). Not supported: binary write, the old OpenStep text format, integers past @@ -9,8 +9,8 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") -local Json = require("@formats/codecs/Json") +local Xml = require("@formats/codecs/text/Xml") +local Json = require("@formats/codecs/text/Json") local Base64 = require("@formats/core/Base64") local Binary = require("@formats/data/plist/Binary") @@ -20,7 +20,7 @@ local Plist = { category = "data", 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 }, } diff --git a/src/Formats/data/toml/Decode.luau b/src/Formats/data/toml/Decode.luau index 8974dd2..0320afb 100644 --- a/src/Formats/data/toml/Decode.luau +++ b/src/Formats/data/toml/Decode.luau @@ -3,7 +3,7 @@ -- their key order; arrays are arrays; datetimes are Types.Date values. Checks the 1.0 validity rules: UTF-8, control -- characters, table / key redefinition (explicit, implicit, dotted, inline and array-of-tables), number grammar and -- 64-bit range, escapes, datetimes. Never throws: failures return nil, message, offset (0-based). -local Text = require("@formats/codecs/Text") +local Text = require("@formats/codecs/text/Text") local Types = require("@formats/Types") local Decode = {} diff --git a/src/Formats/data/toml/Encode.luau b/src/Formats/data/toml/Encode.luau index 664e467..6e654d7 100644 --- a/src/Formats/data/toml/Encode.luau +++ b/src/Formats/data/toml/Encode.luau @@ -5,7 +5,7 @@ -- values as datetimes. Never throws: bad values (null, buffers, functions, cycles, non-string keys) return nil, -- message. local Types = require("@formats/Types") -local Json = require("@formats/codecs/Json") +local Json = require("@formats/codecs/text/Json") local Encode = {} diff --git a/src/Formats/data/toml/init.luau b/src/Formats/data/toml/init.luau index a019400..e0d871d 100644 --- a/src/Formats/data/toml/init.luau +++ b/src/Formats/data/toml/init.luau @@ -19,7 +19,7 @@ local Toml = { category = "data", 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 }, } diff --git a/src/Formats/data/xml/init.luau b/src/Formats/data/xml/init.luau index 6479ec5..dc81104 100644 --- a/src/Formats/data/xml/init.luau +++ b/src/Formats/data/xml/init.luau @@ -1,5 +1,5 @@ --!strict --- data/xml: XML 1.0 files, a thin wrapper over codecs/Xml (which see for the node shape and options). Supports: +-- data/xml: XML 1.0 files, a thin wrapper over codecs/text/Xml (which see for the node shape and options). Supports: -- decode to a "#document" XmlNode tree (doc.root = the root element), encode a document or an element. Not -- supported: external entities / DTDs, validation. @@ -8,7 +8,7 @@ local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") -- ------------------------------------------------------------------------------------------------ contract local XmlFormat = { @@ -16,7 +16,7 @@ local XmlFormat = { category = "data", 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 }, } diff --git a/src/Formats/data/yaml/Parse.luau b/src/Formats/data/yaml/Parse.luau index 172ae04..ff9bd1a 100644 --- a/src/Formats/data/yaml/Parse.luau +++ b/src/Formats/data/yaml/Parse.luau @@ -6,7 +6,7 @@ -- opts.tags = "ignore"), %YAML / %TAG directives, multi-document streams, comments. Scalars resolve with the core -- schema. Not supported: complex keys ("? "), collections as keys, recursive aliases, merge keys "<<" (kept as a -- normal key). Internally raises { yamlErr } tables caught by run(); never throws past it. -local Text = require("@formats/codecs/Text") +local Text = require("@formats/codecs/text/Text") local Types = require("@formats/Types") local Base64 = require("@formats/core/Base64") diff --git a/src/Formats/data/yaml/init.luau b/src/Formats/data/yaml/init.luau index 2b888ee..edc5b10 100644 --- a/src/Formats/data/yaml/init.luau +++ b/src/Formats/data/yaml/init.luau @@ -20,7 +20,7 @@ local Yaml = { category = "data", 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 }, } diff --git a/src/Formats/font/ttf/init.luau b/src/Formats/font/ttf/init.luau index 2e81f06..6df1358 100644 --- a/src/Formats/font/ttf/init.luau +++ b/src/Formats/font/ttf/init.luau @@ -1,14 +1,14 @@ --!strict -- font/ttf: TrueType and OpenType fonts (.ttf, .otf with CFF outlines) and collections (.ttc / .otc), read into the --- standard Font (Types.Font) by codecs/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table, --- GPOS pair kerning) and rasterize(glyph, px) through codecs/Raster. Ported from stb_truetype 1.26 (public domain / --- MIT) via imgui-luau's imstb_truetype.lua; see codecs/TrueType. opts.index picks the font of a collection. +-- standard Font (Types.Font) by codecs/font/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table, +-- GPOS pair kerning) and rasterize(glyph, px) through codecs/image/Raster. Ported from stb_truetype 1.26 (public domain / +-- MIT) via imgui-luau's imstb_truetype.lua; see codecs/font/TrueType. opts.index picks the font of a collection. -- Not supported: hinting, variable fonts, bitmap / colour glyphs, GSUB, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local TrueType = require("@formats/codecs/TrueType") +local TrueType = require("@formats/codecs/font/TrueType") -- ------------------------------------------------------------------------------------------------ contract local Ttf = { @@ -16,7 +16,7 @@ local Ttf = { category = "font", 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 }, } diff --git a/src/Formats/font/woff/init.luau b/src/Formats/font/woff/init.luau index 84d8ad9..c20e880 100644 --- a/src/Formats/font/woff/init.luau +++ b/src/Formats/font/woff/init.luau @@ -1,13 +1,13 @@ --!strict -- font/woff: WOFF 1.0 (W3C Recommendation, 2012): an sfnt font whose tables are zlib-compressed one by one. Decoding --- rebuilds the sfnt and reads it through codecs/TrueType (TrueType or CFF outlines, see font/ttf); the extended +-- rebuilds the sfnt and reads it through codecs/font/TrueType (TrueType or CFF outlines, see font/ttf); the extended -- metadata XML is kept in meta.woffMetadata. Written from the spec. Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local Deflate = require("@formats/codecs/Deflate") -local TrueType = require("@formats/codecs/TrueType") +local Deflate = require("@formats/codecs/compress/Deflate") +local TrueType = require("@formats/codecs/font/TrueType") -- ------------------------------------------------------------------------------------------------ contract local Woff = { @@ -15,7 +15,7 @@ local Woff = { category = "font", 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" } }, } diff --git a/src/Formats/font/woff2/Rebuild.luau b/src/Formats/font/woff2/Rebuild.luau index c2668d2..914d34f 100644 --- a/src/Formats/font/woff2/Rebuild.luau +++ b/src/Formats/font/woff2/Rebuild.luau @@ -6,7 +6,7 @@ -- -- Never throws: malformed data returns nil, message. local Bytes = require("@formats/core/Bytes") -local Brotli = require("@formats/codecs/Brotli") +local Brotli = require("@formats/codecs/compress/Brotli") local Rebuild = {} diff --git a/src/Formats/font/woff2/init.luau b/src/Formats/font/woff2/init.luau index 1e697cb..61bfa80 100644 --- a/src/Formats/font/woff2/init.luau +++ b/src/Formats/font/woff2/init.luau @@ -1,12 +1,12 @@ --!strict -- font/woff2: WOFF 2.0 (W3C Recommendation): sfnt tables in one Brotli stream, with the glyf / loca and hmtx --- transforms. Decoding rebuilds the sfnt (font/woff2/Rebuild) and reads it through codecs/TrueType (TrueType or CFF --- outlines, see font/ttf). Written from the spec; Brotli is codecs/Brotli. Not supported: collections, writing. +-- transforms. Decoding rebuilds the sfnt (font/woff2/Rebuild) and reads it through codecs/font/TrueType (TrueType or CFF +-- outlines, see font/ttf). Written from the spec; Brotli is codecs/compress/Brotli. Not supported: collections, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local TrueType = require("@formats/codecs/TrueType") +local TrueType = require("@formats/codecs/font/TrueType") local Rebuild = require("@formats/font/woff2/Rebuild") -- ------------------------------------------------------------------------------------------------ contract @@ -15,7 +15,7 @@ local Woff2 = { category = "font", 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" } }, } diff --git a/src/Formats/image/bmp/init.luau b/src/Formats/image/bmp/init.luau index e21a9fa..4904706 100644 --- a/src/Formats/image/bmp/init.luau +++ b/src/Formats/image/bmp/init.luau @@ -16,7 +16,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Pixels = require("@formats/image/bmp/Pixels") +local Pixels = require("@formats/codecs/image/Pixels") -- ------------------------------------------------------------------------------------------------ contract local Bmp = { @@ -24,7 +24,7 @@ local Bmp = { category = "image", 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 }, } diff --git a/src/Formats/image/gif/init.luau b/src/Formats/image/gif/init.luau index fcd3bfb..a80829b 100644 --- a/src/Formats/image/gif/init.luau +++ b/src/Formats/image/gif/init.luau @@ -3,7 +3,7 @@ -- (global / local colour tables, interlaced rows, LZW minimum code sizes 2..8 and the odd 1, transparency, frames -- smaller than or outside the canvas), animation (Graphic Control Extension delays, disposal none / background / -- previous, NETSCAPE2.0 / ANIMEXTS1.0 loop counts), comments (meta.text.comment); truncated files keep the frames --- read so far (meta.truncated). Encode of rgba8 images and animations (Types.Frame lists) through codecs/Quantize +-- read so far (meta.truncated). Encode of rgba8 images and animations (Types.Frame lists) through codecs/image/Quantize -- (median cut or octree, optional Floyd-Steinberg dithering; exact palettes, so lossless, at <= 256 colours) with -- alpha < 128 as the transparent index. -- Not supported: the plain text extension (skipped), the aspect ratio (kept in meta.source.aspect), the "user input" @@ -17,8 +17,8 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local Lzw = require("@formats/codecs/Lzw") -local Quantize = require("@formats/codecs/Quantize") +local Lzw = require("@formats/codecs/compress/Lzw") +local Quantize = require("@formats/codecs/image/Quantize") local Types = require("@formats/Types") local Decode = require("@formats/image/gif/Decode") @@ -28,7 +28,7 @@ local Gif = { category = "image", 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 } }, } diff --git a/src/Formats/image/ico/Dib.luau b/src/Formats/image/ico/Dib.luau index 447fa5e..7bc2f2c 100644 --- a/src/Formats/image/ico/Dib.luau +++ b/src/Formats/image/ico/Dib.luau @@ -4,8 +4,11 @@ -- image/ico/Dib: the BMP device-independent bitmaps inside ICO / CUR entries (native; never throws). Written from -- the Microsoft ICO / BITMAPINFOHEADER documentation: a colour (XOR) bitmap of 1 / 4 / 8 / 16 (5-5-5) / 24 / 32-bit -- pixels, bottom-up rows padded to 4 bytes, then a 1-bit AND mask (1 = transparent). 32-bit entries use their alpha --- channel unless it is all zero (old icons), in which case the AND mask decides. -local readu8, readu16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32 +-- channel unless it is all zero (old icons), in which case the AND mask decides. The row loops are +-- codecs/image/Pixels (shared with BMP); the AND mask and the alpha rule are ICO's. +local Pixels = require("@formats/codecs/image/Pixels") + +local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32 local Dib = {} @@ -18,29 +21,19 @@ function Dib.decode(b: buffer, p: number, e: number, w: number, h: number, bpp: end local hasMask = p + stride * h + maskStride * h <= e local anyAlpha = false - for y = 0, h - 1 do - local row = p + (h - 1 - y) * stride - for x = 0, w - 1 do - local v - if bpp == 32 then - v = readu8(b, row + x * 4 + 2) + readu8(b, row + x * 4 + 1) * 256 + readu8(b, row + x * 4) * 65536 + readu8(b, row + x * 4 + 3) * 16777216 - if v >= 16777216 then - anyAlpha = true - end - elseif bpp == 24 then - v = readu8(b, row + x * 3 + 2) + readu8(b, row + x * 3 + 1) * 256 + readu8(b, row + x * 3) * 65536 + 0xFF000000 - elseif bpp == 16 then - local s = readu16(b, row + x * 2) - local r, g, bl = (s // 1024) % 32, (s // 32) % 32, s % 32 - v = (r * 255 + 15) // 31 + ((g * 255 + 15) // 31) * 256 + ((bl * 255 + 15) // 31) * 65536 + 0xFF000000 - else - local bit = x * bpp - local byte = readu8(b, row + bit // 8) - local idx = (byte // 2 ^ (8 - bpp - bit % 8)) % 2 ^ bpp - v = if idx < palN then readu32(pal, idx * 4) else 0xFF000000 - end - writeu32(out, (y * w + x) * 4, v) + if bpp == 32 then + anyAlpha = Pixels.bgra32(b, p, stride, out, w, h, false) ~= 0 + elseif bpp == 24 then + Pixels.bgr24(b, p, stride, out, w, h, false) + elseif bpp == 16 then + Pixels.rgb555(b, p, stride, out, w, h, false) + else + -- palette indexes past palN read as opaque black + local full = buffer.create(1024) + for i = 0, 255 do + writeu32(full, i * 4, if i < palN then readu32(pal, i * 4) else 0xFF000000) end + Pixels.indexed(b, p, stride, bpp, out, w, h, false, full) end if bpp == 32 and anyAlpha then return true, nil diff --git a/src/Formats/image/ico/init.luau b/src/Formats/image/ico/init.luau index ba4085d..e614446 100644 --- a/src/Formats/image/ico/init.luau +++ b/src/Formats/image/ico/init.luau @@ -22,7 +22,7 @@ local Ico = { category = "image", 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 } }, } diff --git a/src/Formats/image/jpeg/init.luau b/src/Formats/image/jpeg/init.luau index aeffeea..b597f5d 100644 --- a/src/Formats/image/jpeg/init.luau +++ b/src/Formats/image/jpeg/init.luau @@ -1,5 +1,5 @@ --!strict --- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/Jpeg (the engine, shared with the Motion-JPEG +-- image/jpeg: JPEG / JFIF / EXIF (ITU T.81), a thin format over codecs/image/Jpeg (the engine, shared with the Motion-JPEG -- video tracks; absorbed from jpeg-luau 1.0, same author, bit-exact with libjpeg-turbo's djpeg and byte-identical -- with cjpeg; IJG-derived parts: licenses/libjpeg-turbo-LICENSE.md). This module is the contract, the sniff, the -- options and the meta segments: meta.exif (APP1), meta.icc (APP2 chunks), meta.text.comment (COM) and meta.dpi @@ -20,7 +20,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Codec = require("@formats/codecs/Jpeg") +local Codec = require("@formats/codecs/image/Jpeg") -- ------------------------------------------------------------------------------------------------ contract local Jpeg = { @@ -28,7 +28,7 @@ local Jpeg = { category = "image", 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 }, } diff --git a/src/Formats/image/png/init.luau b/src/Formats/image/png/init.luau index 117ff4f..f6f2c05 100644 --- a/src/Formats/image/png/init.luau +++ b/src/Formats/image/png/init.luau @@ -14,8 +14,9 @@ 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 Types = require("@formats/Types") +local Chunks = require("@formats/containers/Chunks") local Decode = require("@formats/image/png/Decode") local Encode = require("@formats/image/png/Encode") local Apng = require("@formats/image/png/Apng") @@ -26,7 +27,7 @@ local Png = { category = "image", 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 } }, } @@ -193,13 +194,15 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E local animPixels = 0 local p = r.base + 8 local first = true - while p + 12 <= n do - local len = be32(b, p) - local typ = buffer.readstring(b, p + 4, 4) - if len > n - p - 12 then + for _, c in Chunks.walk(b, p, n, Chunks.PNG) do + local len, typ, d = c.size, c.id, c.offset + p = c.start + if c.truncated then + if p + 12 > n then + break -- not even a whole chunk header + CRC left (a cut tail) + end return nil, Err.new(Err.TRUNCATED, "chunk " .. typ .. " runs past the end", p) end - local d = p + 8 if checkCrc then local want = be32(b, d + len) if Crc32.raw(b, p + 4, len + 4) ~= want then @@ -305,7 +308,6 @@ function Png.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.E elseif bit32.band(readu8(b, p + 4), 0x20) == 0 and typ ~= "IHDR" then return nil, Err.new(Err.UNSUPPORTED, "unknown critical chunk " .. typ, p) end - p = d + len + 4 end if #idat == 0 then return nil, Err.new(Err.TRUNCATED, "no image data", p) diff --git a/src/Formats/image/tiff/init.luau b/src/Formats/image/tiff/init.luau index a44f977..549b166 100644 --- a/src/Formats/image/tiff/init.luau +++ b/src/Formats/image/tiff/init.luau @@ -1,7 +1,7 @@ --!strict -- image/tiff: TIFF 6.0 (+ Adobe technote 3 floating point, BigTIFF). New code from the TIFF 6.0 specification. -- Decode: both byte orders, classic and BigTIFF, strips and tiles, planar configuration 1 and 2, compression none / --- LZW (codecs/Lzw, also old-style) / Deflate (8 and 32946, codecs/Deflate) / PackBits, JPEG (7) through the api's +-- LZW (codecs/compress/Lzw, also old-style) / Deflate (8 and 32946, codecs/compress/Deflate) / PackBits, JPEG (7) through the api's -- opts.decodeImage hook (JPEGTables stitched to each strip / tile), predictors 2 (8 / 16 / 32-bit) and 3 (float), -- 1..32-bit unsigned / signed integer and 16 / 32 / 64-bit float samples, min-is-white / min-is-black, RGB, palette, -- CMYK (naive conversion), extra samples (associated alpha is un-premultiplied), fill order 2, every page as @@ -15,8 +15,8 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Deflate = require("@formats/codecs/Deflate") -local Lzw = require("@formats/codecs/Lzw") +local Deflate = require("@formats/codecs/compress/Deflate") +local Lzw = require("@formats/codecs/compress/Lzw") local Pixels = require("@formats/image/tiff/Pixels") -- ------------------------------------------------------------------------------------------------ contract @@ -25,7 +25,7 @@ local Tiff = { category = "image", 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 }, } diff --git a/src/Formats/image/webp/Alpha.luau b/src/Formats/image/webp/Alpha.luau index 5da90de..9541342 100644 --- a/src/Formats/image/webp/Alpha.luau +++ b/src/Formats/image/webp/Alpha.luau @@ -3,7 +3,7 @@ -- image/webp/Alpha: the ALPH chunk (RFC 9649 section 2.7.1.2): header byte (compression, filter, pre-processing), -- raw or VP8L-compressed alpha (the green channel of a headerless VP8L stream), and the horizontal / vertical / -- gradient unfilters of libwebp src/dsp/filters.c (BSD-3-Clause, licenses/libwebp-LICENSE.txt). Never throws. -local Vp8L = require("@formats/codecs/Vp8L") +local Vp8L = require("@formats/codecs/image/Vp8L") local readu8, writeu8 = buffer.readu8, buffer.writeu8 diff --git a/src/Formats/image/webp/init.luau b/src/Formats/image/webp/init.luau index 9834b1c..a5b09c9 100644 --- a/src/Formats/image/webp/init.luau +++ b/src/Formats/image/webp/init.luau @@ -1,6 +1,6 @@ --!strict -- image/webp: WebP (RFC 9649; Google's "WebP Container Specification"). New code: the bitstreams are ports of libwebp 1.6 --- (codecs/Vp8, codecs/Vp8L; BSD-3-Clause, licenses/libwebp-LICENSE.txt), the chunks go through containers/Riff, the +-- (codecs/image/Vp8, codecs/image/Vp8L; BSD-3-Clause, licenses/libwebp-LICENSE.txt), the chunks go through containers/Riff, the -- container rules and the compositing follow libwebp's demux / WebPAnimDecoder. -- Supports: decode of lossy (VP8 key frames: bit-exact with dwebp, fancy or point chroma upsampling, or the raw -- yuv420p planes with opts.native), lossless (VP8L, bit-exact), alpha (ALPH raw or lossless, every filter), the @@ -18,8 +18,8 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Vp8 = require("@formats/codecs/Vp8") -local Vp8L = require("@formats/codecs/Vp8L") +local Vp8 = require("@formats/codecs/image/Vp8") +local Vp8L = require("@formats/codecs/image/Vp8L") local Riff = require("@formats/containers/Riff") local Alpha = require("@formats/image/webp/Alpha") local Anim = require("@formats/image/webp/Anim") @@ -30,7 +30,7 @@ local Webp = { category = "image", 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 } }, } @@ -134,7 +134,7 @@ end -- subChunks(f, c) -> the chunks inside an ANMF payload (after its 16-byte header) local function subChunks(f: Riff.File, c: Chunk): ({ Chunk }?, Err.Err?) local n = c.size - 12 - return convert(Riff.list(f, { id = c.id, offset = c.off + 12, size = n, declared = n, avail = n, truncated = false, streamed = false })) + return convert(Riff.list(f, { id = c.id, start = c.off + 4, offset = c.off + 12, size = n, declared = n, avail = n, truncated = false, streamed = false })) end type Bitstream = { rgba: buffer?, yuv: Types.Image?, w: number, h: number, hasAlpha: boolean, source: { [string]: any } } diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 407aec5..4f90979 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -20,7 +20,7 @@ local Bytes = require("@formats/core/Bytes") local Input = require("@formats/core/Input") local Types = require("@formats/Types") local Registry = require("@formats/Registry") -local Video = require("@formats/codecs/Video") +local Video = require("@formats/codecs/video/Video") local AudioWrap = require("@formats/containers/AudioWrap") local ImageOps = require("@formats/ops/ImageOps") local host = require("@formats/host") @@ -648,7 +648,7 @@ end F.video.fromFrames = function(images: any, delays: any?, opts: Options?): (any, Err.Err?) return Video.fromFrames(images, delays, opts) end --- F.video.codecs: the video codec registry (codecs/Video: register / entry / fromFourcc / fromMatroska / decoder) +-- F.video.codecs: the video codec registry (codecs/video/Video: register / entry / fromFourcc / fromMatroska / decoder) F.video.codecs = Video -- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or diff --git a/src/Formats/layered/aseprite/init.luau b/src/Formats/layered/aseprite/init.luau index 6799137..04f2f8b 100644 --- a/src/Formats/layered/aseprite/init.luau +++ b/src/Formats/layered/aseprite/init.luau @@ -17,7 +17,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") -- ------------------------------------------------------------------------------------------------ contract local Aseprite = { @@ -25,7 +25,7 @@ local Aseprite = { category = "layered", 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 } }, } diff --git a/src/Formats/layered/psd/Channels.luau b/src/Formats/layered/psd/Channels.luau index b44657e..811f076 100644 --- a/src/Formats/layered/psd/Channels.luau +++ b/src/Formats/layered/psd/Channels.luau @@ -4,7 +4,7 @@ -- plane of big-endian samples, converts planes to rgba8 for every colour mode, and PackBits-encodes rows for the -- writer. Adobe Photoshop File Formats Specification (2016), "Channel image data" / "Image data section". -- Never throws: every read is range-checked first; failures return nil, "message". -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") local Channels = {} diff --git a/src/Formats/layered/psd/init.luau b/src/Formats/layered/psd/init.luau index af510e7..af83e5f 100644 --- a/src/Formats/layered/psd/init.luau +++ b/src/Formats/layered/psd/init.luau @@ -5,7 +5,7 @@ -- opacity, fill opacity (iOpa), visibility, clipping, Unicode names (luni), user masks (as grey masks), groups (lsct / -- lsdk section dividers -> group layers with children; pass-through kept as the "passThrough" blend); the merged image -- (meta.composite); image resources (meta.resources, ICC profile in meta.icc). Everything converts to rgba8. --- Encode: an 8-bit RGB PSD (PSB when a side is over 30000) with the RLE merged composite (ops-free: codecs/Blend +-- Encode: an 8-bit RGB PSD (PSB when a side is over 30000) with the RLE merged composite (ops-free: codecs/image/Blend -- flattens the tree, or opts.composite) and every layer as RLE RGBA channels, groups as section dividers, masks, -- clipping, opacity / fill, hidden flags and Unicode names. -- Not supported: adjustment / fill / type / smart-object layer contents (their pixels, if any, are used), layer @@ -15,7 +15,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Blend = require("@formats/codecs/Blend") +local Blend = require("@formats/codecs/image/Blend") local Channels = require("@formats/layered/psd/Channels") -- ------------------------------------------------------------------------------------------------ contract @@ -24,7 +24,7 @@ local Psd = { category = "layered", 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 } }, } @@ -34,7 +34,7 @@ export type DecodeOptions = { maxLayers: number?, -- default 10000 } export type EncodeOptions = { - composite: Types.Image?, -- the merged image to store (default: the layers flattened with codecs/Blend) + composite: Types.Image?, -- the merged image to store (default: the layers flattened with codecs/image/Blend) } -- ------------------------------------------------------------------------------------------------ constants diff --git a/src/Formats/model/3mf/Read.luau b/src/Formats/model/3mf/Read.luau index 710de1c..2239bf7 100644 --- a/src/Formats/model/3mf/Read.luau +++ b/src/Formats/model/3mf/Read.luau @@ -8,7 +8,7 @@ -- texture groups give per-corner COLOR_0 / TEXCOORD_0, so vertices are split where corners of one vertex differ. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Zip = require("@formats/containers/Zip") local Read = {} diff --git a/src/Formats/model/3mf/Write.luau b/src/Formats/model/3mf/Write.luau index a1f4f4b..80b5c64 100644 --- a/src/Formats/model/3mf/Write.luau +++ b/src/Formats/model/3mf/Write.luau @@ -7,7 +7,7 @@ -- Units: meta.unit picks the 3MF unit when it is one of them; otherwise millimetres and the build transforms scale. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Zip = require("@formats/containers/Zip") local Write = {} diff --git a/src/Formats/model/3mf/init.luau b/src/Formats/model/3mf/init.luau index 025a695..213c037 100644 --- a/src/Formats/model/3mf/init.luau +++ b/src/Formats/model/3mf/init.luau @@ -1,7 +1,7 @@ --!strict -- model/3mf: 3D Manufacturing Format (3MF Consortium core specification 1.3, materials and properties extension 1.2, -- production extension 1.1 part references). New code. An OPC package (containers/Zip) holding XML model parts --- (codecs/Xml). +-- (codecs/text/Xml). -- Reads: the root model part (_rels/.rels), objects (mesh vertices / triangles; components with transforms, also from -- other model parts through p:path), build items -> root nodes with their transforms (3MF's row-vector 4x3 matrices -- become column-major node.matrix), object names / types / part numbers (node / mesh extras["3mf"]), metadata @@ -31,7 +31,7 @@ local ThreeMf = { category = "model", 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 }, } diff --git a/src/Formats/model/dae/Math.luau b/src/Formats/model/dae/Math.luau index 594a53b..dbc2a1c 100644 --- a/src/Formats/model/dae/Math.luau +++ b/src/Formats/model/dae/Math.luau @@ -1,79 +1,11 @@ --!strict --- model/dae/Math: the matrix helpers the Collada reader and writer share. Matrices are flat arrays of 16 in glTF's --- column-major order (Collada writes row-major: fromRows / toRows convert). Quaternions are { x, y, z, w }. +-- model/dae/Math: the Collada-specific transform elements (, ); everything else (matrices, +-- quaternions, decomposition) is codecs/model/Mat4. Matrices are flat arrays of 16 in column-major order. +local Mat4 = require("@formats/codecs/model/Mat4") + local DaeMath = {} -local sqrt, abs, rad, sin, cos = math.sqrt, math.abs, math.rad, math.sin, math.cos - -function DaeMath.identity(): { number } - return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } -end - --- fromRows(v, at?) -> column-major from 16 row-major values starting at v[at] (default 1) -function DaeMath.fromRows(v: { number }, at: number?): { number } - local o = (at or 1) - 1 - local m = table.create(16, 0) - for r = 0, 3 do - for c = 0, 3 do - m[c * 4 + r + 1] = v[o + r * 4 + c + 1] or (if r == c then 1 else 0) - end - end - return m -end - -function DaeMath.toRows(m: { number }): { number } - local v = table.create(16, 0) - for r = 0, 3 do - for c = 0, 3 do - v[r * 4 + c + 1] = m[c * 4 + r + 1] - end - end - return v -end - -function DaeMath.mul(a: { number }, b: { number }): { number } - local m = table.create(16, 0) - for col = 0, 3 do - for row = 0, 3 do - local s = 0 - for k = 0, 3 do - s += a[k * 4 + row + 1] * b[col * 4 + k + 1] - end - m[col * 4 + row + 1] = s - end - end - return m -end - -function DaeMath.translation(x: number, y: number, z: number): { number } - return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } -end - -function DaeMath.scaling(x: number, y: number, z: number): { number } - return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } -end - --- axisAngle(x, y, z, degrees) -> quaternion -function DaeMath.axisAngle(x: number, y: number, z: number, degrees: number): { number } - local l = sqrt(x * x + y * y + z * z) - if l < 1e-12 then - return { 0, 0, 0, 1 } - end - local h = rad(degrees) / 2 - local s = sin(h) / l - return { x * s, y * s, z * s, cos(h) } -end - -function DaeMath.quatMatrix(q: { number }): { number } - local x, y, z, w = q[1], q[2], q[3], q[4] - local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z - return { - 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0, - 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0, - 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0, - 0, 0, 0, 1, - } -end +local sqrt, rad = math.sqrt, math.rad local function cross(a: { number }, b: { number }): { number } return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] } @@ -101,7 +33,7 @@ function DaeMath.skew(v: { number }): { number } local r = norm({ v[2] or 0, v[3] or 0, v[4] or 0 }) local t = norm({ v[5] or 0, v[6] or 0, v[7] or 0 }) local s = math.tan(a) - local m = DaeMath.identity() + local m = Mat4.identity() -- M = I + s * t * r^T (column-major: m[col*4 + row]) for row = 0, 2 do for col = 0, 2 do @@ -111,78 +43,4 @@ function DaeMath.skew(v: { number }): { number } return m end --- decompose(m) -> translation, rotation, scale | nil (shear, a projective row, or a singular matrix) -function DaeMath.decompose(m: { number }): ({ number }?, { number }?, { number }?) - if abs(m[4]) > 1e-6 or abs(m[8]) > 1e-6 or abs(m[12]) > 1e-6 or abs(m[16] - 1) > 1e-6 then - return nil, nil, nil - end - local c1 = { m[1], m[2], m[3] } - local c2 = { m[5], m[6], m[7] } - local c3 = { m[9], m[10], m[11] } - local sx = sqrt(c1[1] * c1[1] + c1[2] * c1[2] + c1[3] * c1[3]) - local sy = sqrt(c2[1] * c2[1] + c2[2] * c2[2] + c2[3] * c2[3]) - local sz = sqrt(c3[1] * c3[1] + c3[2] * c3[2] + c3[3] * c3[3]) - if sx < 1e-12 or sy < 1e-12 or sz < 1e-12 then - return nil, nil, nil - end - local x, y, z = { c1[1] / sx, c1[2] / sx, c1[3] / sx }, { c2[1] / sy, c2[2] / sy, c2[3] / sy }, { c3[1] / sz, c3[2] / sz, c3[3] / sz } - local dxy = x[1] * y[1] + x[2] * y[2] + x[3] * y[3] - local dxz = x[1] * z[1] + x[2] * z[2] + x[3] * z[3] - local dyz = y[1] * z[1] + y[2] * z[2] + y[3] * z[3] - if abs(dxy) > 1e-4 or abs(dxz) > 1e-4 or abs(dyz) > 1e-4 then - return nil, nil, nil - end - local cr = cross(x, y) - if cr[1] * z[1] + cr[2] * z[2] + cr[3] * z[3] < 0 then - sx = -sx - x = { -x[1], -x[2], -x[3] } - end - -- rotation matrix (columns x, y, z) -> quaternion - local m00, m01, m02 = x[1], y[1], z[1] - local m10, m11, m12 = x[2], y[2], z[2] - local m20, m21, m22 = x[3], y[3], z[3] - local tr = m00 + m11 + m22 - local qx, qy, qz, qw - if tr > 0 then - local s = sqrt(tr + 1) * 2 - qw, qx, qy, qz = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s - elseif m00 > m11 and m00 > m22 then - local s = sqrt(1 + m00 - m11 - m22) * 2 - qw, qx, qy, qz = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s - elseif m11 > m22 then - local s = sqrt(1 + m11 - m00 - m22) * 2 - qw, qx, qy, qz = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s - else - local s = sqrt(1 + m22 - m00 - m11) * 2 - qw, qx, qy, qz = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4 - end - local l = sqrt(qx * qx + qy * qy + qz * qz + qw * qw) - return { m[13], m[14], m[15] }, { qx / l, qy / l, qz / l, qw / l }, { sx, sy, sz } -end - --- transformPoint / transformDir (column-major m) -function DaeMath.point(m: { number }, x: number, y: number, z: number): (number, number, number) - return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] -end - --- the inverse transpose of the upper 3x3 (for normals), as a column-major 4x4 -function DaeMath.normalMatrix(m: { number }): { number } - local a, b, c = m[1], m[5], m[9] - local d, e, f = m[2], m[6], m[10] - local g, h, i = m[3], m[7], m[11] - local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g - local det = a * A + b * B + c * C - if abs(det) < 1e-30 then - return DaeMath.identity() - end - local k = 1 / det - -- inverse = adj / det; its transpose has rows = cofactors - return { - A * k, B * k, C * k, 0, - -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0, - (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0, - 0, 0, 0, 1, - } -end - return DaeMath diff --git a/src/Formats/model/dae/Read.luau b/src/Formats/model/dae/Read.luau index 93ae05f..2d0c857 100644 --- a/src/Formats/model/dae/Read.luau +++ b/src/Formats/model/dae/Read.luau @@ -1,5 +1,5 @@ --!strict --- model/dae/Read: a parsed Collada document (codecs/Xml DOM) -> Scene. Geometry (triangles / polylist / polygons / +-- model/dae/Read: a parsed Collada document (codecs/text/Xml DOM) -> Scene. Geometry (triangles / polylist / polygons / -- lines / linestrips / tristrips / trifans with shared input offsets, de-indexed per index tuple), common-profile -- materials (phong / blinn / lambert / constant -> PBR + extras.phong) with their sampler2D / surface / image chains, -- images (kept encoded through the fetch callback, or embedded hex ), the visual scene's node tree (matrix / @@ -10,9 +10,10 @@ -- channels; one animation per animation clip, else one for the file). local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Base64 = require("@formats/core/Base64") local M = require("@formats/model/dae/Math") +local Mat4 = require("@formats/codecs/model/Mat4") local Read = {} @@ -919,14 +920,14 @@ local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { local pos = copyAccessor(attrs.POSITION) for v = 0, pos.count - 1 do local x, y, z = buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8) - x, y, z = M.point(bindShape, x, y, z) + x, y, z = Mat4.point(bindShape, x, y, z) buffer.writef32(pos.data, v * 12, x) buffer.writef32(pos.data, v * 12 + 4, y) buffer.writef32(pos.data, v * 12 + 8, z) end attrs.POSITION = pos if attrs.NORMAL then - local nm = M.normalMatrix(bindShape) + local nm = Mat4.normalMatrix(bindShape) local nrm = copyAccessor(attrs.NORMAL) for v = 0, nrm.count - 1 do local x, y, z = buffer.readf32(nrm.data, v * 12), buffer.readf32(nrm.data, v * 12 + 4), buffer.readf32(nrm.data, v * 12 + 8) @@ -1126,31 +1127,31 @@ local XFORMS = { matrix = 16, translate = 3, rotate = 4, scale = 3, lookat = 9, -- the matrix of one transform element's values local function xfMatrix(kind: string, v: { number }): { number } if kind == "matrix" then - return M.fromRows(v) + return Mat4.fromRows(v) elseif kind == "translate" then - return M.translation(v[1] or 0, v[2] or 0, v[3] or 0) + return Mat4.translation(v[1] or 0, v[2] or 0, v[3] or 0) elseif kind == "rotate" then - return M.quatMatrix(M.axisAngle(v[1] or 0, v[2] or 0, v[3] or 1, v[4] or 0)) + return Mat4.fromQuat(Mat4.axisAngle(v[1] or 0, v[2] or 0, v[3] or 1, v[4] or 0)) elseif kind == "scale" then - return M.scaling(v[1] or 1, v[2] or 1, v[3] or 1) + return Mat4.scaling(v[1] or 1, v[2] or 1, v[3] or 1) elseif kind == "lookat" then return M.lookat(v) elseif kind == "skew" then return M.skew(v) end - return M.identity() + return Mat4.identity() end local function compose(xf: { any }): { number } - local m = M.identity() + local m = Mat4.identity() for _, x in xf do - m = M.mul(m, xfMatrix(x.kind, x.values)) + m = Mat4.mul(m, xfMatrix(x.kind, x.values)) end return m end local function setTransform(node: Types.Node, m: { number }) - local t, r, s = M.decompose(m) + local t, r, s = Mat4.decomposeStrict(m) node.translation, node.rotation, node.scale, node.matrix = nil, nil, nil, nil if t and r and s then if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then @@ -1164,7 +1165,7 @@ local function setTransform(node: Types.Node, m: { number }) end else for i = 1, 16 do - if math.abs(m[i] - M.identity()[i]) > 0 then + if math.abs(m[i] - Mat4.identity()[i]) > 0 then node.matrix = m break end @@ -1219,7 +1220,7 @@ local function instances(C: Ctx, el: any, node: Types.Node, idx: number) end if src and lname(src) == "geometry" then local bsm = child(skinEl, "bind_shape_matrix") - local bind = if bsm then M.fromRows(numbers(text(bsm), 16) or {}) else nil + local bind = if bsm then Mat4.fromRows(numbers(text(bsm), 16) or {}) else nil local mi, built = meshFor(C, src, ch, "skin:" .. (attr(ctrl, "id") or ""), bind) if C.err then return @@ -1414,7 +1415,7 @@ local function resolveSkins(C: Ctx) if ibm and ibm.comps == 16 and ibm.count >= #names then local b = buffer.create(#names * 64) for i = 0, #names - 1 do - local cm = M.fromRows(ibm.data, i * 16 + 1) + local cm = Mat4.fromRows(ibm.data, i * 16 + 1) for k = 1, 16 do buffer.writef32(b, (i * 16 + k - 1) * 4, cm[k]) end @@ -1715,7 +1716,7 @@ local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, orde end end end - local tr, ro, sc = M.decompose(compose(xf)) + local tr, ro, sc = Mat4.decomposeStrict(compose(xf)) tr, ro, sc = tr or { 0, 0, 0 }, ro or { 0, 0, 0, 1 }, sc or { 1, 1, 1 } if prev and prev[1] * ro[1] + prev[2] * ro[2] + prev[3] * ro[3] + prev[4] * ro[4] < 0 then ro = { -ro[1], -ro[2], -ro[3], -ro[4] } diff --git a/src/Formats/model/dae/Write.luau b/src/Formats/model/dae/Write.luau index 7d8b51c..e9a4831 100644 --- a/src/Formats/model/dae/Write.luau +++ b/src/Formats/model/dae/Write.luau @@ -5,9 +5,9 @@ -- extras.phong; images as files (opts.files), their uri, or data: URIs; the node tree as row-major ; cameras; -- lights. Not written: skins, morph targets, animations. local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Base64 = require("@formats/core/Base64") -local M = require("@formats/model/dae/Math") +local Mat4 = require("@formats/codecs/model/Mat4") local Write = {} @@ -325,7 +325,7 @@ function Write.build(scene: Types.Scene, opts: any?): string? return end seen[i] = true - w(format('%s', i, nameAttr(n.name), list(M.toRows(Scene.nodeMatrix(n))))) + w(format('%s', i, nameAttr(n.name), list(Mat4.toRows(Scene.nodeMatrix(n))))) if n.mesh and geoms[n.mesh] then for _, g in geoms[n.mesh] do if g.material then diff --git a/src/Formats/model/dae/init.luau b/src/Formats/model/dae/init.luau index 735bef9..7aae240 100644 --- a/src/Formats/model/dae/init.luau +++ b/src/Formats/model/dae/init.luau @@ -26,7 +26,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Xml = require("@formats/codecs/Xml") +local Xml = require("@formats/codecs/text/Xml") local Zip = require("@formats/containers/Zip") local Read = require("@formats/model/dae/Read") local Write = require("@formats/model/dae/Write") @@ -37,7 +37,7 @@ local Dae = { category = "model", 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 }, } diff --git a/src/Formats/model/fbx/Binary.luau b/src/Formats/model/fbx/Binary.luau index a1ea942..01880f5 100644 --- a/src/Formats/model/fbx/Binary.luau +++ b/src/Formats/model/fbx/Binary.luau @@ -2,10 +2,10 @@ --!native -- model/fbx/Binary: the binary FBX node tree reader and writer (versions 7.x: 32-bit node records before 7500, 64-bit -- from 7500). From the format as documented by Blender's io_scene_fbx (encode_bin.py / parse_fbx.py) and assimp's --- FBXBinaryTokenizer. Arrays (f, d, l, i, b) are inflated with codecs/Deflate when compressed and kept as Tree.Array +-- FBXBinaryTokenizer. Arrays (f, d, l, i, b) are inflated with codecs/compress/Deflate when compressed and kept as Tree.Array -- values (every element as an f64; 64-bit integers past 2^53 lose precision there); scalar L values past 2^53 become -- the string "L" so ids stay exact. Never throws: errors are returned (nil, message, offset). -local Deflate = require("@formats/codecs/Deflate") +local Deflate = require("@formats/codecs/compress/Deflate") local Binary = {} diff --git a/src/Formats/model/fbx/Read.luau b/src/Formats/model/fbx/Read.luau index aa9ea4d..9d3aeb5 100644 --- a/src/Formats/model/fbx/Read.luau +++ b/src/Formats/model/fbx/Read.luau @@ -14,6 +14,7 @@ local Err = require("@formats/core/Err") local Types = require("@formats/Types") local Base64 = require("@formats/core/Base64") local Xform = require("@formats/model/fbx/Xform") +local Mat4 = require("@formats/codecs/model/Mat4") local Read = {} @@ -486,13 +487,13 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ order = pnum(p, "RotationOrder", 0), } end - local localM: { [number]: Xform.M4 } = {} + local localM: { [number]: Mat4.M4 } = {} for _, o in models do local ni = nodeOf[o.id] local nd = scene.nodes[ni] local m = Xform.localMatrix(xprops(o)) localM[ni] = m - local t, r, s = Xform.decompose(m) + local t, r, s = Mat4.decompose(m) if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then nd.translation = t end @@ -543,9 +544,9 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end -- world matrices (rest pose) - local worldM: { [number]: Xform.M4 } = {} - local function world(i: number, parent: Xform.M4) - worldM[i] = Xform.mul(parent, localM[i] or Xform.identity()) + local worldM: { [number]: Mat4.M4 } = {} + local function world(i: number, parent: Mat4.M4) + worldM[i] = Mat4.mul(parent, localM[i] or Mat4.identity()) for _, c in scene.nodes[i].children do if not worldM[c] then world(c, worldM[i]) @@ -553,7 +554,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end end for _, r in scene.roots do - world(r, Xform.identity()) + world(r, Mat4.identity()) end -- ------------------------------------------------------------------------------------------ meshes @@ -566,7 +567,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end local perCp: { { { number } } } = {} local joints: { number } = {} - local ibms: { Xform.M4 } = {} + local ibms: { Mat4.M4 } = {} for _, cl in sources(skin.id, "Deformer", "Cluster") do local bone = sources(cl.id, "Model")[1] local bi = bone and nodeOf[bone.id] @@ -575,13 +576,13 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ joints[ji] = bi local idx, w = array(cl.node, "Indexes"), array(cl.node, "Weights") local T, TL = array(cl.node, "Transform"), array(cl.node, "TransformLink") - local tm = Xform.identity() + local tm = Mat4.identity() if T and T.count >= 16 then for k = 1, 16 do tm[k] = at(T, k - 1) end end - local tl: Xform.M4? = nil + local tl: Mat4.M4? = nil if TL and TL.count >= 16 then tl = {} for k = 1, 16 do @@ -590,8 +591,8 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ else tl = worldM[bi] end - local inv = Xform.inverse(tl :: Xform.M4) or Xform.identity() - ibms[ji] = Xform.mul(inv, tm) + local inv = Mat4.inverse(tl :: Mat4.M4) or Mat4.identity() + ibms[ji] = Mat4.mul(inv, tm) if idx and w then for k = 0, math.min(idx.count, w.count) - 1 do local cp = at(idx, k) @@ -648,7 +649,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ local nodeSkin: { [number]: number } = {} local skinCache: { [any]: number } = {} - local function buildMesh(geo: Obj, mats: { number }, G: Xform.M4?): (number?, Err.Err?) + local function buildMesh(geo: Obj, mats: { number }, G: Mat4.M4?): (number?, Err.Err?) local g = geo.node local verts = array(g, "Vertices") local pvi = array(g, "PolygonVertexIndex") @@ -784,15 +785,15 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ table.sort(slots) local perCp, skin = skinOf(geo) local shapes = shapesOf(geo) - local N3: Xform.M4? = nil -- normal matrix (inverse transpose of G) + local N3: Mat4.M4? = nil -- normal matrix (inverse transpose of G) if G then - local inv = Xform.inverse(G) + local inv = Mat4.inverse(G) if inv then N3 = { inv[1], inv[5], inv[9], 0, inv[2], inv[6], inv[10], 0, inv[3], inv[7], inv[11], 0, 0, 0, 0, 1 } end end local mesh: Types.Mesh = { name = geo.name, primitives = {} } - local function v3(dst: buffer, o: number, x: number, y: number, z: number, M: Xform.M4?, w: number) + local function v3(dst: buffer, o: number, x: number, y: number, z: number, M: Mat4.M4?, w: number) if M then x, y, z = M[1] * x + M[5] * y + M[9] * z + M[13] * w, M[2] * x + M[6] * y + M[10] * z + M[14] * w, M[3] * x + M[7] * y + M[11] * z + M[15] * w end @@ -1012,9 +1013,9 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ local gt = pvec(o.props, "GeometricTranslation", { 0, 0, 0 }) local gr = pvec(o.props, "GeometricRotation", { 0, 0, 0 }) local gsc = pvec(o.props, "GeometricScaling", { 1, 1, 1 }) - local G: Xform.M4? = nil + local G: Mat4.M4? = nil if gt[1] ~= 0 or gt[2] ~= 0 or gt[3] ~= 0 or gr[1] ~= 0 or gr[2] ~= 0 or gr[3] ~= 0 or gsc[1] ~= 1 or gsc[2] ~= 1 or gsc[3] ~= 1 then - G = Xform.mul(Xform.translate(gt[1], gt[2], gt[3]), Xform.mul(Xform.euler(gr[1], gr[2], gr[3], 0), Xform.scale(gsc[1], gsc[2], gsc[3]))) + G = Mat4.mul(Mat4.translation(gt[1], gt[2], gt[3]), Mat4.mul(Xform.euler(gr[1], gr[2], gr[3], 0), Mat4.scaling(gsc[1], gsc[2], gsc[3]))) end for _, geo in sources(o.id, "Geometry") do if geo.sub == "Mesh" or geo.sub == "" then @@ -1294,7 +1295,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ end over[key] = v end - local tt, rr, ss = Xform.decompose(Xform.localMatrix(xprops(o, over))) + local tt, rr, ss = Mat4.decompose(Xform.localMatrix(xprops(o, over))) if prevQ and rr[1] * prevQ[1] + rr[2] * prevQ[2] + rr[3] * prevQ[3] + rr[4] * prevQ[4] < 0 then rr = { -rr[1], -rr[2], -rr[3], -rr[4] } end diff --git a/src/Formats/model/fbx/Write.luau b/src/Formats/model/fbx/Write.luau index 6d16eab..82a4371 100644 --- a/src/Formats/model/fbx/Write.luau +++ b/src/Formats/model/fbx/Write.luau @@ -8,7 +8,7 @@ -- BlendShape / BlendShapeChannel / Shape; animations -> AnimationStack / Layer / CurveNode / Curve. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Xform = require("@formats/model/fbx/Xform") +local Mat4 = require("@formats/codecs/model/Mat4") local Write = {} @@ -284,26 +284,26 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) end end -- world matrices (rest pose) for clusters and the bind pose - local worldM: { [number]: Xform.M4 } = {} + local worldM: { [number]: Mat4.M4 } = {} local visiting: { [number]: boolean } = {} - local function world(i: number): Xform.M4 + local function world(i: number): Mat4.M4 if worldM[i] then return worldM[i] end if visiting[i] then - return Xform.identity() + return Mat4.identity() end visiting[i] = true local nd = nodes[i] - local l = if nd.matrix and #(nd.matrix :: Xform.M4) == 16 then nd.matrix else Xform.compose(nd.translation, nd.rotation, nd.scale) + local l = if nd.matrix and #(nd.matrix :: Mat4.M4) == 16 then nd.matrix else Mat4.compose(nd.translation, nd.rotation, nd.scale) local p = parentOf[i] - local w = if p then Xform.mul(world(p), l) else l + local w = if p then Mat4.mul(world(p), l) else l worldM[i] = w return w end local function trs(nd: Types.Node): ({ number }, { number }, { number }) - if nd.matrix and #(nd.matrix :: Xform.M4) == 16 then - return Xform.decompose(nd.matrix) + if nd.matrix and #(nd.matrix :: Mat4.M4) == 16 then + return Mat4.decompose(nd.matrix) end return nd.translation or { 0, 0, 0 }, nd.rotation or { 0, 0, 0, 1 }, nd.scale or { 1, 1, 1 } end @@ -387,7 +387,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) for i, nd in nodes do if not skip[i] then local t, r, s = trs(nd) - local euler = Xform.eulerXYZ(r) + local euler = Mat4.eulerXYZ(r) local ftype = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.type local sub = if nd.mesh then "Mesh" elseif jointSet[i] or ftype == "LimbNode" then "LimbNode" else "Null" -- an orientation child folded into this node gives it its attribute @@ -697,7 +697,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) local poseNodes: { WNode } = {} local posed: { [number]: boolean } = {} - local function pose(mid: number, m: Xform.M4) + local function pose(mid: number, m: Mat4.M4) if posed[mid] then return end @@ -752,14 +752,14 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) for j, ji in skin.joints do local jm = modelIds[ji] if jm then - local IB = Xform.identity() + local IB = Mat4.identity() if ibm and skin.inverseBindMatrices and j <= skin.inverseBindMatrices.count then for k = 1, 16 do IB[k] = ibm(j - 1, k - 1) end end - local inv = Xform.inverse(IB) or Xform.identity() - local link = Xform.mul(meshWorld, inv) + local inv = Mat4.inverse(IB) or Mat4.identity() + local link = Mat4.mul(meshWorld, inv) local cid = id() add("Deformer", N("Deformer", "LSS", { cid, cls(nodes[ji].name, "SubDeformer"), "Cluster" }, { N("Version", "I", { 100 }), @@ -859,7 +859,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) else q = { 0, 0, 0, 1 } end - v = Xform.eulerXYZ(q) + v = Mat4.eulerXYZ(q) if prev then for a = 1, 3 do while v[a] - prev[a] > 180 do diff --git a/src/Formats/model/fbx/Xform.luau b/src/Formats/model/fbx/Xform.luau index a4d734d..bec2b47 100644 --- a/src/Formats/model/fbx/Xform.luau +++ b/src/Formats/model/fbx/Xform.luau @@ -1,80 +1,15 @@ --!strict -- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): the local matrix of a Model --- node T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1, Euler rotations in degrees in the six --- orders, column-major 4x4 matrices (flat arrays of 16, translation at 13..15 as glTF and FBX store them), inverse, --- TRS decomposition (quaternion x, y, z, w) and Euler XYZ from a quaternion (the writer). +-- node T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1, with FBX's numbered Euler orders. The +-- matrix / quaternion arithmetic is codecs/model/Mat4. +local Mat4 = require("@formats/codecs/model/Mat4") + local Xform = {} -export type M4 = { number } - -local rad = math.pi / 180 - -function Xform.identity(): M4 - return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } -end - -function Xform.mul(a: M4, b: M4): M4 - local m = table.create(16, 0) - for col = 0, 3 do - for row = 0, 3 do - m[col * 4 + row + 1] = a[row + 1] * b[col * 4 + 1] + a[4 + row + 1] * b[col * 4 + 2] + a[8 + row + 1] * b[col * 4 + 3] + a[12 + row + 1] * b[col * 4 + 4] - end - end - return m -end - -function Xform.translate(x: number, y: number, z: number): M4 - return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } -end - -function Xform.scale(x: number, y: number, z: number): M4 - return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } -end - -local function rx(a: number): M4 - local c, s = math.cos(a), math.sin(a) - return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 } -end -local function ry(a: number): M4 - local c, s = math.cos(a), math.sin(a) - return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 } -end -local function rz(a: number): M4 - local c, s = math.cos(a), math.sin(a) - return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } -end - -- FBX RotationOrder: 0 XYZ (R = Rz * Ry * Rx: X applied first), 1 XZY, 2 YZX, 3 YXZ, 4 ZXY, 5 ZYX, 6 spheric (= XYZ) local ORDERS = { [0] = "xyz", "xzy", "yzx", "yxz", "zxy", "zyx", "xyz" } -function Xform.euler(x: number, y: number, z: number, order: number?): M4 - local o = ORDERS[order or 0] or "xyz" - local R = { x = rx(x * rad), y = ry(y * rad), z = rz(z * rad) } - local a, b, c = string.sub(o, 1, 1), string.sub(o, 2, 2), string.sub(o, 3, 3) - return Xform.mul(R[c], Xform.mul(R[b], R[a])) -end - --- inverse of an affine matrix (general 3x3 part) | nil when singular -function Xform.inverse(m: M4): M4? - local a, b, c = m[1], m[5], m[9] - local d, e, f = m[2], m[6], m[10] - local g, h, i = m[3], m[7], m[11] - local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g - local det = a * A + b * B + c * C - if det == 0 or det ~= det then - return nil - end - local k = 1 / det - local r = { - A * k, B * k, C * k, 0, - -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0, - (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0, - 0, 0, 0, 1, - } - local tx, ty, tz = m[13], m[14], m[15] - r[13] = -(r[1] * tx + r[5] * ty + r[9] * tz) - r[14] = -(r[2] * tx + r[6] * ty + r[10] * tz) - r[15] = -(r[3] * tx + r[7] * ty + r[11] * tz) - return r +function Xform.euler(x: number, y: number, z: number, order: number?): Mat4.M4 + return Mat4.euler(x, y, z, ORDERS[order or 0] or "xyz") end -- the local matrix of a node from its (already defaulted) FBX properties p: vectors of 3 numbers @@ -86,113 +21,20 @@ export type Props = { local function isZero(v: { number }): boolean return v[1] == 0 and v[2] == 0 and v[3] == 0 end -function Xform.localMatrix(p: Props): M4 - local m = Xform.translate(p.T[1] + p.Roff[1] + p.Rp[1], p.T[2] + p.Roff[2] + p.Rp[2], p.T[3] + p.Roff[3] + p.Rp[3]) +function Xform.localMatrix(p: Props): Mat4.M4 + local m = Mat4.translation(p.T[1] + p.Roff[1] + p.Rp[1], p.T[2] + p.Roff[2] + p.Rp[2], p.T[3] + p.Roff[3] + p.Rp[3]) if not isZero(p.Rpre) then - m = Xform.mul(m, Xform.euler(p.Rpre[1], p.Rpre[2], p.Rpre[3], 0)) + m = Mat4.mul(m, Xform.euler(p.Rpre[1], p.Rpre[2], p.Rpre[3], 0)) end - m = Xform.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order)) + m = Mat4.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order)) if not isZero(p.Rpost) then - local post = Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0) -- the inverse of a rotation is its transpose - local tr = { post[1], post[5], post[9], 0, post[2], post[6], post[10], 0, post[3], post[7], post[11], 0, 0, 0, 0, 1 } - m = Xform.mul(m, tr) + m = Mat4.mul(m, Mat4.transpose3(Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0))) end - m = Xform.mul(m, Xform.translate(-p.Rp[1] + p.Soff[1] + p.Sp[1], -p.Rp[2] + p.Soff[2] + p.Sp[2], -p.Rp[3] + p.Soff[3] + p.Sp[3])) - m = Xform.mul(m, Xform.scale(p.S[1], p.S[2], p.S[3])) + m = Mat4.mul(m, Mat4.translation(-p.Rp[1] + p.Soff[1] + p.Sp[1], -p.Rp[2] + p.Soff[2] + p.Sp[2], -p.Rp[3] + p.Soff[3] + p.Sp[3])) + m = Mat4.mul(m, Mat4.scaling(p.S[1], p.S[2], p.S[3])) if not isZero(p.Sp) then - m = Xform.mul(m, Xform.translate(-p.Sp[1], -p.Sp[2], -p.Sp[3])) - end - return m -end - --- quaternion (x, y, z, w) of a pure rotation matrix -local function quat(m: M4): { number } - local m00, m01, m02 = m[1], m[5], m[9] - local m10, m11, m12 = m[2], m[6], m[10] - local m20, m21, m22 = m[3], m[7], m[11] - local tr = m00 + m11 + m22 - local x, y, z, w - if tr > 0 then - local s = math.sqrt(tr + 1) * 2 - w, x, y, z = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s - elseif m00 > m11 and m00 > m22 then - local s = math.sqrt(math.max(1 + m00 - m11 - m22, 1e-30)) * 2 - w, x, y, z = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s - elseif m11 > m22 then - local s = math.sqrt(math.max(1 + m11 - m00 - m22, 1e-30)) * 2 - w, x, y, z = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s - else - local s = math.sqrt(math.max(1 + m22 - m00 - m11, 1e-30)) * 2 - w, x, y, z = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4 - end - local n = math.sqrt(x * x + y * y + z * z + w * w) - if n == 0 or n ~= n then - return { 0, 0, 0, 1 } - end - return { x / n, y / n, z / n, w / n } -end -Xform.quat = quat - --- decompose(m) -> translation, rotation (quaternion), scale (a negative determinant flips the x scale) -function Xform.decompose(m: M4): ({ number }, { number }, { number }) - local t = { m[13], m[14], m[15] } - local sx = math.sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3]) - local sy = math.sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7]) - local sz = math.sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11]) - local det = m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3]) - if det < 0 then - sx = -sx - end - local ix = if sx ~= 0 then 1 / sx else 0 - local iy = if sy ~= 0 then 1 / sy else 0 - local iz = if sz ~= 0 then 1 / sz else 0 - local r = { m[1] * ix, m[2] * ix, m[3] * ix, 0, m[5] * iy, m[6] * iy, m[7] * iy, 0, m[9] * iz, m[10] * iz, m[11] * iz, 0, 0, 0, 0, 1 } - return t, quat(r), { sx, sy, sz } -end - --- the rotation matrix of a quaternion -function Xform.fromQuat(q: { number }): M4 - local x, y, z, w = q[1], q[2], q[3], q[4] - local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z - return { - 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0, - 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0, - 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0, - 0, 0, 0, 1, - } -end - --- Euler XYZ degrees (R = Rz * Ry * Rx) of a quaternion -function Xform.eulerXYZ(q: { number }): { number } - local m = Xform.fromQuat(q) - -- m[3] = r20 = -sin(y) - local sy = -m[3] - sy = math.clamp(sy, -1, 1) - local y = math.asin(sy) - local x, z - if math.abs(sy) < 0.9999999 then - x = math.atan2(m[7], m[11]) - z = math.atan2(m[2], m[1]) - else - x = math.atan2(-m[10], m[6]) - z = 0 - end - return { x / rad, y / rad, z / rad } -end - --- TRS -> matrix (glTF semantics) -function Xform.compose(t: { number }?, r: { number }?, s: { number }?): M4 - local m = if r then Xform.fromQuat(r) else Xform.identity() - if s then - for k = 0, 2 do - m[k * 4 + 1] *= s[k + 1] - m[k * 4 + 2] *= s[k + 1] - m[k * 4 + 3] *= s[k + 1] - end - end - if t then - m[13], m[14], m[15] = t[1], t[2], t[3] + m = Mat4.mul(m, Mat4.translation(-p.Sp[1], -p.Sp[2], -p.Sp[3])) end return m end diff --git a/src/Formats/model/fbx/init.luau b/src/Formats/model/fbx/init.luau index bf8bfcf..0f615d5 100644 --- a/src/Formats/model/fbx/init.luau +++ b/src/Formats/model/fbx/init.luau @@ -1,6 +1,6 @@ --!strict -- model/fbx: Autodesk FBX 7.x, binary (7.0 - 7.7: 32-bit records before 7500, 64-bit after; zlib-compressed arrays --- through codecs/Deflate) and ASCII. New code, from the format as reverse engineered by Blender's io_scene_fbx and +-- through codecs/compress/Deflate) and ASCII. New code, from the format as reverse engineered by Blender's io_scene_fbx and -- assimp's FBX importer, and the FBX SDK's documentation of the transform model. -- Reads: the node tree (Fbx.tree), then Objects / Connections -> Scene: Model nodes with the full transform (Lcl -- T / R / S, pre / post rotation, rotation / scaling pivots and offsets, the six rotation orders; geometric transforms @@ -35,7 +35,7 @@ local Fbx = { category = "model", 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 }, } diff --git a/src/Formats/model/gltf/init.luau b/src/Formats/model/gltf/init.luau index bf14547..8af711c 100644 --- a/src/Formats/model/gltf/init.luau +++ b/src/Formats/model/gltf/init.luau @@ -20,7 +20,7 @@ local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Json = require("@formats/codecs/Json") +local Json = require("@formats/codecs/text/Json") local Base64 = require("@formats/core/Base64") local Read = require("@formats/model/gltf/Read") local Write = require("@formats/model/gltf/Write") @@ -31,7 +31,7 @@ local Gltf = { category = "model", 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 }, } diff --git a/src/Formats/model/off/init.luau b/src/Formats/model/off/init.luau index 4c3ab8c..1d2c5ba 100644 --- a/src/Formats/model/off/init.luau +++ b/src/Formats/model/off/init.luau @@ -21,7 +21,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Flatten = require("@formats/codecs/MeshFlatten") +local Flatten = require("@formats/codecs/model/MeshFlatten") -- ------------------------------------------------------------------------------------------------ contract local Off = { @@ -29,7 +29,7 @@ local Off = { category = "model", 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 }, } diff --git a/src/Formats/model/ply/init.luau b/src/Formats/model/ply/init.luau index 69ea451..8e118f7 100644 --- a/src/Formats/model/ply/init.luau +++ b/src/Formats/model/ply/init.luau @@ -25,7 +25,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Binary = require("@formats/model/ply/Binary") -local Flatten = require("@formats/codecs/MeshFlatten") +local Flatten = require("@formats/codecs/model/MeshFlatten") -- ------------------------------------------------------------------------------------------------ contract local Ply = { @@ -33,7 +33,7 @@ local Ply = { category = "model", 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 }, } diff --git a/src/Formats/model/stl/init.luau b/src/Formats/model/stl/init.luau index 06147a5..5878daf 100644 --- a/src/Formats/model/stl/init.luau +++ b/src/Formats/model/stl/init.luau @@ -21,7 +21,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Decode = require("@formats/model/stl/Decode") -local Flatten = require("@formats/codecs/MeshFlatten") +local Flatten = require("@formats/codecs/model/MeshFlatten") -- ------------------------------------------------------------------------------------------------ contract local Stl = { @@ -29,7 +29,7 @@ local Stl = { category = "model", 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 }, } diff --git a/src/Formats/model/usda/Build.luau b/src/Formats/model/usda/Build.luau index 5e4be9f..2d554bd 100644 --- a/src/Formats/model/usda/Build.luau +++ b/src/Formats/model/usda/Build.luau @@ -18,6 +18,7 @@ -- Not supported: composition arcs (references, payloads, inherits, specializes, subLayers: listed in -- meta.source.unsupported), UsdSkel, blend shapes, BasisCurves / Points / NURBS, instancing, MaterialX networks. local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") local Parse = require("@formats/model/usda/Parse") local Build = {} @@ -149,95 +150,13 @@ end -- ------------------------------------------------------------------------------------------------ matrices -- column-major 4x4 (glTF layout = USD's row-major row-vector text order) local mul = Types.Scene.mul -local function translateM(x: number, y: number, z: number): { number } - return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } -end -local function scaleM(x: number, y: number, z: number): { number } - return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } -end -local function rotM(axis: number, deg: number): { number } - local c, s = math.cos(deg * DEG), math.sin(deg * DEG) - if axis == 1 then - return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 } - elseif axis == 2 then - return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 } - end - return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } -end local function quatM(x: number, y: number, z: number, w: number): { number } local l = math.sqrt(x * x + y * y + z * z + w * w) if l > 0 then x, y, z, w = x / l, y / l, z / l, w / l end - return Types.Scene.nodeMatrix({ children = {}, rotation = { x, y, z, w } }) + return Mat4.fromQuat({ x, y, z, w }) end -local function inverse(m: { number }): { number }? - local a = m - local inv = table.create(16, 0) - inv[1] = a[6] * a[11] * a[16] - a[6] * a[12] * a[15] - a[10] * a[7] * a[16] + a[10] * a[8] * a[15] + a[14] * a[7] * a[12] - a[14] * a[8] * a[11] - inv[5] = -a[5] * a[11] * a[16] + a[5] * a[12] * a[15] + a[9] * a[7] * a[16] - a[9] * a[8] * a[15] - a[13] * a[7] * a[12] + a[13] * a[8] * a[11] - inv[9] = a[5] * a[10] * a[16] - a[5] * a[12] * a[14] - a[9] * a[6] * a[16] + a[9] * a[8] * a[14] + a[13] * a[6] * a[12] - a[13] * a[8] * a[10] - inv[13] = -a[5] * a[10] * a[15] + a[5] * a[11] * a[14] + a[9] * a[6] * a[15] - a[9] * a[7] * a[14] - a[13] * a[6] * a[11] + a[13] * a[7] * a[10] - inv[2] = -a[2] * a[11] * a[16] + a[2] * a[12] * a[15] + a[10] * a[3] * a[16] - a[10] * a[4] * a[15] - a[14] * a[3] * a[12] + a[14] * a[4] * a[11] - inv[6] = a[1] * a[11] * a[16] - a[1] * a[12] * a[15] - a[9] * a[3] * a[16] + a[9] * a[4] * a[15] + a[13] * a[3] * a[12] - a[13] * a[4] * a[11] - inv[10] = -a[1] * a[10] * a[16] + a[1] * a[12] * a[14] + a[9] * a[2] * a[16] - a[9] * a[4] * a[14] - a[13] * a[2] * a[12] + a[13] * a[4] * a[10] - inv[14] = a[1] * a[10] * a[15] - a[1] * a[11] * a[14] - a[9] * a[2] * a[15] + a[9] * a[3] * a[14] + a[13] * a[2] * a[11] - a[13] * a[3] * a[10] - inv[3] = a[2] * a[7] * a[16] - a[2] * a[8] * a[15] - a[6] * a[3] * a[16] + a[6] * a[4] * a[15] + a[14] * a[3] * a[8] - a[14] * a[4] * a[7] - inv[7] = -a[1] * a[7] * a[16] + a[1] * a[8] * a[15] + a[5] * a[3] * a[16] - a[5] * a[4] * a[15] - a[13] * a[3] * a[8] + a[13] * a[4] * a[7] - inv[11] = a[1] * a[6] * a[16] - a[1] * a[8] * a[14] - a[5] * a[2] * a[16] + a[5] * a[4] * a[14] + a[13] * a[2] * a[8] - a[13] * a[4] * a[6] - inv[15] = -a[1] * a[6] * a[15] + a[1] * a[7] * a[14] + a[5] * a[2] * a[15] - a[5] * a[3] * a[14] - a[13] * a[2] * a[7] + a[13] * a[3] * a[6] - inv[4] = -a[2] * a[7] * a[12] + a[2] * a[8] * a[11] + a[6] * a[3] * a[12] - a[6] * a[4] * a[11] - a[10] * a[3] * a[8] + a[10] * a[4] * a[7] - inv[8] = a[1] * a[7] * a[12] - a[1] * a[8] * a[11] - a[5] * a[3] * a[12] + a[5] * a[4] * a[11] + a[9] * a[3] * a[8] - a[9] * a[4] * a[7] - inv[12] = -a[1] * a[6] * a[12] + a[1] * a[8] * a[10] + a[5] * a[2] * a[12] - a[5] * a[4] * a[10] - a[9] * a[2] * a[8] + a[9] * a[4] * a[6] - inv[16] = a[1] * a[6] * a[11] - a[1] * a[7] * a[10] - a[5] * a[2] * a[11] + a[5] * a[3] * a[10] + a[9] * a[2] * a[7] - a[9] * a[3] * a[6] - local det = a[1] * inv[1] + a[2] * inv[5] + a[3] * inv[9] + a[4] * inv[13] - if det == 0 or det ~= det then - return nil - end - for k = 1, 16 do - inv[k] /= det - end - return inv -end -Build.inverse = inverse - --- decompose(m) -> translation, rotation (quaternion x y z w), scale (no shear) -local function decompose(m: { number }): ({ number }, { number }, { number }) - local sx = math.sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3]) - local sy = math.sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7]) - local sz = math.sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11]) - local det = m[1] * (m[6] * m[11] - m[7] * m[10]) - m[5] * (m[2] * m[11] - m[3] * m[10]) + m[9] * (m[2] * m[7] - m[3] * m[6]) - if det < 0 then - sx = -sx - end - local function d(v: number, s: number): number - return if s ~= 0 then v / s else 0 - end - local r00, r10, r20 = d(m[1], sx), d(m[2], sx), d(m[3], sx) - local r01, r11, r21 = d(m[5], sy), d(m[6], sy), d(m[7], sy) - local r02, r12, r22 = d(m[9], sz), d(m[10], sz), d(m[11], sz) - local x, y, z, w - local tr = r00 + r11 + r22 - if tr > 0 then - local s = math.sqrt(tr + 1) * 2 - w, x, y, z = 0.25 * s, (r21 - r12) / s, (r02 - r20) / s, (r10 - r01) / s - elseif r00 > r11 and r00 > r22 then - local s = math.sqrt(1 + r00 - r11 - r22) * 2 - w, x, y, z = (r21 - r12) / s, 0.25 * s, (r01 + r10) / s, (r02 + r20) / s - elseif r11 > r22 then - local s = math.sqrt(1 + r11 - r00 - r22) * 2 - w, x, y, z = (r02 - r20) / s, (r01 + r10) / s, 0.25 * s, (r12 + r21) / s - else - local s = math.sqrt(1 + r22 - r00 - r11) * 2 - w, x, y, z = (r10 - r01) / s, (r02 + r20) / s, (r12 + r21) / s, 0.25 * s - end - local l = math.sqrt(x * x + y * y + z * z + w * w) - if l > 0 then - x, y, z, w = x / l, y / l, z / l, w / l - end - return { m[13], m[14], m[15] }, { x, y, z, w }, { sx, sy, sz } -end -Build.decompose = decompose -- ------------------------------------------------------------------------------------------------ xform ops type Op = { kind: string, axes: string?, prop: Prop, invert: boolean } @@ -283,10 +202,10 @@ local function opMatrix(op: Op, v: any): { number }? local m: { number }? local k = op.kind if k == "translate" then - m = translateM(n[1] or 0, n[2] or 0, n[3] or 0) + m = Mat4.translation(n[1] or 0, n[2] or 0, n[3] or 0) elseif k == "scale" then local s1 = n[1] or 1 - m = scaleM(s1, n[2] or s1, n[3] or s1) + m = Mat4.scaling(s1, n[2] or s1, n[3] or s1) elseif k == "orient" then -- USD quaternions are written (real, i, j, k) m = quatM(n[2] or 0, n[3] or 0, n[4] or 0, n[1] or 1) @@ -302,14 +221,14 @@ local function opMatrix(op: Op, v: any): { number }? for c = 1, #axes do local a = AXIS[string.sub(axes, c, c)] local angle = if #axes == 1 then n[1] or 0 else n[a] or 0 - r = mul(rotM(a, angle), r) + r = mul(Mat4.rotation(a, angle), r) end m = r else return nil end if op.invert and m then - m = inverse(m) + m = Mat4.inverseFull(m) end return m end @@ -1253,7 +1172,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) local sc = Types.Scene.accessor(nil, "f32", 3, count) local prev: { number }? = nil for k = 1, count do - local T, R, S = decompose(localMatrix(ops, times[k])) + local T, R, S = Mat4.decompose(localMatrix(ops, times[k])) if prev and prev[1] * R[1] + prev[2] * R[2] + prev[3] * R[3] + prev[4] * R[4] < 0 then R = { -R[1], -R[2], -R[3], -R[4] } end @@ -1270,7 +1189,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) table.insert(animation.channels, { node = ni, path = "translation", input = tin, output = tr, interpolation = "LINEAR" } :: Types.Channel) table.insert(animation.channels, { node = ni, path = "rotation", input = tin, output = ro, interpolation = "LINEAR" } :: Types.Channel) table.insert(animation.channels, { node = ni, path = "scale", input = tin, output = sc, interpolation = "LINEAR" } :: Types.Channel) - local T, R, S = decompose(localMatrix(ops, times[1])) + local T, R, S = Mat4.decompose(localMatrix(ops, times[1])) n.translation, n.rotation, n.scale = T, R, S elseif #ops > 0 then -- static: TRS when the stack is translate / rotate / scale in that order, else the matrix @@ -1285,7 +1204,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) end local m = localMatrix(ops, nil) if simple then - local T, R, S = decompose(m) + local T, R, S = Mat4.decompose(m) local tx = ops[1].kind == "translate" if tx then n.translation = T diff --git a/src/Formats/model/usda/init.luau b/src/Formats/model/usda/init.luau index 3e52979..04439f7 100644 --- a/src/Formats/model/usda/init.luau +++ b/src/Formats/model/usda/init.luau @@ -31,7 +31,7 @@ local Usda = { category = "model", 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 }, } diff --git a/src/Formats/music/it/init.luau b/src/Formats/music/it/init.luau index d73cec0..0782816 100644 --- a/src/Formats/music/it/init.luau +++ b/src/Formats/music/it/init.luau @@ -1,6 +1,6 @@ --!strict -- music/it: Impulse Tracker modules (IMPM, ITTECH.TXT; also files from OpenMPT / Schism Tracker). Reads into the --- codecs/Tracker Module and plays through its engine (Module:render() / open() -> an audio Decoder). Supports: up to +-- codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio Decoder). Supports: up to -- 64 channels, instrument and sample mode, new and old (pre-2.0) instrument headers, volume / panning / pitch (or -- filter) envelopes with loops and sustain loops, new note actions and duplicate checks, pitch-pan separation, -- resonant filters (instrument cutoff / resonance, default Zxx macros), 8 / 16-bit signed or unsigned mono / stereo @@ -12,7 +12,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Tracker = require("@formats/codecs/Tracker") +local Tracker = require("@formats/codecs/audio/Tracker") local Itsex = require("@formats/music/it/Itsex") -- ------------------------------------------------------------------------------------------------ contract @@ -21,7 +21,7 @@ local It = { category = "music", 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 }, } diff --git a/src/Formats/music/midi/Render.luau b/src/Formats/music/midi/Render.luau index a40aa56..9b4e1e5 100644 --- a/src/Formats/music/midi/Render.luau +++ b/src/Formats/music/midi/Render.luau @@ -1,11 +1,11 @@ --!strict -- music/midi/Render: the tempo map (ticks -> seconds, as python mido computes lengths), the time-ordered event list, --- and the audio Decoder that plays a Midi through codecs/SoundFont's synth (a SoundFont bank, or the built-in +-- and the audio Decoder that plays a Midi through codecs/audio/SoundFont's synth (a SoundFont bank, or the built-in -- waveform set). Format 0 / 1: one tempo map from every track's tempo events, tracks merged (ties keep track order). -- Format 2: each track is its own song with its own tempo map, played one after another. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local SoundFont = require("@formats/codecs/SoundFont") +local SoundFont = require("@formats/codecs/audio/SoundFont") local Synth = SoundFont.Synth @@ -162,7 +162,7 @@ end export type RenderOptions = { sampleRate: number?, -- default 44100 - soundfont: any?, -- a SoundFont (music/sf2 decode, codecs/SoundFont.parse) or SF2 bytes (buffer / string); default the built-in waveforms + soundfont: any?, -- a SoundFont (music/sf2 decode, codecs/audio/SoundFont.parse) or SF2 bytes (buffer / string); default the built-in waveforms gain: number?, -- linear output gain, default 0.5 tail: number?, -- seconds rendered after the last event (release tails), default 1 maxVoices: number?, -- default 256 diff --git a/src/Formats/music/midi/init.luau b/src/Formats/music/midi/init.luau index fcaeb46..ac60034 100644 --- a/src/Formats/music/midi/init.luau +++ b/src/Formats/music/midi/init.luau @@ -1,6 +1,6 @@ --!strict -- music/midi: Standard MIDI Files (SMF 1.0: formats 0, 1 and 2; PPQ and SMPTE time; RIFF RMID read). Written from the --- specification (no third-party code); rendering goes through codecs/SoundFont (a TinySoundFont port). +-- specification (no third-party code); rendering goes through codecs/audio/SoundFont (a TinySoundFont port). -- Supports: decode to a Types.Midi (absolute ticks; channel events noteOff / noteOn / aftertouch / controller / -- program / channelPressure / pitchBend with their raw data bytes, sysex / escape with the bytes after the length, -- meta events with meta = the meta type; meta.tempos / timeSignatures / keySignatures, track names), encode (running @@ -21,7 +21,7 @@ local Midi = { category = "music", 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 }, } diff --git a/src/Formats/music/mod/init.luau b/src/Formats/music/mod/init.luau index 7f4eb88..6b97843 100644 --- a/src/Formats/music/mod/init.luau +++ b/src/Formats/music/mod/init.luau @@ -1,7 +1,7 @@ --!strict -- music/mod: ProTracker / NoiseTracker / StarTrekker MOD modules (the 31-sample "M.K." family: M.K., M!K!, FLT4, -- 4CHN .. 9CHN, 10CH .. 32CH, xxCN, CD81, OKTA / OCTA, TDZx; 15-sample Soundtracker files when asked for by name or --- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/Tracker Module and plays through +-- extension). Written from the ProTracker 2.3 documentation. Reads into the codecs/audio/Tracker Module and plays through -- its engine (Module:render() / open() -> an audio Decoder). Writes 31-sample MODs (M.K. / xCHN / xxCH) from "mod" -- modules, and from XM modules that fit (one sample per instrument, effects 0..F, 64-row patterns). -- Not supported: FLT8's split 4 + 4 channel patterns (read as 8 plain channels), the Amiga hardware low-pass filter @@ -11,7 +11,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Tracker = require("@formats/codecs/Tracker") +local Tracker = require("@formats/codecs/audio/Tracker") -- ------------------------------------------------------------------------------------------------ contract local Mod = { @@ -19,7 +19,7 @@ local Mod = { category = "music", 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 } }, } diff --git a/src/Formats/music/s3m/init.luau b/src/Formats/music/s3m/init.luau index dd27e0e..a8ff4f5 100644 --- a/src/Formats/music/s3m/init.luau +++ b/src/Formats/music/s3m/init.luau @@ -1,6 +1,6 @@ --!strict -- music/s3m: Scream Tracker 3 modules (SCRM, ST3 TECH.DOC; also files from Impulse Tracker / OpenMPT / Schism --- Tracker). Reads into the codecs/Tracker Module and plays through its engine (Module:render() / open() -> an audio +-- Tracker). Reads into the codecs/audio/Tracker Module and plays through its engine (Module:render() / open() -> an audio -- Decoder). Supports: up to 32 PCM channels, 8 / 16-bit signed or unsigned, mono or stereo samples, loops, the panning -- table, ST3.00 fast volume slides, every ST3 effect. Notes are stored one octave up (S3M C-4 = note 61 = the C5 -- speed reference, as IT shows S3M files). @@ -10,7 +10,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Tracker = require("@formats/codecs/Tracker") +local Tracker = require("@formats/codecs/audio/Tracker") -- ------------------------------------------------------------------------------------------------ contract local S3m = { @@ -18,7 +18,7 @@ local S3m = { category = "music", 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 } }, } diff --git a/src/Formats/music/sf2/init.luau b/src/Formats/music/sf2/init.luau index a7fcc20..b03c84f 100644 --- a/src/Formats/music/sf2/init.luau +++ b/src/Formats/music/sf2/init.luau @@ -1,5 +1,5 @@ --!strict --- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/SoundFont (the +-- music/sf2: SoundFont 2 banks (SoundFont 2.04 specification), read-only. A thin wrapper over codecs/audio/SoundFont (the -- parser and the TinySoundFont-port synth music/midi renders with). Supports: INFO, 16-bit samples (+ sm24 24-bit), -- presets / instruments / sample headers with global zones, generator merging into playable regions. -- Not supported: writing, SF3 (Ogg Vorbis samples), modulators (read past, not applied). @@ -8,7 +8,7 @@ -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") -local SoundFont = require("@formats/codecs/SoundFont") +local SoundFont = require("@formats/codecs/audio/SoundFont") -- ------------------------------------------------------------------------------------------------ contract local Sf2 = { @@ -16,7 +16,7 @@ local Sf2 = { category = "music", 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 }, } @@ -37,7 +37,7 @@ function Sf2.decode(r: Bytes.Reader, opts: DecodeOptions?): (SoundFont.SoundFont end -- ------------------------------------------------------------------------------------------------ extras --- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/SoundFont.Synth drives it) +-- synth(sf?, sampleRate?, opts?) -> a synth State (codecs/audio/SoundFont.Synth drives it) Sf2.synth = SoundFont.synth Sf2.fallback = SoundFont.fallback diff --git a/src/Formats/music/xm/init.luau b/src/Formats/music/xm/init.luau index ceddd5a..080795c 100644 --- a/src/Formats/music/xm/init.luau +++ b/src/Formats/music/xm/init.luau @@ -1,6 +1,6 @@ --!strict -- music/xm: FastTracker 2 Extended Modules (XM 1.04, the "Extended Module: " format; also OpenMPT / MilkyTracker / --- Skale files). Written from the XM specification and FT2 behaviour notes. Reads into the codecs/Tracker Module and +-- Skale files). Written from the XM specification and FT2 behaviour notes. Reads into the codecs/audio/Tracker Module and -- plays through its engine (Module:render() / open() -> an audio Decoder): up to 32 channels (more are read), 8 / 16-bit -- delta samples, multi-sample instruments with volume / panning envelopes, fadeout and auto-vibrato, linear and Amiga -- frequency tables, every FT2 effect and volume-column command. Writes XM from "xm" modules (byte-identical for files @@ -11,7 +11,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Tracker = require("@formats/codecs/Tracker") +local Tracker = require("@formats/codecs/audio/Tracker") -- ------------------------------------------------------------------------------------------------ contract local Xm = { @@ -19,7 +19,7 @@ local Xm = { category = "music", 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 } }, } diff --git a/src/Formats/ops/AudioOps.luau b/src/Formats/ops/AudioOps.luau index b1803e6..c0e473e 100644 --- a/src/Formats/ops/AudioOps.luau +++ b/src/Formats/ops/AudioOps.luau @@ -1,7 +1,7 @@ --!strict -- ops/AudioOps: editing on the standard Audio (layer 5.5: core, Types and codecs only): a Decoder collected into an -- Audio, gain (linear or dB), normalize, mix, channel remixing (downmix / upmix with the usual WAVE-layout matrices), --- resampling (codecs/Resample), trim, concat, fades, peak / RMS. New code. +-- resampling (codecs/audio/Resample), trim, concat, fades, peak / RMS. New code. -- -- local AudioOps = require("@formats/ops/AudioOps") -- F.ops.audio in the api -- local a = AudioOps.toAudio(F.audio.open(src)) -- an Audio from an Audio or a streaming Decoder @@ -20,8 +20,8 @@ -- copied from the (first) input. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -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") local AudioOps = {} @@ -362,7 +362,7 @@ function AudioOps.upmix(a: Types.Audio, channels: number): (Types.Audio?, Err.Er end -- ------------------------------------------------------------------------------------------------ time --- resample(a, rate, opts?) -> Audio at the new rate (codecs/Resample: opts.quality "low" | "medium" | "high") +-- resample(a, rate, opts?) -> Audio at the new rate (codecs/audio/Resample: opts.quality "low" | "medium" | "high") function AudioOps.resample(a: Types.Audio, rate: number, opts: Resample.Options?): (Types.Audio?, Err.Err?) if not isAudio(a) then return bad("resample: expected an Audio") diff --git a/src/Formats/ops/LayerOps.luau b/src/Formats/ops/LayerOps.luau index bf4b242..97400c7 100644 --- a/src/Formats/ops/LayerOps.luau +++ b/src/Formats/ops/LayerOps.luau @@ -1,6 +1,6 @@ --!strict -- ops/LayerOps: editing on the Layered type (PSD, Aseprite): flatten a layer tree (or one animation frame) to an --- rgba8 Image with the blend modes of codecs/Blend, opacity, groups (isolated, or pass-through), clipping layers and +-- rgba8 Image with the blend modes of codecs/image/Blend, opacity, groups (isolated, or pass-through), clipping layers and -- grey layer masks; every frame as an animated Image; walking the leaves. -- -- local LayerOps = require("@formats/ops/LayerOps") @@ -12,7 +12,7 @@ -- Never throws: bad values return nil, Err.ARG. local Err = require("@formats/core/Err") local Types = require("@formats/Types") -local Blend = require("@formats/codecs/Blend") +local Blend = require("@formats/codecs/image/Blend") local LayerOps = {} diff --git a/src/Formats/playlist/m3u/init.luau b/src/Formats/playlist/m3u/init.luau index 4e3acb4..5e32d81 100644 --- a/src/Formats/playlist/m3u/init.luau +++ b/src/Formats/playlist/m3u/init.luau @@ -4,7 +4,7 @@ -- location lists, a BOM, CRLF / CR, Windows-1252 text; HLS master playlists (variants with BANDWIDTH / CODECS / -- attributes, EXT-X-MEDIA renditions) and media playlists (segments, durations, byte ranges, target duration, media -- sequence, end list, encryption, the segment format). Locations resolve against opts.baseUrl (RFC 3986, --- codecs/Url); Windows / UNC paths stay as they are and are flagged unplayable, as are relative paths without a base +-- codecs/text/Url); Windows / UNC paths stay as they are and are flagged unplayable, as are relative paths without a base -- and non-HTTP schemes (mp3 HLS segments are playable; .ts / .aac / fMP4 are flagged). Encode: M3U8 (#EXTM3U, -- #EXTINF, #PLAYLIST). Not supported: writing HLS tags. -- @@ -17,8 +17,8 @@ local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Url = require("@formats/codecs/Url") -local Text = require("@formats/codecs/Text") +local Url = require("@formats/codecs/text/Url") +local Text = require("@formats/codecs/text/Text") -- ------------------------------------------------------------------------------------------------ contract local M3u = { @@ -26,7 +26,7 @@ local M3u = { category = "playlist", 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 }, } diff --git a/src/Formats/playlist/pls/init.luau b/src/Formats/playlist/pls/init.luau index 676f302..c3d4598 100644 --- a/src/Formats/playlist/pls/init.luau +++ b/src/Formats/playlist/pls/init.luau @@ -2,7 +2,7 @@ -- playlist/pls: PLS playlists ([playlist], FileN / TitleN / LengthN, NumberOfEntries, Version). Absorbed from -- playlist-luau 3fc7fd3 (same author, no third-party code; the parser), plus a new writer. Decode: keys in any case -- and order, comments, a BOM, CRLF / CR, Windows-1252 text, gaps in the numbering (entries sort by number), a --- NumberOfEntries mismatch as a warning; locations resolve against opts.baseUrl (RFC 3986, codecs/Url), local / +-- NumberOfEntries mismatch as a warning; locations resolve against opts.baseUrl (RFC 3986, codecs/text/Url), local / -- relative / non-HTTP locations are flagged unplayable. Encode: Version=2, Length -1 for unknown durations. -- -- local pl = Pls.decode(Bytes.reader(buf), { baseUrl = "https://radio.example/list.pls" }) @@ -13,8 +13,8 @@ local Err = require("@formats/core/Err") local Sniff = require("@formats/core/Sniff") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Url = require("@formats/codecs/Url") -local Text = require("@formats/codecs/Text") +local Url = require("@formats/codecs/text/Url") +local Text = require("@formats/codecs/text/Text") -- ------------------------------------------------------------------------------------------------ contract local Pls = { @@ -22,7 +22,7 @@ local Pls = { category = "playlist", 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 }, } diff --git a/src/Formats/playlist/xspf/init.luau b/src/Formats/playlist/xspf/init.luau index d93c3ac..325f0ac 100644 --- a/src/Formats/playlist/xspf/init.luau +++ b/src/Formats/playlist/xspf/init.luau @@ -1,9 +1,9 @@ --!strict --- playlist/xspf: XSPF 1 ("spiff", https://xspf.org/spec) playlists on codecs/Xml. New in formats-luau (playlist-luau +-- playlist/xspf: XSPF 1 ("spiff", https://xspf.org/spec) playlists on codecs/text/Xml. New in formats-luau (playlist-luau -- had no XSPF). Decode: the playlist's title / creator / annotation / info / location / identifier / image / date, -- every track's location (the first one is the entry url, all of them in entry.locations), title, creator, album, -- annotation, info, image, trackNum and duration (milliseconds -> seconds), xml:base on the playlist and on tracks; --- locations resolve against xml:base, then opts.baseUrl (RFC 3986, codecs/Url), and are classified like the other +-- locations resolve against xml:base, then opts.baseUrl (RFC 3986, codecs/text/Url), and are classified like the other -- playlist formats (local / relative / non-HTTP locations are unplayable). Encode: XSPF version 1 with those fields. -- Not supported: extension / link / meta elements (skipped), XSPF version 0 differences. -- @@ -15,8 +15,8 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") -local Url = require("@formats/codecs/Url") -local Xml = require("@formats/codecs/Xml") +local Url = require("@formats/codecs/text/Url") +local Xml = require("@formats/codecs/text/Xml") -- ------------------------------------------------------------------------------------------------ contract local Xspf = { @@ -24,7 +24,7 @@ local Xspf = { category = "playlist", 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 }, } diff --git a/src/Formats/vector/svg/Parse.luau b/src/Formats/vector/svg/Parse.luau index 827670e..f60199d 100644 --- a/src/Formats/vector/svg/Parse.luau +++ b/src/Formats/vector/svg/Parse.luau @@ -1,12 +1,12 @@ --!strict --- vector/svg/Parse: an SVG document (a codecs/Xml tree) to a Types.Vector: the cascade (presentation attributes, +-- vector/svg/Parse: an SVG document (a codecs/text/Xml tree) to a Types.Vector: the cascade (presentation attributes, --