merge ws/cleanup: restructure C (codecs by domain, shared Chunks/Stream/Pixels/Sniff/Mat4, audio codecs out of format folders, DUP lint, type gate 93), dedup, consistency, F.ops, README

This commit is contained in:
4DBug committed 2026-10-31 13:32:16 -05:00
commit 1d21568af8
369 files changed
+5143 -3739

No files matched your search

+113 -41
View File
@@ -3,73 +3,145 @@
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, [docs/API.md](docs/API.md) for the whole API, and the guide
([docs/guide/README.md](docs/guide/README.md)) for walkthroughs.
```luau
local F = require(Formats) -- LuaJIT: require("formats"); luau CLI: require("@formats")
local img, err = F.load(src) -- src: buffer | string | path (hosts with files)
if not img then print(tostring(err)) end -- errors are values: "png: CORRUPT at 0x21: bad filter type 7"
local buf = F.save(img, nil, { format = "png" }) -- a buffer; F.save(img, "out.png") writes a file
local s = F.saveString(img, { format = "png" })
local F = require(Formats) -- LuaJIT: require("formats"); luau CLI: require("@formats")
local img, err = F.load(src) -- src: buffer | string | path (hosts with files)
if not img then print(tostring(err)) end -- errors are values: "png: CORRUPT at 0x21: bad filter type 7"
local buf = F.save(img, nil, { format = "webp" }) -- a buffer; F.save(img, "out.webp") writes a file
local out = F.convert(src, "png", { level = 9 })
local img2 = F.image.load(src) -- category facades: F.image / audio / video / model / font / ...
for _, f in F.formats() do print(f.name, f.caps.decode, f.caps.encode) end
local small = F.ops.image.resize(img, 64, 64, "lanczos")
```
Nothing throws on bad data or bad arguments: every call returns `nil, err` (`err.code` is one of the `F.Err` codes).
## Runtimes
## Install
| Runtime | How | Files |
**Roblox (Rojo).** `python3 -I tools/build.py roblox` writes `build/roblox/Formats` (requires turned into instance
paths); `default.project.json` mounts it, so `rojo build -o Formats.rbxm` (or `rojo serve`) gives a `Formats`
ModuleScript to put in ReplicatedStorage: `local F = require(game.ReplicatedStorage.Formats)`. There is no file system:
pass buffers or strings. `F.host.toEditableImage(img)` makes an EditableImage.
**LuaJIT / LÖVE.** `python3 -I tools/build.py luajit` writes `build/luajit/formats/` (Lua 5.1 + LuaJIT FFI; the Luau
standard library pieces come from `formats/_compat.lua`). Copy the `formats` folder into the game (or put
`build/luajit/?.lua;build/luajit/?/init.lua` on `package.path`) and `local F = require("formats")`. Files load by path
(`love.filesystem` under LÖVE, else `io.open`); `F.host.toImageData(img)`, `F.host.fromImageData(imageData)` and
`F.host.toSoundData(audioOrDecoder)` bridge to LÖVE. `examples/love` is a runnable example and smoke test
(`love examples/love` from the repo root after building).
**luau CLI.** `luau` with the `.luaurc` alias `@formats` runs `src/` directly (no file system).
## Quick start
```luau
-- images: PNG / APNG, JPEG, WebP, GIF, BMP, TGA, QOI, TIFF, ICO, PNM, HDR -> Image (rgba8 pixels in a buffer)
local img = F.image.load(pngBytes)
print(img.width, img.height, #(img.frames or {}), img.loops) -- animations: frames; loops = play count, 0 forever
local jpg = F.save(img, nil, { format = "jpeg", quality = 85 })
-- audio: WAV, FLAC, MP3 / MP2, Ogg Vorbis, Opus, AAC, M4A, AIFF, AU, CAF, VOC -> streaming Decoder or Audio
local dec = F.audio.open(flacBytes) -- dec:read(n) -> interleaved f32 buffer, frames; dec:seek(s)
local song = F.audio.load(mp3Bytes) -- Audio { sampleRate, channels, frames, samples, tags }
local mono = F.ops.audio.downmix(song, 1) -- channels are in WAVE order; tags keys are lower case
local opus = F.save(F.ops.audio.resample(mono, 48000), nil, { format = "opus", bitrate = 64000 })
-- video: MP4 / MOV, MKV / WebM, AVI, MPEG-TS / PS, Y4M (+ animated images) -> VideoDecoder
local v = F.video.open(mp4Bytes) -- v:nextFrame() -> frame (image yuv420p or rgba8, pts)
-- models: glTF / GLB, OBJ, STL, PLY, FBX, Collada, 3MF, USDA, OFF, VOX -> Scene
local scene = F.model.load(glbBytes)
local prim = F.ops.mesh.merge(scene) -- one triangle primitive in world space
-- fonts, archives, data, vector, layered, subtitles, music, playlists
local font = F.font.load(ttfBytes) -- outlines, metrics, kerning
local zip = F.archive.load(zipBytes) -- entries; F.archive.save writes zip / tar / gzip
local t = F.data.load('{"a": [1, 2]}', { format = "json" }) -- JSON, XML, YAML, TOML, CSV, INI, plist, msgpack, CBOR
local icon = F.ops.vector.rasterize(F.vector.load(svgText), 64, 64)
local flat = F.ops.layers.flatten(F.layered.load(psdBytes))
local subs = F.subtitle.load(srtText)
local tune = F.music.load(modBytes) -- MOD / S3M / XM / IT / MIDI, rendered to audio on request
```
## The API in short
`F.load`, `F.open`, `F.save`, `F.saveString`, `F.convert`, `F.detect`, `F.formats`, `F.format(name)`; the category
facades `F.image`, `F.audio`, `F.video`, `F.model`, `F.cad`, `F.font`, `F.archive`, `F.data`, `F.vector`,
`F.layered`, `F.subtitle`, `F.music`, `F.playlist`; editing in `F.ops.image`, `F.ops.mesh`, `F.ops.layers`,
`F.ops.audio`, `F.ops.vector.rasterize`; `F.host`, `F.plugins`, `F.Err`, `F.Types`. Options and the hooks the api
hands to formats (decodeImage / encodeImage / openAudio / plugins): [docs/API.md](docs/API.md).
## Host notes
| Host | Files | Bridges |
|---|---|---|
| Roblox | `python3 -I tools/build.py roblox`, then `rojo build` / `rojo serve` (`default.project.json` mounts `build/roblox/Formats`) | none: pass buffers / strings; `F.host.toEditableImage(img)` |
| LuaJIT | `python3 -I tools/build.py luajit`; `package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path` | `io.open` |
| LÖVE | the LuaJIT build, copied into the game | `love.filesystem` (+ `io`); `F.host.toImageData(img)`, `F.host.fromImageData(id)`, `F.host.toSoundData(audio or decoder)` |
| luau CLI | `luau` with the `.luaurc` alias `@formats` (`src/` directly) | none |
| Roblox | none: pass buffers / strings | `F.host.toEditableImage(img)` |
| LÖVE | `love.filesystem`, then `io` | `toImageData`, `fromImageData`, `toSoundData` |
| LuaJIT | `io.open` | |
| luau CLI | none | |
The LuaJIT build supplies the Luau standard library pieces it needs from `compat/luajit.lua` (unsigned `bit32`,
`buffer` on FFI memory, `table.create`, `math.clamp`, `string.split`, `utf8`, ...), required by each module, without
touching globals (`require("formats._compat").install()` puts `buffer` / `bit32` / `utf8` / `typeof` in `_G` if a
game wants them).
- **Paths.** A string is read as a path only on hosts with files, when it looks like one (short, no NUL / newline)
and the file exists, or when `opts.path = true`; `opts.data = true` forces bytes. Files next to a loaded model
(OBJ `.mtl`, glTF `.bin` and textures) are found through `opts.resolve`, which the api fills in for paths.
- **LuaJIT trace tuning.** On load the host raises LuaJIT's trace limits (`jit.opt.start("maxtrace=8000",
"maxmcode=65536")`): the big decoders (Opus CELT, VP8, H.264, MPEG-1) outgrow the defaults and fall back to the
interpreter (2x or more slower). Set `_G.FORMATS_NO_JIT_TUNE = true` before requiring the library to leave the
JIT settings alone.
## Layout
```
src/Formats/
init.luau Registry.luau (generated) api: F.*
ops/ editing on the standard types (ImageOps, MeshOps, LayerOps, AudioOps)
<category>/<fmt>/ formats: only what is specific to the format (parsing, mapping, writing)
containers/ Chunks, Riff, IsoBmff, Ebml, Ogg, Zip, Tar, Avi, MpegTs, MpegPs, ...
codecs/compress/ Deflate, Lzma, Zstd, Brotli, Bzip2, Lzw
codecs/entropy/ Huffman, RangeCoder
codecs/image/ Jpeg, Dct, Vp8, Vp8L, Pixels, Yuv, Quantize, Raster, Blend
codecs/audio/ Opus, Vorbis, Flac, Mpa (MP1-3), Aac, Alac, Mdct, Pcm, Stream, Resample,
VorbisComment, Tracker, SoundFont
codecs/video/ H264, Mpeg1, Video (the codec registry)
codecs/text/ codecs/font/ codecs/model/ Json, Xml, Text, Url / TrueType, Cff / Mat4, MeshFlatten
host/ runtime adapters (only the api uses them)
Types.luau the standard types + constructors
core/ Bytes, Bits, Err, Crc32, Adler32, Base64, Md5, Input, Sniff
compat/luajit.lua tools/ tests/ (T.luau, <category>/<fmt>.luau, codecs/, containers/, gen/) docs/ licenses/
examples/love/
```
How the layers fit, the format contract, and what belongs in a format folder: [docs/STYLE.md](docs/STYLE.md).
## Development
```sh
bash tools/test.sh # fixtures, registry, build, every test under luau --codegen -O2 and LuaJIT, lint
bash tools/test.sh png # one test (both runtimes), no lint
bash tools/lint.sh # globals, headers, requires, native-throw, layers, deps, contract, registry
bash tools/lint.sh # globals, type baseline, headers, requires, native-throw, layers, deps, contract, DUP
bash tools/bench.sh # throughput on both runtimes (pin it: taskset -c 2 bash tools/bench.sh)
python3 -I tools/build.py # build/roblox + build/luajit
python3 -I tools/gen_registry.py # src/Formats/Registry.luau + docs/FORMATS.md from the format folders
python3 -I tools/fixtures.py # tests/gen/*.luau from tools/fixtures/*.py
python3 -I tools/fixtures.py # tests/gen/*.luau from tools/fixtures/*.py (reference tools through nix)
python3 -I tools/move.py codecs/image/Foo=codecs/video/Foo # move a module, rewriting every reference
```
Tools: python3, and through nix: `luau` (+ `luau-analyze`), `luajit`, `darklua` 0.19, `rojo` (each script finds them
on PATH or runs them with `nix shell nixpkgs#<tool>`).
on PATH or runs them with `nix shell nixpkgs#<tool>`); the fixture generators run ffmpeg, ImageMagick, libwebp, flac,
lame, opus-tools, vorbis-tools, assimp, fontTools and others through nix.
Layout, layering, the format contract, how to add a format or absorb a repo: [docs/STYLE.md](docs/STYLE.md).
The type checker's diagnostics may only go down: `tools/lint.sh` fails when their count passes
`tools/lint_types_baseline.txt` (`LINT_TYPES=1` lists them, `LINT_TYPES_UPDATE=1` lowers the baseline).
```
src/Formats/ init.luau (API) Types.luau Registry.luau (generated) core/ host/ codecs/ containers/
<category>/<fmt>/ ops/
compat/luajit.lua tools/ tests/ (T.luau, <category>/<fmt>.luau, fixtures/, gen/) docs/ licenses/
```
## Performance
## Performance (one Zen 5 core, `taskset -c 2 bash tools/bench.sh`)
| | luau --codegen -O2 | LuaJIT 2.1 |
|---|---|---|
| inflate, 6 MB text + binary (exact size) | ~330 MB/s | ~470 MB/s |
| zlib (inflate + Adler-32) | ~170 MB/s | ~280 MB/s |
| CRC-32 | ~310 MB/s | ~520 MB/s |
| PNG decode 1024x768 RGBA | ~52 MB/s | ~30-75 MB/s |
| deflate compress -6 | ~12 MB/s | ~8-20 MB/s |
LuaJIT numbers vary between runs: its trace recorder is randomised, and about one run in ten picks a slower trace
layout for a loop (inflate then runs at ~190 MB/s). Unpinned runs on this hybrid CPU also differ 2x between core types.
`tools/bench.luau` prints throughput per codec on both runtimes; run it pinned to one core
(`taskset -c 2 bash tools/bench.sh`: on hybrid CPUs the core types differ 2x). LuaJIT numbers vary between runs (its
trace recorder is randomised).
## Licence
+6 -2
View File
@@ -476,10 +476,14 @@ end
-- ---------------------------------------------------------------------------------------------------- math
do
-- math.min / math.max are LuaJIT fast functions (branch-free minsd / maxsd in a trace); the two data-dependent
-- branches of `if x < lo ... elseif x > hi` spawned side traces in hot loops (codecs/Dct, colour conversion) and
-- ran ~3.5x slower. NaN stays NaN, as in Luau (maxsd would return lo).
local mmin, mmax = math.min, math.max
math.clamp = math.clamp or function(x, lo, hi)
if lo > hi then error("max must be greater than or equal to min", 2) end
if x < lo then return lo elseif x > hi then return hi end
return x
if x ~= x then return x end
return mmin(mmax(x, lo), hi)
end
math.sign = math.sign or function(x)
if x > 0 then return 1 elseif x < 0 then return -1 end
+96
View File
@@ -0,0 +1,96 @@
# formats-luau API
`local F = require(Formats)` (Roblox: the ModuleScript; LuaJIT / LÖVE: `require("formats")`; luau CLI:
`require("@formats")`). Everything below is `src/Formats/init.luau` unless noted. Nothing throws on bad data or bad
arguments: a failing call returns `nil, err` where `err` is a `core/Err` value (`err.code`, `err.message`,
`err.offset`, `err.format`; `tostring(err)` prints `png: CORRUPT at 0x21: bad filter type 7`).
## Sources and destinations
A source `src` is a `buffer`, a `string` of bytes, or a file path on hosts with a file system (LuaJIT, LÖVE). A
string is a path only when `opts.path = true` or when it does not look like file data and the file exists; pass
`opts.data = true` to force bytes. Roblox and the luau CLI have no file system: pass buffers or strings.
`F.save(value, dest?, opts?)` returns a `buffer`, or writes the file `dest` (extension = format) and returns `true`.
## Loading and saving
| Call | Returns |
|---|---|
| `F.load(src, opts?)` | the category's standard value (`Image`, `Audio`, `Scene`, `Font`, `Archive`, `Vector`, `Layered`, `Subtitles`, `Module` / `Midi`, `Playlist`, data values, a `VideoDecoder`) |
| `F.open(src, opts?)` | a streaming decoder: audio `Decoder`, `VideoDecoder`, or a container `Demuxer` |
| `F.save(value, dest?, opts?)` | `buffer` / `true` |
| `F.saveString(value, opts?)` | the encoded bytes as a string |
| `F.convert(src, format, opts?)` | load + save (`opts` go to both; `opts.out = path` writes a file) |
| `F.detect(src, opts?)` | the format name (content sniffing first, then the extension) |
| `F.formats(category?)` | `{ { name, category, extensions, mime, caps } }` without loading any format (also [FORMATS.md](FORMATS.md)) |
| `F.format(name)` | the format module itself (`sniff` / `decode` / `encode` / `open` and extras such as `png.info`) |
Common options: `format` (a name or extension: what to decode as / encode to; without it, saving uses the source
format), `category`, `name` (a file name hint for detection), `path` / `data`, size limits (`maxPixels`, `maxBytes`,
`maxFrames`, ...), and each format's own options (documented in its `init.luau`: `level`, `quality`, `bitrate`, ...).
## 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` each have `load`, `open`, `save` and `formats`: the calls above restricted to
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/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`).
- `F.data.null`: the JSON / YAML / TOML / msgpack / CBOR null.
## Editing: `F.ops`
Loaded on first use; every function returns a new value (or edits in place where it says so) and `nil, Err` for bad
arguments.
| Table | Module | Functions |
|---|---|---|
| `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/audio/Resample`), `trim`, `concat`, `fade` |
| `F.ops.vector` | `vector/svg` | `rasterize(vector, w?, h?, opts?)`: any `Vector` to an rgba8 `Image` |
```luau
local img = F.load(png)
local thumb = F.ops.image.resize(img, 128, 128, "lanczos")
local music = F.ops.audio.toAudio(F.audio.open(mp3))
local quiet = F.ops.audio.gainDb(F.ops.audio.resample(music, 48000), -6)
F.save(quiet, "out.flac")
local icon = F.ops.vector.rasterize(F.load(svgText), 64, 64)
```
## Hooks and plug-ins
A format never requires another format, so the api passes these to decoders / encoders in `opts` (callers of
`F.format(name).decode` directly may pass their own; without them the embedded parts return `Err.UNSUPPORTED`):
- `opts.decodeImage(buf) -> Image | nil, Err` and `opts.encodeImage(img, format) -> buffer | nil, Err`: images inside
other files (ICO PNG entries, PSD / glTF / 3MF textures, MJPEG frames, ...).
- `opts.openAudio(demuxer, track) -> Decoder | nil, Err`: audio tracks of video containers (wrapped by
`containers/AudioWrap` and opened as the matching audio format).
- `opts.plugins` (default `F.plugins`): injected optional dependencies, e.g. `F.plugins.brep` (a B-rep kernel for
`cad/step`).
- `opts.resolve(uri) -> buffer?`: files referenced by a model (OBJ `.mtl`, glTF `.bin`); filled in for paths on hosts
with files. `opts.loadPage(file, page)` for bitmap-font pages.
## Host
`F.host` (`src/Formats/host`): `name` (`"roblox"`, `"love"`, `"luajit"`, `"luau"`), `hasFiles`, `readFile`,
`writeFile`, `exists`; Roblox `toEditableImage(img)`; LÖVE `toImageData(img)`, `fromImageData(imageData)`,
`toSoundData(audioOrDecoder)`.
On LuaJIT the host raises the trace limits at load (`jit.opt.start("maxtrace=8000", "maxmcode=65536")`): the big
decoders (CELT, VP8, H.264, MPEG-1) outgrow the defaults and fall back to the interpreter. Set
`_G.FORMATS_NO_JIT_TUNE = true` before requiring the library to leave the JIT settings alone.
## Also exported
`F.Err` (codes `TRUNCATED`, `CORRUPT`, `CHECKSUM`, `UNSUPPORTED`, `LIMIT`, `ARG`, `IO`, `UNKNOWN_FORMAT`), `F.Types`
(the standard types and their constructors), `F.Bytes` (`core/Bytes` Reader / Writer), `F.null`, `F.version`.
+53 -34
View File
@@ -22,8 +22,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| audio | caf | .caf .caff | yes | yes | codecs: "pcm", "alac", "aac", "ulaw", "alaw", encodeCodecs: "pcm", "alac", tags: true, streaming: true | `tests/audio/caf.luau` |
| audio | flac | .flac .oga | yes | yes | streaming: true, depths: 4, 8, 12, 16, 20, 24, 32, ogg: true, seek: true | `tests/audio/flac.luau` |
| audio | m4a | .m4a .m4b .m4r | yes | yes | codecs: "aac", "alac", encodeCodecs: "alac", tags: true, streaming: true | `tests/audio/m4a.luau` |
| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | yes | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` |
| audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt" | `tests/audio/opus.luau` |
| audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | yes | streaming: true, seek: true, layers: 1, 2, 3, encodeLayers: 2, 3, channels: 2 | `tests/audio/mp3.luau` |
| audio | opus | .opus | yes | yes | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000, encodeModes: "celt", encodeChannels: 2 | `tests/audio/opus.luau` |
| audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` |
| audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` |
| audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` |
@@ -83,36 +83,55 @@ 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/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, for data: URIs
- 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/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
- 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/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/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim,
- codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
- codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it:
- codecs/audio/Opus: the Opus codec (RFC 6716) without its container: TOC / packet framing (Packet), the SILK and CELT
- 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/Vorbis: the Vorbis I decoder without its container: identification / comment / setup headers (Setup),
- 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/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF
- 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.
+71 -15
View File
@@ -1,7 +1,8 @@
# formats-luau style guide
Every format looks the same: one folder, one contract, one test, one fixture generator. `bash tools/lint.sh` enforces
most of what follows (the rule names in CAPITALS are lint rules, implemented in `tools/lint_rules.py`).
Every format looks the same: one folder, one contract, one test, one fixture generator, and the folder holds only what
is specific to the format (section 2a). `bash tools/lint.sh` enforces most of what follows (the rule names in
CAPITALS are lint rules, implemented in `tools/lint_rules.py`).
The reference implementation to copy is **PNG**:
@@ -11,27 +12,36 @@ The reference implementation to copy is **PNG**:
| Private hot submodules (`--!native`) | `src/Formats/image/png/Decode.luau`, `src/Formats/image/png/Encode.luau` |
| Test | `tests/image/png.luau` |
| Fixture generator | `tools/fixtures/png.py` (a reference tool through nix: `tools/fixtures/_png_reference.py`) |
| A codec (layer 1) | `src/Formats/codecs/Deflate/` + `tests/codecs/deflate.luau` + `tools/fixtures/deflate.py` |
| A codec (layer 3) | `src/Formats/codecs/compress/Deflate/` + `tests/codecs/deflate.luau` + `tools/fixtures/deflate.py` |
## 1. Layout and layers
```
src/Formats/
init.luau Registry.luau (generated) api (layer 6)
ops/ ops (layer 5.5) editing on the standard types
ops/ ops (layer 5.5) editing on the standard types (F.ops.image /
mesh / layers / audio; ImageOps, MeshOps, ...)
<category>/<fmt>/ formats (layer 5) image audio video model cad font archive data
vector layered subtitle music playlist
containers/ containers (layer 4) Riff, IsoBmff, Ebml, Ogg, Zip, Tar, ...
codecs/ codecs (layer 3) Deflate, Lzw, Dct, Huffman-heavy algorithms
containers/ containers (layer 4) Chunks, Riff, IsoBmff, Ebml, Ogg, Zip, Tar, ...
codecs/<domain>/<Name> codecs (layer 3) generic algorithms, by domain:
compress/ Deflate Lzma Zstd Brotli Bzip2 Lzw entropy/ Huffman RangeCoder
image/ Jpeg Dct Vp8 Vp8L Pixels Yuv Quantize Raster Blend
audio/ Opus Vorbis Flac Mpa Aac Alac Mdct Pcm Stream Resample VorbisComment Tracker SoundFont
video/ H264 Mpeg1 Video (the video codec registry) text/ Json Xml Text Url
font/ TrueType Cff model/ Mat4 MeshFlatten
host/ host (layer 2) runtime adapters; only the api uses them
Types.luau types (layer 1) standard types + constructors
core/ core (layer 0) Bytes, Bits, Err, Crc32, Adler32, Huffman, Input
core/ core (layer 0) Bytes, Bits, Err, Crc32, Adler32, Base64, Md5,
Input, Sniff (runtime-neutral primitives)
```
LAYERS: a module requires only what is below it. core requires core; Types requires core; codecs require core, Types
and other codecs; containers add codecs; a format may require core, Types, codecs, containers and **its own folder**,
never another format (shared code moves down to `codecs/` or `containers/`: WebP lossy and WebM both use `codecs/Vp8`).
Nothing but the api requires `host/`: formats are pure functions of bytes.
never another format (shared code moves down to `codecs/` or `containers/`: WebP lossy and WebM both use `codecs/image/Vp8`).
Nothing but the api requires `host/`: formats are pure functions of bytes. A codec lives in a domain folder
(`codecs/<compress|entropy|image|audio|video|text|font|model>/<Name>`); `containers/` and `core/` are flat. Moving a
module: `python3 -I tools/move.py old/Path=new/Path` rewrites every reference (requires, deps, headers, docs).
REQUIRE: every require is a string literal `require("@formats/<path>")` (tests and tools may also use
`require("@tests/<path>")`). No `script.X`, no `@self`, no relative paths, no computed requires: `tools/build.py` turns
@@ -119,6 +129,18 @@ Rules:
- Extra format-specific functions (`Png.info(r)`) are fine; `F.format("png")` returns the module.
- No globals, no state between calls, no host access (no files, no `game`).
### Conventions shared by every format
- Images: `rgba8` unless `opts.native`; `img.loops` is the play count (0 = forever: GIF stores repeats, APNG / WebP
play counts); animation frames per `Types.Frame`.
- Audio: interleaved f32 in **WAVE channel order** (FL FR C LFE BL BR SL SR; Vorbis / Opus streams are reordered with
`Pcm.WAVE_FROM_VORBIS`); `tags` keys are **lower case** (title, artist, album, albumartist, date, genre, track,
disc, comment, ...: `codecs/audio/VorbisComment` for Vorbis / Opus / FLAC); raw fields go in `meta.source`.
- Hooks: a format never requires another format. For embedded data in another format the api passes
`opts.decodeImage(buf)`, `opts.encodeImage(img, format)`, `opts.openAudio(demuxer, track)` (audio tracks of video
containers, through `containers/AudioWrap`), `opts.plugins` (injected optional dependencies such as the B-rep
kernel) and `opts.resolve(uri)` (sibling files); without them the embedded part is `Err.UNSUPPORTED`. Video codecs
register in `codecs/video/Video` (fourcc / Matroska id -> decoder) so every container finds them.
### Errors (Err)
Nothing throws on bad data or bad arguments. Every failure is `return nil, Err.new(code, message, offset?)`:
@@ -134,7 +156,9 @@ Nothing throws on bad data or bad arguments. Every failure is `return nil, Err.n
Messages are lower case, without the format name (the api adds it: `png: CORRUPT at 0x21: bad filter type 7`).
The `Bytes` reader's errors are sticky: read a run of fields, then check `if r.err then return nil, r.err end` once.
Private submodules may return `false, "message"` or `nil, "message"`; `init.luau` turns that into an `Err`.
Private submodules may return `false, "message"` or `nil, "message"[, kind]`; `init.luau` turns that into an `Err`
with `Err.from(message, offset?, kind?)` (kind = "truncated" / "limit" / ...; without it a `"limit: "` /
`"unsupported: "` prefix or "truncated" / "past the end" in the message picks the code, else CORRUPT).
### Native code (NATIVE)
A Luau error unwinding through a native frame crashes Roblox Studio, even inside `pcall`. So:
@@ -150,12 +174,41 @@ 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. A codec is not the format: the Opus, Vorbis, FLAC and
MPEG audio decoders / encoders live in `codecs/audio/` (audio/opus is Ogg Opus around `codecs/audio/Opus`), as JPEG,
VP8 / VP8L, H.264 and MPEG-1 live in `codecs/image/` / `codecs/video/`, so containers and other formats can reach
them. Anything generic goes down a layer and is called:
| Need | Use |
|---|---|
| chunked files (RIFF / IFF / PNG / CAF style: id, size, body, pad, trailer) | `containers/Chunks` (`containers/Riff` for RIFF forms) |
| a decode() that drains open() | `codecs/audio/Pcm.drain(dec, source)` |
| a streaming Decoder over packets (priming, end padding, seek pre-roll) | `codecs/audio/Stream.packets` |
| encoder input (Audio or Decoder), sample formats, channel order | `codecs/audio/Pcm` (`source`, `collect`, `Convert`, `reorder`) |
| other sample rates | `codecs/audio/Resample` |
| Vorbis comments | `codecs/audio/VorbisComment` |
| bitmap rows (indexed bits, BGR / BGRA, 5-5-5, masks, RLE4 / 8, bottom-up) | `codecs/image/Pixels` |
| 4x4 matrices, quaternions, TRS | `codecs/model/Mat4` |
| compression, entropy coding, CRCs, base64 | `codecs/compress/*`, `codecs/entropy/*`, `core/Crc32` (`.msb` too), `core/Base64` |
| bit writing for encoders | `core/Bits` (`msbWriter`, or `Bits.msbPut` on a raw record) |
| argument checking of (buffer \| string, offset, length) | `core/Bytes.span` |
| sniffing text (BOM) / magic | `core/Sniff` |
| private-submodule errors -> Err | `core/Err.from` |
| UTF-8 code points, text decoding | `codecs/text/Text` |
DUP enforces the direction: a function body of 12 or more code lines repeated token for token in another module
fails the lint. When two formats need the same code, move it down (to `codecs/<domain>/` or `containers/`) instead of
copying.
## 3. Tests
`tests/<category>/<fmt>.luau`, run by `bash tools/test.sh [filter]` under `luau --codegen -O2` **and** LuaJIT. Template:
@@ -193,14 +246,17 @@ t:done()
their licence in `licenses/`). Prefer generating over committing. Keep fixture modules under ~15 MB.
- Both runtimes read the same `require("@tests/gen/<name>")`; there is no second mechanism.
- A fuzz pass is mandatory for every decoder (CONTRACT checks `:fuzz(`).
- Types: `luau-analyze` diagnostics are counted by the lint (TYPES) and may not rise above
`tools/lint_types_baseline.txt`; new code should add none (`LINT_TYPES=1 bash tools/lint.sh` lists them, and
`LINT_TYPES_UPDATE=1` lowers the baseline after a cleanup).
## 4. Adding a format
1. `src/Formats/<category>/<fmt>/init.luau` from the template above (copy `image/png/init.luau`), private submodules
next to it. Use `core/Bytes` for parsing, `core/Bits` / `core/Huffman` for entropy coding, `Types` constructors for
the result.
2. Shared code (a codec two formats need, a container) goes to `codecs/` or `containers/` instead, with its own test in
`tests/codecs/` / `tests/containers/`.
next to it. Use `core/Bytes` for parsing, `core/Bits` / `codecs/entropy/Huffman` for entropy coding, the shared
modules of section 2a for everything generic, `Types` constructors for the result.
2. Shared code (a codec two formats need, a container) goes to `codecs/<domain>/` or `containers/` instead, with its
own test in `tests/codecs/` / `tests/containers/`.
3. `deps = { ... }` = the requires outside the folder.
4. `python3 -I tools/gen_registry.py` (regenerates `src/Formats/Registry.luau` and `docs/FORMATS.md`; never edit those
by hand; after a merge, just rerun it).
+6 -6
View File
@@ -24,10 +24,10 @@ F.convert(gif, "avi") -- animated images become videos (un
| `containers/Demux` | the indexed Demuxer every container builds: per-track cursors, keyframe seek, `count` / `get` / `info` |
| `containers/Ebml`, `Avi`, `IsoBmff`, `MpegTs`, `MpegPs`, `MpegEs` | container structures |
| `containers/AudioWrap` | an audio track as a stream an audio format reads (PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, ...) |
| `codecs/Video` | the codec registry and the generic VideoDecoder (`Video.open(demuxer, opts)`, `Video.fromFrames`) |
| `codecs/Video/Source` | what writers write: copied packets or frames encoded by a registry encoder, PCM from the audio |
| `codecs/Yuv` | yuv420p <-> rgba8 (BT.601 / 709, limited / full range from `image.meta.yuv`), range remap |
| `codecs/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) |
| `codecs/video/Video` | the codec registry and the generic VideoDecoder (`Video.open(demuxer, opts)`, `Video.fromFrames`) |
| `codecs/video/Video/Source` | what writers write: copied packets or frames encoded by a registry encoder, PCM from the audio |
| `codecs/image/Yuv` | yuv420p <-> rgba8 (BT.601 / 709, limited / full range from `image.meta.yuv`), range remap |
| `codecs/image/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) |
| `video/<fmt>` | the formats: demux into `containers/Demux`, `open` = `Video.open(demuxer, opts)`, `encode` via Source |
Audio tracks reach the audio formats through the api hook `opts.openAudio(demuxer, track)` (a format never requires
@@ -36,13 +36,13 @@ another format): `F.video.open` / `F.load` set it; calling a video format's `ope
## Adding a codec (H.264, ...)
The registry is static (Roblox has no dynamic require): add an entry to `BUILTIN` in `src/Formats/codecs/Video/init.luau`
The registry is static (Roblox has no dynamic require): add an entry to `BUILTIN` in `src/Formats/codecs/video/Video/init.luau`
with a `new` constructor that requires the codec lazily, or call `Video.register(entry)` at run time
(`F.video.codecs.register`).
```luau
{ id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", ... }, matroska = { "V_MPEG4/ISO/AVC" },
new = function(track, opts) return require("@formats/codecs/H264").newVideoDecoder(track, opts) end }
new = function(track, opts) return require("@formats/codecs/video/H264").newVideoDecoder(track, opts) end }
```
`new(track, opts)` returns a `Types.VideoCodecDecoder`:
+68 -68
View File
@@ -20,7 +20,7 @@ local list: { Entry } = {
path = "image/bmp",
extensions = { "bmp", "dib" },
mime = { "image/bmp", "image/x-bmp", "image/x-ms-bmp" },
deps = { "core/Err", "core/Bytes", "Types" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" },
caps = { decode = true, encode = true, alpha = true, depths = { 1, 2, 4, 8, 16, 24, 32 }, rle = true },
load = function()
return require("@formats/image/bmp")
@@ -32,7 +32,7 @@ local list: { Entry } = {
path = "image/gif",
extensions = { "gif" },
mime = { "image/gif" },
deps = { "core/Err", "core/Bytes", "codecs/Lzw", "codecs/Quantize", "Types" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Lzw", "codecs/image/Quantize", "Types" },
caps = { decode = true, encode = true, animation = true, alpha = true, palette = true, depths = { 1, 2, 4, 8 } },
load = function()
return require("@formats/image/gif")
@@ -56,7 +56,7 @@ local list: { Entry } = {
path = "image/ico",
extensions = { "ico", "cur" },
mime = { "image/vnd.microsoft.icon", "image/x-icon" },
deps = { "core/Err", "core/Bytes", "Types" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" },
caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 4, 8, 16, 24, 32 } },
load = function()
return require("@formats/image/ico")
@@ -68,7 +68,7 @@ local list: { Entry } = {
path = "image/jpeg",
extensions = { "jpg", "jpeg", "jpe", "jfif" },
mime = { "image/jpeg" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Jpeg" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Jpeg" },
caps = { decode = true, encode = true, lossy = true, alpha = false, depths = { 8, 12 }, progressive = true, arithmetic = true },
load = function()
return require("@formats/image/jpeg")
@@ -80,7 +80,7 @@ local list: { Entry } = {
path = "image/png",
extensions = { "png", "apng" },
mime = { "image/png", "image/apng" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "Types" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "Types", "containers/Chunks" },
caps = { decode = true, encode = true, animation = true, alpha = true, depths = { 1, 2, 4, 8, 16 } },
load = function()
return require("@formats/image/png")
@@ -128,7 +128,7 @@ local list: { Entry } = {
path = "image/tiff",
extensions = { "tif", "tiff" },
mime = { "image/tiff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "codecs/Lzw" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/compress/Lzw", "codecs/compress/PackBits" },
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" },
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" },
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", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Pcm", "codecs/audio/VorbisComment", "codecs/audio/Flac/Frame", "codecs/audio/Flac/Encode" },
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" },
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,8 +224,8 @@ local list: { Entry } = {
path = "audio/mp3",
extensions = { "mp3", "mp2", "mp1", "mpga" },
mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/Mpa/Header", "codecs/audio/Mpa/Core", "codecs/audio/Mpa/Encode3", "codecs/audio/Mpa/Encode2" },
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")
end,
@@ -236,8 +236,8 @@ local list: { Entry } = {
path = "audio/opus",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/entropy/RangeCoder/Decoder", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/VorbisComment", "codecs/audio/Opus/CeltEncoder", "codecs/audio/Opus/Decoder", "codecs/audio/Opus/Packet", "codecs/audio/Opus/Celt", "codecs/audio/Opus/Silk" },
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")
end,
@@ -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" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/audio/Pcm", "codecs/audio/VorbisComment", "codecs/audio/Vorbis/Tables", "codecs/audio/Vorbis/Setup", "codecs/audio/Vorbis/Packet" },
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" },
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", "codecs/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", "codecs/Base64" },
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")
@@ -488,7 +488,7 @@ local list: { Entry } = {
path = "cad/step",
extensions = { "step", "stp", "p21" },
mime = { "model/step", "application/step", "application/p21" },
deps = { "core/Err", "core/Bytes", "Types" },
deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" },
caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" },
load = function()
return require("@formats/cad/step")
@@ -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", "codecs/text/Text" },
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" },
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" },
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" },
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", "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" },
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" },
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" },
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" },
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" },
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", "codecs/compress/PackBits", "codecs/text/Text" },
caps = { decode = true, encode = true, layers = true, groups = true, depths = { 1, 8, 16, 32 } },
load = function()
return require("@formats/layered/psd")
@@ -800,7 +800,7 @@ local list: { Entry } = {
path = "subtitle/ass",
extensions = { "ass", "ssa" },
mime = { "text/x-ssa", "text/x-ass" },
deps = { "core/Err", "core/Bytes", "Types" },
deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" },
caps = { decode = true, encode = true, styles = true },
load = function()
return require("@formats/subtitle/ass")
@@ -812,7 +812,7 @@ local list: { Entry } = {
path = "subtitle/srt",
extensions = { "srt" },
mime = { "application/x-subrip", "text/srt" },
deps = { "core/Err", "core/Bytes", "Types" },
deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" },
caps = { decode = true, encode = true, styles = false },
load = function()
return require("@formats/subtitle/srt")
@@ -824,7 +824,7 @@ local list: { Entry } = {
path = "subtitle/vtt",
extensions = { "vtt", "webvtt" },
mime = { "text/vtt" },
deps = { "core/Err", "core/Bytes", "Types" },
deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" },
caps = { decode = true, encode = true, styles = true },
load = function()
return require("@formats/subtitle/vtt")
@@ -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" },
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" },
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")
+47 -15
View File
@@ -28,7 +28,7 @@ local BPP: { [string]: number } = {
graya8 = 2,
alpha8 = 1,
}
Types.BPP = table.freeze(BPP)
Types.BPP = table.freeze(BPP) :: { [string]: number }
export type ImageMeta = {
colorSpace: string?, -- "srgb" (default), "linear", "display-p3", ...
@@ -59,7 +59,8 @@ export type Image = {
format: PixelFormat,
pixels: buffer,
frames: { Frame }?, -- animations: frame 1 is also width x height pixels (the composited first frame)
loops: number, -- 0 = forever
loops: number, -- play count: how many times the animation plays, 0 = forever (GIF stores repeats: plays - 1; APNG
-- num_plays and the WebP ANIM loop count are play counts)
meta: ImageMeta,
}
@@ -165,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
@@ -241,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
@@ -429,7 +430,7 @@ local COMPONENT_SIZE: { [string]: number } = {
snorm8 = 1,
snorm16 = 2,
}
Types.COMPONENT_SIZE = table.freeze(COMPONENT_SIZE)
Types.COMPONENT_SIZE = table.freeze(COMPONENT_SIZE) :: { [string]: number }
-- accessor(data, type, components, count) -> Accessor (data = nil allocates a zero-filled buffer)
function Scene.accessor(data: buffer?, type: any, components: number, count: number): Accessor
local d = data or buffer.create(count * components * (COMPONENT_SIZE[type] or 4))
@@ -672,7 +673,7 @@ local OBJECT = { __object = true }
local objectMeta: { [any]: { any } } = setmetatable({}, { __mode = "k" }) :: any -- object -> its key order
-- object(t?, keys?) -> t marked as an object, keys = its key order (default: none recorded; Types.set appends)
function Types.object(t: { [any]: any }?, keys: { any }?): { [any]: any }
local o = t or {}
local o: { [any]: any } = t or {}
if getmetatable(o) == nil then
setmetatable(o, OBJECT)
end
@@ -691,6 +692,7 @@ function Types.set(o: { [any]: any }, k: any, v: any)
end
o[k] = v
end
-- keyLess(a, b): a total order for table keys (by type name, then value; numbers before strings)
local function keyLess(a: any, b: any): boolean
local ta, tb = type(a), type(b)
if ta ~= tb then
@@ -701,6 +703,27 @@ local function keyLess(a: any, b: any): boolean
end
return tostring(a) < tostring(b)
end
Types.keyLess = keyLess
-- isArray(t, emptyIsMap?) -> t is a plain array 1 .. #t (no other keys, not an ordered object); an empty table is an
-- array unless emptyIsMap
function Types.isArray(t: { [any]: any }, emptyIsMap: boolean?): boolean
if Types.isObject(t) then
return false
end
local n = #t
if n == 0 then
return next(t) == nil and not emptyIsMap
end
if next(t, n) ~= nil then
return false
end
local c = 0
for _ in next, t do
c += 1
end
return c == n
end
-- keys(t) -> the keys in order: an object's recorded order (keys since removed are skipped), then any other keys
-- sorted (numbers before strings)
function Types.keys(t: { [any]: any }): { any }
@@ -746,13 +769,13 @@ local function p2(n: number): string
return string.format("%02d", n)
end
local function fmtDate(d: any): string
local s = ""
local s: string = ""
if d.year then
s = string.format("%04d-%02d-%02d", d.year, d.month or 1, d.day or 1)
end
if d.hour then
if s ~= "" then
s ..= "T"
s = s .. "T"
end
s ..= p2(d.hour) .. ":" .. p2(d.minute or 0) .. ":" .. p2(d.second or 0)
local ns = d.nanosecond or 0
@@ -798,6 +821,7 @@ local function civilFromDays(z: number): (number, number, number)
local m = if mp < 10 then mp + 3 else mp - 9
return (if m <= 2 then y + 1 else y), m, d
end
DateLib.civilFromDays = civilFromDays -- days since 1970-01-01 -> year, month, day (proleptic Gregorian)
local MDAYS = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
-- new(fields) -> Date (kind inferred from the fields present when not given)
function DateLib.new(f: { [string]: any }): Date
@@ -841,11 +865,11 @@ end
-- "07:32:00.999", "1979-05-27 07:32:00Z", lower-case t / z accepted); out-of-range fields return nil
function DateLib.parse(s: string): Date?
local d: any = {}
local rest = s
local rest: string = s
local y, mo, dd, r1 = string.match(rest, "^(%d%d%d%d)%-(%d%d)%-(%d%d)(.*)$")
if y then
d.year, d.month, d.day = tonumber(y), tonumber(mo), tonumber(dd)
rest = r1
rest = r1 :: string
if rest == "" then
return if DateLib.valid(d) then DateLib.new(d) else nil
end
@@ -860,17 +884,17 @@ function DateLib.parse(s: string): Date?
return nil
end
d.hour, d.minute = tonumber(h), tonumber(mi)
rest = r2
rest = r2 :: string
local sec, r3 = string.match(rest, "^:(%d%d)(.*)$")
if not sec then
return nil
end
d.second = tonumber(sec)
rest = r3
rest = r3 :: string
local frac, r4 = string.match(rest, "^%.(%d+)(.*)$")
if frac then
d.nanosecond = tonumber(string.sub(frac .. "000000000", 1, 9))
rest = r4
rest = r4 :: string
else
d.nanosecond = 0
end
@@ -950,6 +974,14 @@ export type VectorPath = {
strokeWidth: number,
transform: { number }?, -- a, b, c, d, e, f
opacity: number,
group: number?, -- index into meta.groups (svg <g> nesting: opacity / clip-path per group)
clip: number?, -- index into meta.clips (a clip-path)
id: string?,
strokeDashArray: { number }?,
strokeDashOffset: number?,
strokeLineJoin: ("miter" | "round" | "bevel")?, -- default "miter"
strokeLineCap: ("butt" | "round" | "square")?, -- default "butt"
strokeMiterLimit: number?,
}
export type Vector = {
kind: "vector",
@@ -966,7 +998,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? }
@@ -1082,6 +1114,6 @@ Types.CATEGORIES = table.freeze({
subtitle = "subtitles",
music = "music",
playlist = "playlist",
})
} :: { [string]: string })
return Types
+6 -18
View File
@@ -3,6 +3,7 @@
-- streams info (pack info, folders with their coders and bind pairs, substreams), files info (names, empty streams /
-- files, anti items, times, attributes). Not --!native: a parse failure raises an Err value that parse() catches and
-- returns; any other error is a bug and propagates (the tests' fuzz pass sees it).
local Text = require("@formats/codecs/text/Text")
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
@@ -177,7 +178,8 @@ local function folder(r: Bytes.Reader): Folder
check(r)
local nin, nout = 1, 1
if bit32.band(flags, 0x10) ~= 0 then
nin, nout = number(r), number(r)
nin = number(r)
nout = number(r)
if nin > 64 or nout > 64 then
bad(r, "bad coder stream count")
end
@@ -394,21 +396,7 @@ local function streamsInfo(r: Bytes.Reader): Streams
end
local function utf16(b: buffer, o: number, n: number): string
local out = {}
local i = 0
while i + 1 < n do
local u = buffer.readu16(b, o + i)
i += 2
if u >= 0xD800 and u < 0xDC00 and i + 1 < n then
local lo = buffer.readu16(b, o + i)
if lo >= 0xDC00 and lo < 0xE000 then
u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00)
i += 2
end
end
table.insert(out, utf8.char(u))
end
return table.concat(out)
return Text.utf16(b, o, n, false)
end
local function filesInfo(r: Bytes.Reader): { File }
@@ -416,11 +404,11 @@ local function filesInfo(r: Bytes.Reader): { File }
if n > 1000000 then
bad(r, "too many files", Err.LIMIT)
end
local files: { File } = table.create(n)
local files: { File } = table.create(n) :: { File }
for i = 1, n do
files[i] = { name = "", emptyStream = false, emptyFile = false, anti = false }
end
local empties = {}
local empties: { number } = {}
while true do
local t = byte(r)
if t == K.End then
+21 -17
View File
@@ -13,10 +13,10 @@ local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Types = require("@formats/Types")
local Lzma = require("@formats/codecs/Lzma")
local Deflate = require("@formats/codecs/Deflate")
local Bzip2 = require("@formats/codecs/Bzip2")
local Zstd = require("@formats/codecs/Zstd")
local Lzma = require("@formats/codecs/compress/Lzma")
local Deflate = require("@formats/codecs/compress/Deflate")
local Bzip2 = require("@formats/codecs/compress/Bzip2")
local Zstd = require("@formats/codecs/compress/Zstd")
local Archive = require("@formats/containers/Archive")
local Header = require("@formats/archive/7z/Header")
@@ -26,7 +26,7 @@ local SevenZip = {
category = "archive",
extensions = { "7z" },
mime = { "application/x-7z-compressed" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/Lzma", "codecs/Deflate", "codecs/Bzip2", "codecs/Zstd", "containers/Archive" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/compress/Lzma", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Zstd", "containers/Archive", "codecs/text/Text" },
caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false },
}
@@ -144,7 +144,9 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf
if not b then
return nil, e
end
src, so, sl = b, 0, buffer.len(b)
src = b
so = 0
sl = buffer.len(b)
else
local k = table.find(f.packed, inIdx)
if not k then
@@ -162,14 +164,14 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf
src = ctx.buf
end
local id = c.id
local opts = { maxBytes = ctx.maxBytes }
local opts: { maxBytes: number?, verify: boolean? } = { maxBytes = ctx.maxBytes }
if id == "\0" then
if sl < size then
return nil, Err.new(Err.TRUNCATED, "short stored stream")
end
local b = buffer.create(size)
buffer.copy(b, 0, src, so, size)
return b
return b, nil
elseif id == "\3\1\1" then
if buffer.len(c.props) < 5 then
return nil, Err.new(Err.CORRUPT, "bad LZMA properties")
@@ -195,7 +197,7 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf
if buffer.len(b) ~= size then
return nil, Err.new(Err.CORRUPT, methodName(id) .. " stream decodes to the wrong size")
end
return b
return b, nil
elseif FILTERS[id] then
if sl ~= size then
return nil, Err.new(Err.CORRUPT, "filter size mismatch")
@@ -206,7 +208,7 @@ local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buf
if not ok then
return nil, e
end
return b
return b, nil
end
return nil, Err.new(Err.UNSUPPORTED, methodName(id) .. " is not supported")
end
@@ -226,7 +228,7 @@ local function folderMethod(f: Header.Folder): string
end
function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?)
local o = opts or {}
local o: DecodeOptions = opts or {}
local maxBytes = if type(o.maxBytes) == "number" then o.maxBytes else 2 ^ 30
local checkCrc = o.checkCrc ~= false
local b, base, limit = r.buf, r.base, r.limit
@@ -280,17 +282,19 @@ function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?
if f.crc and Crc32.raw(hb, 0, buffer.len(hb)) ~= f.crc then
return nil, Err.new(Err.CHECKSUM, "encoded header CRC-32 mismatch")
end
hbuf, hoff, hlen = hb, 0, buffer.len(hb)
hbuf = hb
hoff = 0
hlen = buffer.len(hb)
end
if not parsed then
return nil, Err.new(Err.CORRUPT, "nested encoded headers")
end
local s = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} }
local s: Header.Streams = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} }
a.meta.folders = #s.folders
a.meta.solid = false
-- folder caches and the substream -> folder map
local cache: { [number]: buffer } = {}
local subFolder, subOffset = {}, {}
local subFolder: { number }, subOffset: { number } = {}, {}
do
local si = 1
for fi, f in s.folders do
@@ -311,7 +315,7 @@ function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?
local function folderData(fi: number): (buffer?, Err.Err?)
local c = cache[fi]
if c then
return c
return c, nil
end
local f = s.folders[fi]
local d, e = decodeFolder(ctx, s, f)
@@ -322,7 +326,7 @@ function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?
return nil, Err.new(Err.CHECKSUM, "folder CRC-32 mismatch")
end
cache[fi] = d
return d
return d, nil
end
local si = 0
for _, file in parsed.files do
@@ -376,7 +380,7 @@ function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?
if checkCrc and want and Crc32.raw(out, 0, size) ~= want then
return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch in " .. file.name)
end
return out
return out, nil
end
end
Archive.put(a, e)
+3 -3
View File
@@ -1,6 +1,6 @@
--!strict
-- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (meta.stream: the api unwraps a .tar.br to the tar
-- inside). Decoding through codecs/Brotli. The entry is named after opts.name without ".br" (else "data").
-- inside). Decoding through codecs/compress/Brotli. The entry is named after opts.name without ".br" (else "data").
-- Supports: read (eager decompression). Not supported: write (no Brotli compressor). Brotli has no magic number:
-- sniff accepts only data that decodes cleanly (the whole stream for small files, a 64 KB prefix for big ones), at a
-- low confidence, so the extension decides between candidates.
@@ -8,7 +8,7 @@
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Brotli = require("@formats/codecs/Brotli")
local Brotli = require("@formats/codecs/compress/Brotli")
local Archive = require("@formats/containers/Archive")
-- ------------------------------------------------------------------------------------------------ contract
@@ -17,7 +17,7 @@ local Br = {
category = "archive",
extensions = { "br" },
mime = { "application/x-brotli" },
deps = { "core/Err", "core/Bytes", "codecs/Brotli", "containers/Archive" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Brotli", "containers/Archive" },
caps = { decode = true, encode = false, stream = true },
}
+5 -4
View File
@@ -1,13 +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). Read only.
-- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). New in formats-luau. Not supported:
-- 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 = {
@@ -15,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 },
}
+7 -7
View File
@@ -3,13 +3,13 @@
-- file name without .gz, else "data"), with the header's MTIME; concatenated members decode as one stream, as gzip -d
-- does. Writing: an Archive with one entry (or a buffer / string) becomes one member with FNAME and MTIME; an Archive
-- with several entries is written as a tar inside the gzip (a .tar.gz). The api unwraps a .tar.gz / .tgz on load (the
-- inner tar, meta.compression = "gzip"). Deflate is codecs/Deflate. Not supported: FHCRC verification.
-- inner tar, meta.compression = "gzip"). Deflate is codecs/compress/Deflate. Not supported: FHCRC verification.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Deflate = require("@formats/codecs/Deflate")
local Deflate = require("@formats/codecs/compress/Deflate")
local Archive = require("@formats/containers/Archive")
local Tar = require("@formats/containers/Tar")
@@ -19,7 +19,7 @@ local Gzip = {
category = "archive",
extensions = { "gz", "tgz", "gzip" },
mime = { "application/gzip" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "containers/Archive", "containers/Tar" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" },
caps = { decode = true, encode = true, stream = true },
}
@@ -49,7 +49,7 @@ local function header(b: buffer, o: number, e: number): { [string]: any }
if bit32.band(flg, 4) ~= 0 and q + 2 <= e then
q += 2 + buffer.readu16(b, q)
end
for _, f in { { 8, "name" }, { 16, "comment" } } do
for _, f in { { 8, "name" }, { 16, "comment" } } :: { { any } } do
if bit32.band(flg, f[1]) ~= 0 then
local s = q
while q < e and buffer.readu8(b, q) ~= 0 do
@@ -85,7 +85,7 @@ function Gzip.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
size = buffer.len(out),
compressedSize = r.limit - r.base,
method = "deflate",
mtime = if h.mtime and h.mtime > 0 then h.mtime else nil,
mtime = if h.mtime and h.mtime > 0 then h.mtime :: number else nil,
dir = false,
data = out,
})
@@ -94,7 +94,7 @@ end
-- ------------------------------------------------------------------------------------------------ encode
function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o = opts or {}
local o: EncodeOptions = opts or {}
local level = if o.level == nil then 6 else o.level
if type(level) ~= "number" or level < 0 or level > 9 or level % 1 ~= 0 then
return nil, Err.new(Err.ARG, "level must be 0..9")
@@ -111,7 +111,7 @@ function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
if not items then
return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string")
end
local files = {}
local files: typeof(items) = {}
for _, it in items do
if not it.entry.dir then
table.insert(files, it)
+4 -4
View File
@@ -1,6 +1,6 @@
--!strict
-- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") files, read as single-stream archives holding one
-- entry (the decompressed data). Built on codecs/Lzma. Supports: concatenated streams, stream padding, every block
-- entry (the decompressed data). Built on codecs/compress/Lzma. Supports: concatenated streams, stream padding, every block
-- layout, checks none / CRC-32 / CRC-64 (verified; SHA-256 is not verified), filters LZMA2, delta and the BCJ filters
-- x86 / PowerPC / ARM / ARM-Thumb / SPARC / ARM64. Not supported: writing, IA-64 / RISC-V filters.
-- The entry is named after the file (opts.name without .xz / .lzma; .txz -> .tar), else "data". meta.stream = true:
@@ -10,7 +10,7 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Lzma = require("@formats/codecs/Lzma")
local Lzma = require("@formats/codecs/compress/Lzma")
local Archive = require("@formats/containers/Archive")
-- ------------------------------------------------------------------------------------------------ contract
@@ -19,7 +19,7 @@ local Xz = {
category = "archive",
extensions = { "xz", "txz", "lzma" },
mime = { "application/x-xz", "application/x-lzma" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Lzma", "containers/Archive" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "containers/Archive" },
caps = { decode = true, encode = false, stream = true, filters = { "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" } },
}
@@ -70,7 +70,7 @@ end
-- ------------------------------------------------------------------------------------------------ decode
function Xz.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?)
local o = opts or {}
local o: DecodeOptions = opts or {}
local n = r.limit - r.base
local out, res
local method
+1 -1
View File
@@ -3,7 +3,7 @@
-- Absorbed from zip-luau 121d4b0 (same author, no third-party code; the reader, now containers/Zip) plus a new
-- writer. Supports: reading stored and deflated entries (CRC-checked), ZIP64, data descriptors, archive comments,
-- prefixed archives (self-extractors), UTF-8 names, case-insensitive / basename lookup; writing stored and deflated
-- entries (codecs/Deflate), unchanged entries copied without recompressing, ZIP64 when needed.
-- entries (codecs/compress/Deflate), unchanged entries copied without recompressing, ZIP64 when needed.
-- Not supported: encryption (traditional PKWARE or AES), compression methods other than store / deflate (bzip2,
-- LZMA, zstd entries are listed but not readable), multi-disk archives.
--
+3 -3
View File
@@ -1,13 +1,13 @@
--!strict
-- archive/zst: a Zstandard-compressed file (.zst, RFC 8878) as a single-stream archive holding one entry, decoded
-- through codecs/Zstd. The entry is named after the file without its extension (opts.name; ".tzst" -> ".tar"), else
-- through codecs/compress/Zstd. The entry is named after the file without its extension (opts.name; ".tzst" -> ".tar"), else
-- "data". The api unwraps it when the entry is itself an archive (.tar.zst loads as the tar). Read-only.
-- Not supported: dictionaries, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Zstd = require("@formats/codecs/Zstd")
local Zstd = require("@formats/codecs/compress/Zstd")
local Archive = require("@formats/containers/Archive")
-- ------------------------------------------------------------------------------------------------ contract
@@ -16,7 +16,7 @@ local Zst = {
category = "archive",
extensions = { "zst", "tzst" },
mime = { "application/zstd" },
deps = { "core/Err", "core/Bytes", "codecs/Zstd", "containers/Archive" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Zstd", "containers/Archive" },
caps = { decode = true, encode = false, stream = true },
}
+24 -92
View File
@@ -1,6 +1,6 @@
--!strict
-- audio/aac: raw AAC in ADTS framing (ISO/IEC 13818-7 / 14496-3 1.A.3), the .aac files encoders and radio streams
-- write. Supports: reading AAC-LC through codecs/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected
-- write. Supports: reading AAC-LC through codecs/audio/Aac (1 - 8 channels, every rate, multi-block frames, CRC-protected
-- headers skipped), a leading ID3v2 tag (skipped; its text frames become tags), resync after garbage, seeking (by
-- frame), HE-AAC streams play their AAC-LC core. Not supported: writing (AAC encoding is out of scope), ADIF, LATM.
@@ -8,7 +8,9 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
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 = {
@@ -16,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" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Aac", "codecs/audio/Pcm", "codecs/audio/Stream" },
caps = { decode = true, encode = false, codecs = { "aac" }, streaming = true },
}
@@ -136,7 +138,7 @@ local function index(r: Bytes.Reader, maxFrames: number): ({ number }, { number
end
function AacFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local o = opts or {}
local o: DecodeOptions = opts or {}
local offs, sizes, first, ierr = index(r, o.maxFrames or 2 ^ 22)
if ierr then
return nil, ierr
@@ -167,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,
@@ -180,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?)
@@ -256,22 +203,7 @@ function AacFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?,
return nil, err
end
local d: any = dec
local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames)
local done = 0
while done < d.frames do
local b, n = d:read(math.min(65536, d.frames - done))
if n == 0 then
break
end
buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4)
done += n
end
if d.error then
return nil, d.error
end
audio.tags = d.tags
audio.meta.source = { format = "aac", codec = "aac", bitrate = d.bitrate }
return audio, nil
return Pcm.drain(d, { format = "aac", codec = "aac", bitrate = d.bitrate })
end
return AacFormat
+26 -31
View File
@@ -10,7 +10,8 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Chunks = require("@formats/containers/Chunks")
local Pcm = require("@formats/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Aiff = {
@@ -18,7 +19,7 @@ local Aiff = {
category = "audio",
extensions = { "aiff", "aif", "aifc", "afc" },
mime = { "audio/aiff", "audio/x-aiff" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "containers/Chunks" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
}
@@ -78,42 +79,42 @@ end
local function sampleFormat(comp: string, bits: number): (string?, string?)
if comp == "NONE" or comp == "twos" or comp == "" then
if bits >= 1 and bits <= 8 then
return "s8"
return "s8", nil
elseif bits <= 16 then
return "s16be"
return "s16be", nil
elseif bits <= 24 then
return "s24be"
return "s24be", nil
elseif bits <= 32 then
return "s32be"
return "s32be", nil
end
return nil, "bad sample size " .. bits
elseif comp == "sowt" then
if bits >= 1 and bits <= 8 then
return "s8"
return "s8", nil
elseif bits <= 16 then
return "s16le"
return "s16le", nil
elseif bits <= 24 then
return "s24le"
return "s24le", nil
elseif bits <= 32 then
return "s32le"
return "s32le", nil
end
return nil, "bad sample size " .. bits
elseif comp == "raw " then
return "u8"
return "u8", nil
elseif comp == "in24" then
return "s24be"
return "s24be", nil
elseif comp == "in32" then
return "s32be"
return "s32be", nil
elseif comp == "42ni" then
return "s32le"
return "s32le", nil
elseif comp == "fl32" or comp == "FL32" then
return "f32be"
return "f32be", nil
elseif comp == "fl64" or comp == "FL64" then
return "f64be"
return "f64be", nil
elseif comp == "ulaw" or comp == "ULAW" then
return "ulaw"
return "ulaw", nil
elseif comp == "alaw" or comp == "ALAW" then
return "alaw"
return "alaw", nil
end
return nil, "compression " .. string.format("%q", comp)
end
@@ -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)
@@ -248,12 +248,7 @@ function Aiff.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.
if not dec then
return nil, err
end
local d = dec :: any
local a = Types.Audio.new(d.sampleRate, d.channels, d.frames)
d:read(d.frames, a.samples)
a.tags = d.tags
a.meta.source = d.source
return a, nil
return Pcm.drain(dec)
end
-- ------------------------------------------------------------------------------------------------ encode
+3 -8
View File
@@ -9,7 +9,7 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Pcm = require("@formats/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Au = {
@@ -17,7 +17,7 @@ local Au = {
category = "audio",
extensions = { "au", "snd" },
mime = { "audio/basic", "audio/x-au" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16, 24, 32 }, float = true, lossy = false },
}
@@ -66,12 +66,7 @@ function Au.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.Er
if not dec then
return nil, err
end
local d = dec :: any
local a = Types.Audio.new(d.sampleRate, d.channels, d.frames)
d:read(d.frames, a.samples)
a.tags = d.tags
a.meta.source = d.source
return a, nil
return Pcm.drain(dec)
end
-- ------------------------------------------------------------------------------------------------ encode
+31 -127
View File
@@ -1,6 +1,6 @@
--!strict
-- audio/caf: Apple Core Audio Format (CAF 1.0, Apple's "Core Audio Format Specification"). Supports reading linear
-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/Alac), AAC-LC (codecs/Aac,
-- PCM (8 / 16 / 24 / 32-bit integer, 32 / 64-bit float, big / little endian), ALAC (codecs/audio/Alac), AAC-LC (codecs/audio/Aac,
-- kuki esds), mu-law and A-law; the packet table (pakt) with priming / remainder trimming, a data chunk of unknown
-- size (-1), info chunk tags; seeking. Writing linear PCM (16 / 24-bit big endian, 32-bit float) and ALAC (16 / 20 /
-- 24-bit) with info tags. Not supported: IMA4, other compressed formats (UNSUPPORTED).
@@ -9,8 +9,11 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
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 = {
@@ -18,7 +21,7 @@ local Caf = {
category = "audio",
extensions = { "caf", "caff" },
mime = { "audio/x-caf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Aac", "codecs/Alac" },
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 },
}
@@ -145,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 = {
@@ -222,10 +214,9 @@ local function parse(r: Bytes.Reader, o: DecodeOptions): (Parsed?, Err.Err?)
if c.err then
break
end
p.tags[INFO_TAGS[string.lower(k)] or k] = v
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
@@ -350,7 +341,7 @@ local function source(r: Bytes.Reader, p: Parsed): (Source?, Err.Err?)
return nil, Err.new(Err.CORRUPT, "compressed CAF without a packet table")
end
end
local offsets = table.create(#sizes, 0)
local offsets = table.create(#(sizes :: { number }), 0)
local o = p.dataStart
for i, s in sizes :: { number } do
offsets[i] = o
@@ -455,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,
@@ -470,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?)
@@ -559,22 +478,7 @@ function Caf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E
return nil, err
end
local d: any = dec
local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames)
local done = 0
while done < d.frames do
local b, n = d:read(math.min(65536, d.frames - done))
if n == 0 then
break
end
buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4)
done += n
end
if d.error then
return nil, d.error
end
audio.tags = d.tags
audio.meta.source = { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample }
return audio, nil
return Pcm.drain(d, { format = "caf", codec = d.codec, bitsPerSample = d.bitsPerSample })
end
-- ------------------------------------------------------------------------------------------------ encode
@@ -585,7 +489,7 @@ end
-- encode(audio | decoder, opts?) -> buffer | nil, Err
function Caf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o = opts or {}
local o: EncodeOptions = opts or {}
if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end
+5 -2
View File
@@ -4,6 +4,8 @@
-- 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/audio/VorbisComment")
local readu8, readu32 = buffer.readu8, buffer.readu32
local Meta = {}
@@ -102,8 +104,9 @@ local function vorbisComment(b: buffer, p: number, e: number, info: Info): boole
p += l
local eq = string.find(s, "=", 1, true)
if eq then
local key, value = string.upper(string.sub(s, 1, eq - 1)), string.sub(s, eq + 1)
table.insert(info.comments, { key = key, value = value })
local name, value = string.sub(s, 1, eq - 1), string.sub(s, eq + 1)
table.insert(info.comments, { key = string.upper(name), value = value })
local key = VorbisComment.tagKey(name)
local old = info.tags[key]
info.tags[key] = if old then old .. "; " .. value else value
end
+1 -1
View File
@@ -8,7 +8,7 @@
-- injected module). Nothing throws: open returns nil, message, code.
local Bytes = require("@formats/core/Bytes")
local Ogg = require("@formats/containers/Ogg")
local Frame = require("@formats/audio/flac/Frame")
local Frame = require("@formats/codecs/audio/Flac/Frame")
local Meta = require("@formats/audio/flac/Meta")
local Stream = {}
+6 -32
View File
@@ -5,9 +5,10 @@
-- with escapes, every stereo mode, 4-32 bits, 1-8 channels, any sample rate, fixed and variable block sizes, frame
-- CRC-16 checks with resync past corrupt frames, sample-accurate seeking (seek table + bisection), an ID3v2 tag in
-- front, STREAMINFO / SEEKTABLE / VORBIS_COMMENT / PICTURE metadata, the total length from the last frame when
-- STREAMINFO has none. Encode (audio/flac/Encode, ws-audio): native FLAC from an Audio or a streamed Decoder, levels
-- STREAMINFO has none. Encode (codecs/audio/Flac/Encode, ws-audio): native FLAC from an Audio or a streamed Decoder, levels
-- 0-8 like libFLAC's presets, 4-24 bits, 1-8 channels, MD5, VORBIS_COMMENT, SEEKTABLE. Not supported: MD5
-- verification on decode, chained Ogg streams, Ogg FLAC output.
-- The codec itself is codecs/audio/Flac; this folder maps it onto the file (container, tags, seeking, writing).
--
-- local dec = Flac.open(Bytes.reader(buf)) -- the Types.Decoder (+ bitsPerSample, readInt, seekSample, ...)
-- local f32, n = dec:read(4096) -- interleaved f32 in [-1, 1); n = 0 at the end
@@ -20,8 +21,8 @@ local Bytes = require("@formats/core/Bytes")
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 Encode = require("@formats/codecs/audio/Flac/Encode")
local Pcm = require("@formats/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Flac = {
@@ -29,7 +30,7 @@ local Flac = {
category = "audio",
extensions = { "flac", "oga" },
mime = { "audio/flac", "audio/x-flac" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "core/Md5", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Pcm", "codecs/audio/VorbisComment", "codecs/audio/Flac/Frame", "codecs/audio/Flac/Encode" },
caps = { decode = true, encode = true, streaming = true, depths = { 4, 8, 12, 16, 20, 24, 32 }, ogg = true, seek = true },
}
@@ -89,34 +90,7 @@ function Flac.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Er
if d.frames > limit or d.frames * d.channels > 2 ^ 28 then
return nil, Err.new(Err.LIMIT, string.format("%d frames is over the limit", d.frames))
end
local ch = d.channels
local parts, total = {}, 0
if d.frames > 0 then
local out, n = d:read(d.frames)
table.insert(parts, out)
total = n
end
while true do -- frames past what STREAMINFO / the scan said
local out, n = d:read(65536)
if n == 0 then
break
end
table.insert(parts, out)
total += n
if total > limit then
return nil, Err.new(Err.LIMIT, "stream over the frame limit")
end
end
local a = Types.Audio.new(d.sampleRate, ch, total)
local o = 0
for _, p in parts do
local n = math.min(buffer.len(p), total * ch * 4 - o)
buffer.copy(a.samples, o, p, 0, n)
o += n
end
a.tags = d.tags
a.meta.source = { format = "flac", bitDepth = d.bitsPerSample, container = d.container, vendor = d.vendor, md5 = d.md5, pictures = d.pictures }
return a, nil
return Pcm.drain(d, { format = "flac", bitDepth = d.bitsPerSample, container = d.container, vendor = d.vendor, md5 = d.md5, pictures = d.pictures, comments = d.comments }, limit)
end
-- ------------------------------------------------------------------------------------------------ encode
+32 -133
View File
@@ -1,6 +1,6 @@
--!strict
-- audio/m4a: MPEG-4 audio files (M4A / M4B / MP4 / MOV audio tracks) through containers/IsoBmff. Supports: reading
-- AAC-LC (codecs/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/Alac) tracks, gapless
-- AAC-LC (codecs/audio/Aac; HE-AAC files play their AAC-LC core at the core rate) and ALAC (codecs/audio/Alac) tracks, gapless
-- trimming through the edit list (encoder priming / padding), seeking, iTunes tags and cover art (dec.pictures);
-- writing ALAC (16 / 20 / 24-bit, 1 - 8 channels) with tags and cover art. Not supported: writing AAC, other codecs
-- inside MP4 (MP3 / Opus / FLAC / AC-3: UNSUPPORTED), encrypted files.
@@ -9,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/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 = {
@@ -19,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" },
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 },
}
@@ -121,7 +123,7 @@ end
-- open(r, opts?) -> Types.Decoder | nil, Err
function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.Err?)
local o = opts or {}
local o: DecodeOptions = opts or {}
local movie, err = IsoBmff.parse(r, { maxSamples = o.maxSamples })
if not movie then
return nil, err
@@ -167,11 +169,11 @@ function M4a.open(r: Bytes.Reader, opts: DecodeOptions?): (Types.Decoder?, Err.E
end
local tags, pictures = IsoBmff.tags(r, movie)
-- iTunes gapless info (fdkaac, iTunes) when there is no edit list: " 0 <priming> <padding> <samples> ..." (hex)
local smpb = tags.iTunSMPB
local smpb = tags.itunsmpb
if gapless and not t.edits and smpb then
local f = {}
local f: { number } = {}
for w in string.gmatch(smpb, "%x+") do
table.insert(f, tonumber(w, 16))
table.insert(f, tonumber(w, 16) :: number)
end
if #f >= 4 and f[2] and f[4] and f[4] > 0 and f[2] + f[4] <= total then
skip = f[2]
@@ -180,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,
@@ -200,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)
@@ -306,38 +226,17 @@ function M4a.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Audio?, Err.E
return nil, err
end
local d: any = dec
local audio = Types.Audio.new(d.sampleRate, d.channels, d.frames)
local done = 0
local chunk = buffer.create(65536 * d.channels * 4)
while done < d.frames do
local b, n = d:read(math.min(65536, d.frames - done), chunk)
if n == 0 then
break
end
buffer.copy(audio.samples, done * d.channels * 4, b, 0, n * d.channels * 4)
done += n
end
if d.error then
return nil, d.error
end
if done < d.frames then
local short = buffer.create(done * d.channels * 4)
buffer.copy(short, 0, audio.samples, 0, buffer.len(short))
audio.samples = short
audio.frames = done
end
audio.tags = d.tags
audio.meta.source = { format = "m4a", codec = d.codec, bitsPerSample = d.track.bitsPerSample, brand = d.movie.brand }
if #d.pictures > 0 then
local audio, derr = Pcm.drain(d, { format = "m4a", codec = d.codec, bitsPerSample = d.track.bitsPerSample, brand = d.movie.brand })
if audio and #d.pictures > 0 then
audio.meta.pictures = d.pictures
end
return audio, nil
return audio, derr
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(audio | decoder, opts?) -> buffer | nil, Err: an ALAC M4A
function M4a.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o = opts or {}
local o: EncodeOptions = opts or {}
if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
end
+4 -4
View File
@@ -5,8 +5,8 @@
-- (same sync, resync and Xing / LAME handling), and simulates the layer III bit reservoir from the side info, so
-- it knows in advance which frames give output and where each one's samples land. That makes the total length
-- exact and seeking sample-accurate. Never throws.
local Header = require("@formats/audio/mp3/Header")
local Core = require("@formats/audio/mp3/Core")
local Header = require("@formats/codecs/audio/Mpa/Header")
local Core = require("@formats/codecs/audio/Mpa/Core")
local band, rshift = bit32.band, bit32.rshift
local ru8 = buffer.readu8
@@ -101,7 +101,7 @@ function Index.build(b: buffer, start: number, stop: number): Index?
if first then
first = false
hz, nch, layer, spf = fHz, fCh, fLayer, Header.frameSamples(h1)
hz, nch, layer, spf = fHz, fCh, fLayer, Header.frameSamples(h1) :: number
version = if band(h1, 8) ~= 0 then 1 elseif band(h1, 0x10) ~= 0 then 2 else 2.5
if fLayer == 3 then
local ret, frames, d, p = Core.vbrTag(b, pos, fs)
@@ -150,7 +150,7 @@ function Index.build(b: buffer, start: number, stop: number): Index?
end
if n == cap then
cap *= 2
OFF, SIZE, FLAGS, OUT, MAIN = grow(OFF, cap * 4), grow(SIZE, cap * 2), grow(FLAGS, cap), grow(OUT, cap * 4), grow(MAIN, cap * 2)
OFF, SIZE, FLAGS, OUT, MAIN = grow(OFF, cap * 4), grow(SIZE, cap * 2), grow(FLAGS, cap), grow(OUT, cap * 4), grow(MAIN, cap * 2) :: buffer
end
buffer.writeu32(OFF, n * 4, pos)
buffer.writeu16(SIZE, n * 2, fs)
+1 -1
View File
@@ -2,7 +2,7 @@
--!optimize 2
-- audio/mp3/Stream: the streaming Decoder (Types.Decoder) over a frame index: gapless (LAME delay / padding), exact
-- length, sample-accurate seeking. From mp3-luau's Mp3.open / Decoder (same author). Never throws.
local Core = require("@formats/audio/mp3/Core")
local Core = require("@formats/codecs/audio/Mpa/Core")
local Index = require("@formats/audio/mp3/Index")
local FLAG_RESET, FLAG_OUTPUT = Index.FLAG_RESET, Index.FLAG_OUTPUT
+9 -7
View File
@@ -35,8 +35,8 @@ local FIELDS = {
TIT2 = "title", TT2 = "title",
TPE1 = "artist", TP1 = "artist",
TALB = "album", TAL = "album",
TPE2 = "albumArtist", TP2 = "albumArtist",
TYER = "year", TYE = "year", TDRC = "year",
TPE2 = "albumartist", TP2 = "albumartist",
TYER = "date", TYE = "date", TDRC = "date",
TRCK = "track", TRK = "track",
TPOS = "disc", TPA = "disc",
TCON = "genre", TCO = "genre",
@@ -179,7 +179,8 @@ local function parseV2(b: buffer, o: number, size: number, tags: any)
local p, e = o + 10, bodyEnd
if band(flags, 0x80) ~= 0 and ver < 4 then
body = deunsync(b, p, e)
p, e = 0, buffer.len(body)
p = 0
e = buffer.len(body)
end
if band(flags, 0x40) ~= 0 and ver >= 3 and p + 4 <= e then
-- extended header: v2.3 size excludes its own 4 bytes, v2.4 includes them (syncsafe)
@@ -216,7 +217,8 @@ local function parseV2(b: buffer, o: number, size: number, tags: any)
end
if not skip and band(fflags, 0x0002) ~= 0 and fs < fe then
fb = deunsync(body, fs, fe)
fs, fe = 0, buffer.len(fb)
fs = 0
fe = buffer.len(fb)
end
end
if not skip and fs < fe then
@@ -257,7 +259,7 @@ local function v1String(b: buffer, o: number, n: number): string
end
-- Parses tags and returns (tags, audio start, audio end) for the buffer b.
-- tags = { title?, artist?, album?, albumArtist?, year?, track?, disc?, genre?, composer?, comment?,
-- tags = { title?, artist?, album?, albumartist?, date?, track?, disc?, genre?, composer?, comment?,
-- raw = { [frame id] = text }, id3v2 = "2.3"?, id3v1 = true? }
function Tags.parse(b: buffer): (any, number, number)
local len = buffer.len(b)
@@ -273,11 +275,11 @@ function Tags.parse(b: buffer): (any, number, number)
if size >= 128 and buffer.readstring(b, start + size - 128, 3) == "TAG" then
local o = start + size - 128
tags.id3v1 = true
local v1 = {
local v1: { [string]: any } = {
title = v1String(b, o + 3, 30),
artist = v1String(b, o + 33, 30),
album = v1String(b, o + 63, 30),
year = v1String(b, o + 93, 4),
date = v1String(b, o + 93, 4),
}
if ru8(b, o + 125) == 0 and ru8(b, o + 126) ~= 0 then
v1.comment = v1String(b, o + 97, 28)
+44 -21
View File
@@ -4,9 +4,11 @@
-- layers I / II / III, mono / stereo / joint stereo / dual channel, CBR / VBR / free format, gapless playback (Xing /
-- Info + LAME delay and padding), exact length and sample-accurate seeking from a frame index built on open, resync
-- 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
-- Float output (minimp3's MINIMP3_FLOAT_OUTPUT scalar path). Encode (ws-audio, codecs/audio/Mpa/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. Not supported: MPEG-2 multichannel extension, CRC checks, VBR / Xing output, encoder resampling.
-- 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.
-- The codec itself is codecs/audio/Mpa; this folder maps it onto the file (container, tags, seeking, writing).
--
-- local dec = Mp3.open(Bytes.reader(buf)) -- the streaming Types.Decoder (+ layer, version, vbr, delay,
-- local pcm, n = dec:read(4096) -- padding, mpegFrames, id3, :seekFrame(i), :readAll())
@@ -16,13 +18,14 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Header = require("@formats/audio/mp3/Header")
local Header = require("@formats/codecs/audio/Mpa/Header")
local Index = require("@formats/audio/mp3/Index")
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 Encode3 = require("@formats/codecs/audio/Mpa/Encode3")
local Encode2 = require("@formats/codecs/audio/Mpa/Encode2")
local Pcm = require("@formats/codecs/audio/Pcm")
local Resample = require("@formats/codecs/audio/Resample")
-- ------------------------------------------------------------------------------------------------ contract
local Mp3 = {
@@ -30,8 +33,8 @@ local Mp3 = {
category = "audio",
extensions = { "mp3", "mp2", "mp1", "mpga" },
mime = { "audio/mpeg", "audio/mp3", "audio/mpa" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, channels = 2 },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/Mpa/Header", "codecs/audio/Mpa/Core", "codecs/audio/Mpa/Encode3", "codecs/audio/Mpa/Encode2" },
caps = { decode = true, encode = true, streaming = true, seek = true, layers = { 1, 2, 3 }, encodeLayers = { 2, 3 }, channels = 2 },
}
-- ------------------------------------------------------------------------------------------------ types
@@ -45,6 +48,9 @@ export type EncodeOptions = {
mode: ("stereo" | "joint" | "mono")?, -- default "joint" (mid / side) for stereo layer III, "stereo" for layer II,
-- "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/audio/Resample)
resampleQuality: ("low" | "medium" | "high")?, -- codecs/audio/Resample quality (default "medium")
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -86,14 +92,11 @@ function Mp3.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err
if not dec then
return nil, err
end
local a = Types.Audio.new(dec.sampleRate, dec.channels, dec.frames)
local _, n = dec:read(dec.frames, a.samples)
if n < dec.frames then
return nil, Err.new(Err.CORRUPT, string.format("decoded %d of %d frames", n, dec.frames))
local a, derr = Pcm.drain(dec, { format = "mp3", layer = dec.layer, version = dec.version, bitrate = dec.bitrate, vbr = dec.vbr })
if a and a.frames < dec.frames then
return nil, Err.new(Err.CORRUPT, string.format("decoded %d of %d frames", a.frames, dec.frames))
end
a.tags = dec.tags
a.meta.source = { format = "mp3", layer = dec.layer, version = dec.version, bitrate = dec.bitrate, vbr = dec.vbr }
return a, nil
return a, derr
end
-- ------------------------------------------------------------------------------------------------ encode
@@ -101,7 +104,7 @@ local ID3_FRAMES = {
{ "title", "TIT2" },
{ "artist", "TPE1" },
{ "album", "TALB" },
{ "albumArtist", "TPE2" },
{ "albumartist", "TPE2" },
{ "year", "TDRC" },
{ "date", "TDRC" },
{ "track", "TRCK" },
@@ -170,10 +173,30 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
return nil, Err.new(Err.ARG, "layer must be 2 or 3")
end
local Enc = if layer == 3 then Encode3 else Encode2
local info = Enc.RATES[src.sampleRate]
if not info then
return nil, Err.new(Err.ARG, string.format("layer %d cannot hold %s Hz (no resampling)", layer, tostring(src.sampleRate)))
-- 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/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)))
end
if not Enc.RATES[rate] then
local best, top = nil, 0
for r in Enc.RATES do
top = math.max(top, r)
if r >= rate and (best == nil or r < best) then
best = r
end
end
rate = best or top
end
if rate ~= src.sampleRate then
local rs, rerr = Resample.source(src, rate, { quality = o.resampleQuality })
if not rs then
return nil, Err.new(Err.ARG, tostring(rerr))
end
src = rs
end
local info = Enc.RATES[rate]
local mpeg1 = info[1] == 3
local mode = o.mode or (if src.channels == 1 then "mono" elseif layer == 3 then "joint" else "stereo")
if mode ~= "stereo" and mode ~= "joint" and mode ~= "mono" then
@@ -187,7 +210,7 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
local bitrate = o.bitrate or (if mpeg1 then (if layer == 3 then 128 else 192) else (if layer == 3 then 64 else 96))
if not table.find(Enc.BITRATES[if mpeg1 then 1 else 2], bitrate) then
return nil, Err.new(Err.ARG, string.format("%s kbps is not a layer %d bit rate at %d Hz", tostring(bitrate), layer, src.sampleRate))
return nil, Err.new(Err.ARG, string.format("%s kbps is not a layer %d bit rate at %d Hz", tostring(bitrate), layer, rate))
end
if layer == 2 and mpeg1 then
-- the standard's allowed bit rate / mode combinations
@@ -206,7 +229,7 @@ function Mp3.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ open
-- the string-valued tag fields (title, artist, album, albumArtist, year, track, disc, genre, composer, comment)
-- the string-valued tag fields (title, artist, album, albumartist, date, track, disc, genre, composer, comment)
local function stringTags(t: any): { [string]: string }
local out: { [string]: string } = {}
for k, v in t do
+34 -102
View File
@@ -1,12 +1,16 @@
--!strict
-- audio/opus/Encode: Ogg Opus writing (RFC 7845) around audio/opus/CeltEncoder: CELT-only packets (TOC config 31:
-- audio/opus/Encode: Ogg Opus writing (RFC 7845) around codecs/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 (a Kaiser-windowed sinc; quality enough for a codec input). New in formats-luau.
-- 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 CeltEncoder = require("@formats/audio/opus/CeltEncoder")
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/codecs/audio/Opus/CeltEncoder")
local Encode = {}
@@ -17,69 +21,20 @@ export type Options = {
serial: number?, -- Ogg stream serial (default 0x4f707573)
}
local floor, sin, pi, sqrt = math.floor, math.sin, math.pi, math.sqrt
local function besselI0(x: number): number
local sum, term = 1, 1
for k = 1, 60 do
term *= (x / (2 * k)) ^ 2
sum += term
if term < sum * 1e-15 then
break
end
end
return sum
end
-- resample(src (interleaved f32 buffer), frames, channels, from, to) -> { number } interleaved, frames out
local function resample(src: buffer, frames: number, channels: number, from: number, to: number): ({ number }, number)
local outFrames = floor(frames * to / from + 0.5)
local out = table.create(outFrames * channels, 0)
local ratio = to / from
local cutoff = 0.97 * math.min(1, ratio) -- of the input Nyquist
local half = 16 -- zero crossings each side (at the cutoff)
local width = half / cutoff
local beta = 8
local i0b = besselI0(beta)
local readf32 = buffer.readf32
for j = 0, outFrames - 1 do
local t = j / ratio -- the input position
local first = math.max(0, floor(t - width) + 1)
local last = math.min(frames - 1, floor(t + width))
for c = 0, channels - 1 do
local acc, wsum = 0, 0
for i = first, last do
local d = i - t
local x = d * cutoff
local s = if x == 0 then 1 else sin(pi * x) / (pi * x)
local r = d / width
local w = besselI0(beta * sqrt(math.max(0, 1 - r * r))) / i0b
local h = s * w
acc += readf32(src, (i * channels + c) * 4) * h
wsum += h
end
out[j * channels + c + 1] = if wsum ~= 0 then acc / wsum else 0
end
end
return out, outFrames
end
local TAG_NAMES: { [string]: string } = {
title = "TITLE", artist = "ARTIST", album = "ALBUM", albumartist = "ALBUMARTIST", date = "DATE", genre = "GENRE",
track = "TRACKNUMBER", tracktotal = "TRACKTOTAL", disc = "DISCNUMBER", comment = "COMMENT", composer = "COMPOSER",
}
local floor = math.floor
-- encode(audio | decoder, opts) -> buffer | nil, Err
function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
local o = opts or {}
if type(value) ~= "table" or type(value.sampleRate) ~= "number" or type(value.channels) ~= "number" then
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
local o: Options = opts or {}
local src, serr = Pcm.source(value)
if not src then
return nil, serr
end
local ch = value.channels
local ch = src.channels
if ch ~= 1 and ch ~= 2 then
return nil, Err.new(Err.UNSUPPORTED, "the CELT encoder writes mono or stereo (got " .. ch .. " channels)")
end
local rate = value.sampleRate
local rate = src.sampleRate
if rate < 1000 or rate > 768000 then
return nil, Err.new(Err.ARG, "bad sample rate " .. tostring(rate))
end
@@ -87,40 +42,24 @@ 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 as an interleaved f32 buffer
local samples: buffer, frames: number
if value.kind == "audio" and type(value.samples) == "buffer" then
samples, frames = value.samples, value.frames
if buffer.len(samples) < frames * ch * 4 then
return nil, Err.new(Err.ARG, "audio.samples is shorter than frames * channels")
-- 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
return nil, Err.new(Err.ARG, tostring(rerr))
end
elseif type(value.read) == "function" then
local w = Bytes.writer(65536)
frames = 0
local chunk: buffer? = nil
while true do
local b, n = value:read(16384, chunk)
chunk = b
if n <= 0 then
break
end
w:bytes(b, 0, n * ch * 4)
frames += n
end
samples = w:finish()
else
return nil, Err.new(Err.ARG, "expected an Audio or a Decoder")
src = rs
end
-- 48 kHz floats
local pcm: { number }, n48: number
if rate == 48000 then
n48 = frames
pcm = table.create(frames * ch, 0)
for i = 1, frames * ch do
pcm[i] = buffer.readf32(samples, (i - 1) * 4)
end
else
pcm, n48 = resample(samples, frames, ch, rate, 48000)
local all, aerr = Pcm.collect(src :: Pcm.Source)
if not all then
return nil, aerr
end
local n48 = all.frames
local samples = all.samples
local pcm: { number } = table.create(n48 * ch, 0)
local readf32 = buffer.readf32
for i = 1, n48 * ch do
pcm[i] = readf32(samples, (i - 1) * 4)
end
local FRAME = CeltEncoder.FRAME
local preSkip = CeltEncoder.DELAY
@@ -144,22 +83,15 @@ function Encode.encode(value: any, opts: Options?): (buffer?, Err.Err?)
head:u8(0)
s:packet(head:finish(), 0, { flush = true })
-- OpusTags
local tags = o.tags or value.tags or {}
local tags = o.tags or src.tags or {}
local tw = Bytes.writer(256)
tw:string("OpusTags")
local vendor = o.vendor or "formats-luau"
tw:u32le(#vendor)
tw:string(vendor)
local keys = {}
for k, v in tags do
if type(k) == "string" and type(v) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
tw:u32le(#keys)
for _, k in keys do
local field = (TAG_NAMES[k] or string.upper(k)) .. "=" .. tags[k]
local fields = VorbisComment.fields(tags)
tw:u32le(#fields)
for _, field in fields do
tw:u32le(#field)
tw:string(field)
end
+39 -55
View File
@@ -11,6 +11,7 @@
-- projection), chained streams (the first Opus stream is decoded), CELT pitch PLC (noise PLC only).
-- Changes from opus-luau: the injected Ogg demuxer is containers/Ogg; errors are core/Err values; read() takes an
-- optional output buffer; decode() fully decodes to an Audio.
-- The codec itself is codecs/audio/Opus; this folder maps it onto the file (container, tags, seeking, writing).
--
-- local dec, err = Opus.open(Bytes.reader(buf)) -- the Types.Decoder: dec:read(n, out?), dec:seek(s), ...
-- local audio = Opus.decode(Bytes.reader(buf)) -- a Types.Audio
@@ -22,11 +23,13 @@ local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
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 RangeDecoder = require("@formats/audio/opus/RangeDecoder")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
local Decoder = require("@formats/codecs/audio/Opus/Decoder")
local Packet = require("@formats/codecs/audio/Opus/Packet")
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/codecs/audio/Opus/Celt")
local Silk = require("@formats/codecs/audio/Opus/Silk")
local Encode = require("@formats/audio/opus/Encode")
-- ------------------------------------------------------------------------------------------------ contract
@@ -35,8 +38,8 @@ local Opus = {
category = "audio",
extensions = { "opus" },
mime = { "audio/opus", "audio/ogg" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/Mdct" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" } },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/entropy/RangeCoder/Decoder", "codecs/audio/Pcm", "codecs/audio/Resample", "codecs/audio/VorbisComment", "codecs/audio/Opus/CeltEncoder", "codecs/audio/Opus/Decoder", "codecs/audio/Opus/Packet", "codecs/audio/Opus/Celt", "codecs/audio/Opus/Silk" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255, rates = { 48000 }, encodeModes = { "celt" }, encodeChannels = 2 },
}
-- ------------------------------------------------------------------------------------------------ types
@@ -124,46 +127,40 @@ local function parseHead(b: buffer, off: number, size: number): (Head?, string?)
return head, nil
end
-- OpusTags (RFC 7845 section 5.2): vendor string and a table of lower-cased field names to values (repeated
-- fields joined with "; ").
local function parseTags(b: buffer, off: number, size: number): (string, { [string]: string })
local tags = {}
-- 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
return "", tags
return "", {}, {}
end
local p = off + 8
local e = off + size
local vlen = buffer.readu32(b, p)
p += 4
if p + vlen > e then
return "", tags
return "", {}, {}
end
local vendor = buffer.readstring(b, p, vlen)
p += vlen
if p + 4 > e then
return vendor, tags
end
local n = buffer.readu32(b, p)
p += 4
for _ = 1, n do
if p + 4 > e then
break
end
local l = buffer.readu32(b, p)
local list = {}
if p + 4 <= e then
local n = buffer.readu32(b, p)
p += 4
if p + l > e then
break
end
local s = buffer.readstring(b, p, l)
p += l
local eq = string.find(s, "=", 1, true)
if eq then
local k = string.lower(string.sub(s, 1, eq - 1))
local v = string.sub(s, eq + 1)
tags[k] = if tags[k] then tags[k] .. "; " .. v else v
for _ = 1, n do
if p + 4 > e then
break
end
local l = buffer.readu32(b, p)
p += 4
if p + l > e then
break
end
table.insert(list, buffer.readstring(b, p, l))
p += l
end
end
return vendor, tags
local tags, raw = VorbisComment.tags(list)
return vendor, tags, raw
end
Opus.Decoder = Decoder
@@ -195,26 +192,7 @@ function Opus.decode(r: any, opts: OpenOptions?): (Types.Audio?, Err.Err?)
if not dec then
return nil, err
end
local ch = dec.channels
local a = Types.Audio.new(SAMPLE_RATE, ch, dec.frames)
local total = 0
while total < dec.frames do
local pcm, n = dec:read(math.min(65536, dec.frames - total))
if n == 0 then
break
end
buffer.copy(a.samples, total * ch * 4, pcm, 0, n * ch * 4)
total += n
end
if total < dec.frames then -- a truncated file: keep what decoded
local s = buffer.create(total * ch * 4)
buffer.copy(s, 0, a.samples, 0, total * ch * 4)
a.samples = s
a.frames = total
end
a.tags = dec.tags
a.meta.source = { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate }
return a, nil
return Pcm.drain(dec, { format = "opus", channels = dec.sourceChannels, preSkip = dec.preSkip, vendor = dec.vendor, comments = dec.comments, mappingFamily = dec.head.mappingFamily, inputSampleRate = dec.head.inputSampleRate })
end
-- ------------------------------------------------------------------------------------------------ encode
@@ -288,6 +266,9 @@ function Stream.read(self: any, maxFrames: number, into: buffer?): (buffer, numb
Decoder.writeDownmix(self.pend, self.pendPos * self.sourceChannels, n, self.sourceChannels, self.downmix, gain, out, got * 8)
else
Decoder.writeF32(self.pend, self.pendPos * ch, n * ch, gain, out, got * ch * 4)
if self.order then
Pcm.reorder(out, got * ch * 4, n, ch, self.order)
end
end
self.pendPos += n
got += n
@@ -356,7 +337,7 @@ function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?)
if tp == nil then
return nil, Err.new(Err.TRUNCATED, "missing OpusTags")
end
local vendor, tags = parseTags(tp.data, tp.offset, tp.size)
local vendor, tags, rawTags = parseTags(tp.data, tp.offset, tp.size)
-- granule of the first audio sample: first page granule minus the packets that end on it
local startGranule = 0
local sum = 0
@@ -391,6 +372,9 @@ function Opus.open(r: any, opts: OpenOptions?): (any, Err.Err?)
head = head,
vendor = vendor,
tags = tags,
comments = rawTags,
-- 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,
sourceChannels = head.channels,
+2 -2
View File
@@ -11,7 +11,7 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/Pcm")
local Pcm = require("@formats/codecs/audio/Pcm")
-- ------------------------------------------------------------------------------------------------ contract
local Voc = {
@@ -19,7 +19,7 @@ local Voc = {
category = "audio",
extensions = { "voc" },
mime = { "audio/x-voc" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Pcm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/audio/Pcm" },
caps = { decode = true, encode = true, streaming = true, depths = { 8, 16 }, lossy = false },
}
+20 -18
View File
@@ -3,16 +3,18 @@
--!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 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")
local Tables = require("@formats/codecs/audio/Vorbis/Tables")
local Encode = {}
@@ -448,17 +450,9 @@ local function commentHeader(vendor: string, tags: { [string]: string }): buffer
putString(w, "vorbis")
put(w, #vendor, 32)
putString(w, vendor)
local keys = {}
for k, v in tags do
if type(k) == "string" and type(v) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
put(w, #keys, 32)
for _, k in keys do
local name = if k == "track" then "TRACKNUMBER" else string.upper(k)
local s = name .. "=" .. tags[k]
local fields = VorbisComment.fields(tags)
put(w, #fields, 32)
for _, s in fields do
put(w, #s, 32)
putString(w, s)
end
@@ -610,13 +604,21 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
local plan = Mdct.new(N) :: Mdct.Plan
local win = Mdct.window("vorbis", N) :: { number }
-- input ring: per channel the samples of the current frame [k*1024 - 1024, k*1024 + 1024)
local frame = table.create(ch)
local frame: { { number } } = table.create(ch) :: any
for c = 1, ch do
frame[c] = table.create(N, 0)
end
-- the input is in WAVE channel order; input channel c goes to Vorbis channel order[c]
local order = Pcm.WAVE_FROM_VORBIS[ch] or {}
if #order ~= ch then
order = table.create(ch, 0)
for c = 1, ch do
order[c] = c
end
end
local blk = table.create(N, 0)
local X = table.create(ch)
local R = table.create(ch)
local X: { { number } } = table.create(ch) :: any
local R: { { number } } = table.create(ch) :: any
for c = 1, ch do
X[c] = table.create(N2, 0)
R[c] = table.create(N2, 0)
@@ -658,7 +660,7 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
for i = 0, take - 1 do
local base = (pendOff + i) * ch * 4
for c = 1, ch do
frame[c][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4)
frame[order[c]][N2 + got + i + 1] = buffer.readf32(pb, base + (c - 1) * 4)
end
end
got += take
+34 -50
View File
@@ -1,6 +1,6 @@
--!strict
-- audio/vorbis: Ogg Vorbis (Vorbis I specification, Xiph.Org; RFC 5215 for the Ogg mapping). The decoder is a Luau
-- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/Mdct,
-- port of stb_vorbis 1.22 (public domain / MIT, licenses/stb_vorbis-LICENSE.txt) on containers/Ogg and codecs/audio/Mdct,
-- with libvorbis' sample-exact timing: start trimming from the first page's granule, end trimming from the last
-- page's, granule-exact seeking (bisection, then decoding forward to a page boundary to recover the position).
-- Supports: decode / open of any channel count (1..255), rates, block sizes 64..8192, floor 1, residues 0 / 1 / 2,
@@ -9,16 +9,18 @@
-- Ogg Vorbis encoder from an Audio or a streamed Decoder (long blocks, floor 1, coupled residue 2, a fixed codebook
-- set, quality -1 .. 10). Not supported: floor 0 (Err.UNSUPPORTED, as in stb_vorbis; no encoder has produced it since
-- 2000), chained streams (the first logical Vorbis stream is decoded), short blocks in the encoder.
-- The codec itself is codecs/audio/Vorbis; this folder maps it onto the file (container, tags, seeking, writing).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Ogg = require("@formats/containers/Ogg")
local Setup = require("@formats/audio/vorbis/Setup")
local Packet = require("@formats/audio/vorbis/Packet")
local Setup = require("@formats/codecs/audio/Vorbis/Setup")
local Packet = require("@formats/codecs/audio/Vorbis/Packet")
local Encode = require("@formats/audio/vorbis/Encode")
local Pcm = require("@formats/codecs/Pcm")
local Pcm = require("@formats/codecs/audio/Pcm")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
-- ------------------------------------------------------------------------------------------------ contract
local Vorbis = {
@@ -26,7 +28,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" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "codecs/audio/Mdct", "codecs/audio/Pcm", "codecs/audio/VorbisComment", "codecs/audio/Vorbis/Tables", "codecs/audio/Vorbis/Setup", "codecs/audio/Vorbis/Packet" },
caps = { decode = true, encode = true, streaming = true, seek = true, lossy = true, channels = 255 },
}
@@ -40,38 +42,36 @@ export type EncodeOptions = {
}
-- ------------------------------------------------------------------------------------------------ constants
local TAG_KEYS = { tracknumber = "track", description = "comment" }
local function tagsOf(comments: { string }): Types.Tags
local tags: Types.Tags = {}
for _, s in comments do
local eq = string.find(s, "=", 1, true)
if eq then
local k = string.lower(string.sub(s, 1, eq - 1))
local v = string.sub(s, eq + 1)
k = TAG_KEYS[k] or k
tags[k] = if tags[k] then tags[k] .. "; " .. v else v
end
-- 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
return m
end
return tags
local id = table.create(ch, 0)
for c = 1, ch do
id[c] = c
end
return id
end
-- the three headers -> ident, setup, vendor, tags | nil, Err
local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, Err.Err?)
-- the three headers -> ident, setup, vendor, tags, raw comment fields | nil, Err
local function headers(h1: any, h2: any, h3: any): (any, any, string?, Types.Tags?, { VorbisComment.Field }?, Err.Err?)
local id, ierr = Setup.ident(h1.data, h1.offset, h1.size)
if not id then
return nil, nil, nil, nil, Err.new(Err.CORRUPT, ierr or "bad identification header")
return nil, nil, nil, nil, nil, Err.new(Err.CORRUPT, ierr or "bad identification header")
end
local vendor, comments = Setup.comment(h2.data, h2.offset, h2.size)
if not vendor then
return nil, nil, nil, nil, Err.new(Err.CORRUPT, "bad comment header")
return nil, nil, nil, nil, nil, Err.new(Err.CORRUPT, "bad comment header")
end
local setup, serr = Setup.setup(h3.data, h3.offset, h3.size, id)
if not setup then
local code = if serr == "floor 0" then Err.UNSUPPORTED else Err.CORRUPT
return nil, nil, nil, nil, Err.new(code, serr or "bad setup header")
return nil, nil, nil, nil, nil, Err.new(code, serr or "bad setup header")
end
return id, setup, vendor, tagsOf(comments or {}), nil
local tags, raw = VorbisComment.tags(comments or {})
return id, setup, vendor, tags, raw, nil
end
-- ------------------------------------------------------------------------------------------------ sniff
@@ -94,28 +94,7 @@ function Vorbis.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.
if not dec then
return nil, err
end
local d = dec :: any
local ch = d.channels
local parts, total = {}, 0
while true do
local b, n = d:read(65536)
if n == 0 then
break
end
local copy = buffer.create(n * ch * 4)
buffer.copy(copy, 0, b, 0, n * ch * 4)
table.insert(parts, copy)
total += n
end
local a = Types.Audio.new(d.sampleRate, ch, total)
local o = 0
for _, p in parts do
buffer.copy(a.samples, o, p)
o += buffer.len(p)
end
a.tags = d.tags
a.meta.source = d.source
return a, nil
return Pcm.drain(dec)
end
-- ------------------------------------------------------------------------------------------------ encode
@@ -244,8 +223,9 @@ function Stream.read(self: any, n: number, out: buffer?): (buffer, number)
end
local arrays, first, last = q[1], q[2], q[3]
local take = math.min(n - got, last - first + 1)
local order = self.order
for c = 1, ch do
local a = arrays[c]
local a = arrays[order[c]]
local o = got * ch * 4 + (c - 1) * 4
for i = first, first + take - 1 do
writef32(b, o, a[i])
@@ -373,7 +353,7 @@ function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
if h3 == nil then
return nil, Err.new(Err.TRUNCATED, "missing setup header")
end
local id, setup, vendor, tags, herr = headers(h1, h2copy, h3)
local id, setup, vendor, tags, raw, herr = headers(h1, h2copy, h3)
if not id then
return nil, herr
end
@@ -420,10 +400,13 @@ function Vorbis.open(r: any, opts: OpenOptions?): (Types.Decoder?, Err.Err?)
tags = tags,
vendor = vendor,
ident = id,
-- WAVE channel order out (codecs/audio/Pcm): output channel c is Vorbis channel order[c]
order = waveOrder(id.channels),
source = {
format = "vorbis",
codec = "vorbis",
vendor = vendor,
comments = raw,
blocksizes = { id.blocksize0, id.blocksize1 },
nominalBitrate = id.bitrateNominal,
},
@@ -456,7 +439,7 @@ function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err
local function pk(b: buffer): any
return { data = b, offset = 0, size = buffer.len(b) }
end
local id, setup, vendor, tags, err = headers(pk(h1), pk(h2), pk(h3))
local id, setup, vendor, tags, _, err = headers(pk(h1), pk(h2), pk(h3))
if not id then
return nil, err
end
@@ -469,7 +452,8 @@ function Vorbis.packetDecoder(h1: buffer, h2: buffer, h3: buffer): (any, Err.Err
channels = id.channels,
vendor = vendor,
tags = tags,
out = st.out,
out = st.out, -- per Vorbis channel; WAVE-order channel c is out[order[c]]
order = waveOrder(id.channels),
decode = function(_self: any, b: buffer, offset: number, size: number): number
if offset < 0 or size < 0 or offset + size > buffer.len(b) then
return -1
+7 -14
View File
@@ -18,6 +18,7 @@
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Pcm = require("@formats/codecs/audio/Pcm")
local Riff = require("@formats/containers/Riff")
local Codecs = require("@formats/audio/wav/Codecs")
@@ -27,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" },
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 },
}
@@ -170,23 +171,14 @@ function Wav.decode(r: Bytes.Reader, opts: OpenOptions?): (Types.Audio?, Err.Err
if not dec then
return nil, err
end
local a = Types.Audio.new(dec.sampleRate, dec.channels, dec.frames)
local _, n = dec:read(dec.frames, a.samples)
if n < dec.frames then
local s = buffer.create(n * dec.channels * 4)
buffer.copy(s, 0, a.samples, 0, n * dec.channels * 4)
a.samples, a.frames = s, n
end
a.tags = dec.tags
a.meta.source = {
return Pcm.drain(dec, {
format = "wav",
codec = dec.format,
bitDepth = dec.bitsPerSample,
container = dec.container,
channelMask = dec.channelMask,
truncated = dec.truncated,
}
return a, nil
})
end
-- ------------------------------------------------------------------------------------------------ encode
@@ -304,7 +296,8 @@ local function encodeParts(value: any, opts: EncodeOptions?, asParts: boolean):
table.sort(keys)
for _, k in keys do
local v = tags[k]
local id = TAG_IDS[k] or (if #k == 4 and string.upper(k) == k then k else nil)
-- other RIFF INFO ids come back as their lower-cased id ("ixyz") and are written as such
local id = TAG_IDS[k] or (if string.match(string.lower(k), "^i[%l%d][%l%d][%l%d]$") then string.upper(k) else nil)
if id and type(v) == "string" and v ~= "" then
table.insert(items, { id, v })
end
@@ -383,7 +376,7 @@ function Wav.open(r: Bytes.Reader, _opts: OpenOptions?): (Decoder?, Err.Err?)
if sc.avail > 0 then
local v = trimTag(buffer.readstring(buf, sc.offset, sc.avail))
if v ~= "" then
tags[name or sc.id] = v
tags[name or string.lower(sc.id)] = v
end
end
end
+3 -5
View File
@@ -22,6 +22,7 @@
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Sniff = require("@formats/core/Sniff")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Parse = require("@formats/cad/step/Parse")
@@ -34,7 +35,7 @@ local Step = {
category = "cad",
extensions = { "step", "stp", "p21" },
mime = { "model/step", "application/step", "application/p21" },
deps = { "core/Err", "core/Bytes", "Types" },
deps = { "core/Err", "core/Bytes", "Types", "core/Sniff" },
caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" },
}
@@ -83,10 +84,7 @@ Step.schemaOf = schemaOf
-- ------------------------------------------------------------------------------------------------ sniff
function Step.sniff(r: Bytes.Reader): number
local head = r:peek(256)
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
local head = Sniff.text(r, 256)
head = string.gsub(head, "^%s*/%*.-%*/", "")
if string.find(head, "^%s*ISO%-10303%-21%s*;") then
return 1
-140
View File
@@ -1,140 +0,0 @@
--!strict
--!native
-- codecs/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, for data: URIs
-- (glTF, SVG, CSS), PEM-like text, YAML !!binary, ... New code. decode skips whitespace, accepts missing padding and
-- both alphabets; any other character is an error. Never throws.
--
-- local Base64 = require("@formats/codecs/Base64")
-- local s = Base64.encode(buf) -- string ("" for an empty buffer)
-- local b, err = Base64.decode(s) -- buffer | nil, "message"
-- local b2 = Base64.decodeDataUri("data:application/octet-stream;base64,AAEC") -- buffer, mime | nil, message
local Base64 = {}
local ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
local ALPHA_URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
local ENC = buffer.fromstring(ALPHA)
local ENC_URL = buffer.fromstring(ALPHA_URL)
-- the decode table: 0..63, 64 = skip (whitespace), 65 = padding, 255 = bad
local DEC = buffer.create(256)
buffer.fill(DEC, 0, 255)
for i = 1, 64 do
buffer.writeu8(DEC, string.byte(ALPHA, i), i - 1)
end
buffer.writeu8(DEC, string.byte("-"), 62)
buffer.writeu8(DEC, string.byte("_"), 63)
for _, c in { 9, 10, 13, 32 } do
buffer.writeu8(DEC, c, 64)
end
buffer.writeu8(DEC, string.byte("="), 65)
local readu8, writeu8 = buffer.readu8, buffer.writeu8
-- encode(buf, opts?, offset?, length?) -> string. opts.url: the URL-safe alphabet; opts.pad = false: no "=" padding.
function Base64.encode(buf: buffer, opts: { url: boolean?, pad: boolean? }?, offset: number?, length: number?): string
local o = math.clamp(offset or 0, 0, buffer.len(buf))
local n = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o)
local enc = if opts and opts.url then ENC_URL else ENC
local pad = not (opts and opts.pad == false)
local full = n // 3
local rest = n - full * 3
local outLen = full * 4 + (if rest == 0 then 0 elseif pad then 4 else rest + 1)
local out = buffer.create(outLen)
local p = 0
for i = 0, full - 1 do
local q = o + i * 3
local v = readu8(buf, q) * 65536 + readu8(buf, q + 1) * 256 + readu8(buf, q + 2)
writeu8(out, p, readu8(enc, v // 262144))
writeu8(out, p + 1, readu8(enc, (v // 4096) % 64))
writeu8(out, p + 2, readu8(enc, (v // 64) % 64))
writeu8(out, p + 3, readu8(enc, v % 64))
p += 4
end
if rest > 0 then
local q = o + full * 3
local v = readu8(buf, q) * 65536 + (if rest == 2 then readu8(buf, q + 1) * 256 else 0)
writeu8(out, p, readu8(enc, v // 262144))
writeu8(out, p + 1, readu8(enc, (v // 4096) % 64))
if rest == 2 then
writeu8(out, p + 2, readu8(enc, (v // 64) % 64))
elseif pad then
writeu8(out, p + 2, 61)
end
if pad then
writeu8(out, p + 3, 61)
end
end
return buffer.tostring(out)
end
-- decode(s) -> buffer | nil, message
function Base64.decode(s: string | buffer): (buffer?, string?)
local src = if type(s) == "string" then buffer.fromstring(s) else s
local n = buffer.len(src)
local out = buffer.create((n // 4 + 1) * 3)
local acc, bits, p = 0, 0, 0
local padded = false
for i = 0, n - 1 do
local d = readu8(DEC, readu8(src, i))
if d < 64 then
if padded then
return nil, "data after padding"
end
acc = acc * 64 + d
bits += 6
if bits >= 8 then
bits -= 8
local byte = acc // (2 ^ bits)
writeu8(out, p, byte % 256)
p += 1
acc = acc % (2 ^ bits)
end
elseif d == 65 then
padded = true
elseif d ~= 64 then
return nil, string.format("bad base64 character 0x%02x at %d", readu8(src, i), i)
end
end
if bits >= 6 then
return nil, "truncated base64 (a single character in the last group)"
end
local res = buffer.create(p)
buffer.copy(res, 0, out, 0, p)
return res, nil
end
-- decodeDataUri(uri) -> buffer, mime | nil, message: "data:[<mime>][;params][;base64],<data>" (percent-encoded data
-- when not base64)
function Base64.decodeDataUri(uri: string): (buffer?, string?)
if string.sub(uri, 1, 5) ~= "data:" then
return nil, "not a data: URI"
end
local comma = string.find(uri, ",", 6, true)
if not comma then
return nil, "data: URI without a comma"
end
local head = string.sub(uri, 6, comma - 1)
local isB64 = string.sub(head, -7) == ";base64"
local mime = string.match(head, "^([^;]*)") or ""
if mime == "" then
mime = "text/plain"
end
local body = string.sub(uri, comma + 1)
if isB64 then
local b, err = Base64.decode(body)
if not b then
return nil, err
end
return b, mime
end
local decoded = string.gsub(body, "%%(%x%x)", function(h: string): string
return string.char(tonumber(h, 16) :: number)
end)
return buffer.fromstring(decoded), mime
end
-- dataUri(buf, mime) -> "data:<mime>;base64,..."
function Base64.dataUri(buf: buffer, mime: string?): string
return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf)
end
return Base64
@@ -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
@@ -132,7 +132,7 @@ export type Channel = {
bandType: { number }, -- [g * maxSfb + sfb + 1]
sf: { number },
-- tns
tnsFilters: { { number } }, -- per window: { length, order, direction, coefs ... } flattened per filter
tnsFilters: { { { number } } }, -- per window: { length, order, direction, coefs ... } flattened per filter
}
export type State = {
@@ -447,7 +447,7 @@ local function spectralData(st: State, c: Channel, pulses: { number }?): string?
return "bad spectral code"
end
-- unpack the symbol into dim values (first value most significant)
local vals1, vals2, vals3, vals4
local vals1: number, vals2: number, vals3: number, vals4: number
if dim == 4 then
vals4 = sym % mod - off
sym = (sym - (sym % mod)) / mod
@@ -1,5 +1,5 @@
--!strict
-- codecs/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): the scalefactor and the eleven
-- codecs/audio/Aac/Tables: the AAC-LC tables of ISO/IEC 14496-3 (subpart 4, Annex 4.A): the scalefactor and the eleven
-- spectral Huffman codebooks (code, length per symbol), the scalefactor band offsets per sampling rate (1024 and 128
-- lines) and the TNS band limits. Transcribed from FFmpeg libavcodec/aactab.c (tables of the standard, no code;
-- see licenses/NOTICE.md). Generated; do not edit.
@@ -1,15 +1,15 @@
--!strict
-- codecs/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
-- codecs/audio/Aac: AAC-LC decoder (ISO/IEC 14496-3 subpart 4, ISO/IEC 13818-7): the AudioSpecificConfig (with a program
-- config element, explicit and backward-compatible SBR signalling), ADTS headers, and raw_data_block decoding
-- (codecs/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it.
-- Written from the standard (tables: codecs/Aac/Tables); no third-party code.
-- (codecs/audio/Aac/Decode). A codec (layer 1): audio/m4a, audio/aac (ADTS), and later MP4 / MKV / MPEG-TS video build on it.
-- Written from the standard (tables: codecs/audio/Aac/Tables); no third-party code.
-- Supports: AAC-LC (object type 2) 1 - 8 channels, all sampling rates, long / short / start / stop windows, sine and KBD
-- windows, M/S, intensity stereo, PNS, TNS, pulses. HE-AAC (SBR, PS: object types 5 / 29, or implicit SBR payloads)
-- decodes its AAC-LC core at the core rate; `decoder.onExtension` receives every FIL extension payload (the hook for a
-- later SBR / PS module), `decoder.sbr` says whether one was seen. Not supported: AAC Main prediction, LTP, SSR gain
-- control, coupling channels, 960-sample frames, ER / USAC object types (UNSUPPORTED).
--
-- local Aac = require("@formats/codecs/Aac")
-- local Aac = require("@formats/codecs/audio/Aac")
-- local dec, err = Aac.decoder(asc) -- an AudioSpecificConfig (buffer) or { objectType, sfIndex, channels }
-- local frames, err = dec:decode(buf, offset, length) -- one raw_data_block -> dec.pcm (frames * channels floats)
-- local h = Aac.adts(buf, offset, limit) -- an ADTS header: { headerSize, frameSize, objectType, sfIndex, ... }
@@ -17,7 +17,7 @@
-- Never throws: bad data returns nil, Err.
local Err = require("@formats/core/Err")
local Bits = require("@formats/core/Bits")
local Decode = require("@formats/codecs/Aac/Decode")
local Decode = require("@formats/codecs/audio/Aac/Decode")
local Aac = {}
@@ -310,7 +310,7 @@ function Aac.decoder(asc: any): (Decoder?, Err.Err?)
sbr = false,
ps = false,
frameLength = 1024,
}
} :: Config
else
return nil, Err.new(Err.ARG, "decoder: expected an AudioSpecificConfig buffer")
end
@@ -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.
@@ -267,8 +267,8 @@ function Decode.frame(st: State, buf: buffer, off: number, len: number): (number
local x = bitsAt(b, pos, 8)
local y = bitsAt(b, pos + 8, 8)
pos += 16
mode[c], denShift[c] = rshift(x, 4), band(x, 15)
pbFactor[c], order[c] = rshift(y, 5), band(y, 31)
mode[c], denShift[c] = rshift(x, 4), band(x, 15) :: number
pbFactor[c], order[c] = rshift(y, 5), band(y, 31) :: number
if pos + order[c] * 16 > limit then
return nil, "frame runs past the end"
end
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of
-- codecs/audio/Alac/Encode: an ALAC frame encoder: per element (SCE / CPE) the stereo mix (mixBits 2, the best mixRes of
-- 0 .. 4 by first-difference energy), per channel LPC coefficients (Levinson-Durbin on a windowed autocorrelation,
-- orders 4 and 8 tried, quantised with denShift 9), residuals through the same adaptive FIR the decoder runs, the
-- adaptive Golomb-Rice code with zero runs; an uncompressed (escape) frame when that is smaller. 16 / 20 / 24-bit
@@ -1,10 +1,10 @@
--!strict
-- codecs/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
-- codecs/audio/Alac: Apple Lossless (ALAC) decoder and encoder, the codec inside m4a / mov / caf. A codec (layer 1).
-- Written from the ALAC format as Apple published it (ALACSpecificConfig, the element syntax, adaptive Golomb-Rice
-- residuals, the adaptive FIR predictor); no third-party code. 1 - 8 channels, 16 / 20 / 24 / 32-bit decode, 16 / 20 /
-- 24-bit encode. Channels come out (and go in) in WAV order (ALAC stores C L R ... for 3+ channels).
--
-- local Alac = require("@formats/codecs/Alac")
-- local Alac = require("@formats/codecs/audio/Alac")
-- local cfg, err = Alac.config(cookie) -- the 24-byte ALACSpecificConfig (frma / alac atoms skipped)
-- local dec = Alac.decoder(cfg)
-- local frames, err = dec:decode(buf, offset, length) -- one packet -> dec.pcm (interleaved integers, WAV order)
@@ -15,8 +15,8 @@
-- Never throws: bad data returns nil, Err (CORRUPT / TRUNCATED / UNSUPPORTED), bad arguments Err.ARG.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Decode = require("@formats/codecs/Alac/Decode")
local Encode = require("@formats/codecs/Alac/Encode")
local Decode = require("@formats/codecs/audio/Alac/Decode")
local Encode = require("@formats/codecs/audio/Alac/Encode")
local Alac = {}
@@ -1,16 +1,19 @@
--!strict
--!native
--!optimize 2
-- audio/flac/Encode: the FLAC encoder (RFC 9639). New code, written from the RFC; the presets mirror libFLAC's -0 .. -8
-- codecs/audio/Flac/Encode: the FLAC encoder (RFC 9639). New code, written from the RFC; the presets mirror libFLAC's -0 .. -8
-- (block size 1152 / 4096, max LPC order 0 / 6 / 8 / 12, Rice partition order 3 .. 6, independent / adaptive /
-- exhaustive stereo decorrelation). Subframes: CONSTANT, VERBATIM, FIXED (order 0..4, chosen by the residual sum),
-- LPC (Levinson-Durbin on the tukey(0.5)-windowed autocorrelation, error-feedback coefficient quantization with
-- 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/audio/VorbisComment")
local Frame = require("@formats/codecs/audio/Flac/Frame")
local Encode = {}
@@ -23,38 +26,17 @@ for i = 0, 63 do
end
-- ------------------------------------------------------------------------------------------------ CRCs
local CRC8 = table.create(256, 0)
local CRC16 = table.create(256, 0)
for i = 0, 255 do
local c = i
for _ = 1, 8 do
c = if c >= 128 then bit32.bxor((c * 2) % 256, 0x07) else c * 2
end
CRC8[i + 1] = c
local d = i * 256
for _ = 1, 8 do
d = if d >= 32768 then bit32.bxor((d * 2) % 65536, 0x8005) else d * 2
end
CRC16[i + 1] = d
end
-- (the decoder's tables: codecs/audio/Flac/Frame; (b, offset, count) here)
local function crc8(b: buffer, o: number, n: number): number
local c = 0
for i = o, o + n - 1 do
c = CRC8[bit32.bxor(c, buffer.readu8(b, i)) + 1]
end
return c
return Frame.crc8(b, o, o + n)
end
local function crc16(b: buffer, o: number, n: number): number
local c = 0
for i = o, o + n - 1 do
c = bit32.bxor((c * 256) % 65536, CRC16[bit32.bxor(c // 256, buffer.readu8(b, i)) + 1])
end
return c
return Frame.crc16(b, o, o + n)
end
Encode.crc8, Encode.crc16 = crc8, crc16
-- ------------------------------------------------------------------------------------------------ bit writer (MSB first)
type W = { buf: buffer, pos: number, acc: number, cnt: number }
type W = Bits.RawWriter
local function ensure(w: W, n: number)
local need = w.pos + n + 16
@@ -66,24 +48,7 @@ local function ensure(w: W, n: number)
end
end
-- put(w, v, n): the low n bits (n <= 32) of the non-negative integer v
local function put(w: W, v: number, n: number)
if n == 0 then
return
end
local acc = w.acc * POW[n + 1] + v
local cnt = w.cnt + n
local b, p = w.buf, w.pos
while cnt >= 8 do
cnt -= 8
local m = POW[cnt + 1]
local byte = floor(acc / m)
writeu8(b, p, byte)
p += 1
acc -= byte * m
end
w.acc, w.cnt, w.pos = acc, cnt, p
end
local put = Bits.msbPut
local function putSigned(w: W, v: number, n: number)
put(w, if v < 0 then v + POW[n + 1] else v, n)
@@ -702,8 +667,6 @@ export type Options = {
vendor: string,
}
local TAG_NAMES = { track = "TRACKNUMBER" }
-- encode(src, opts) -> buffer | nil, message
function Encode.encode(src: Source, opts: Options): (buffer?, string?)
local cfg = PRESETS[opts.level + 1]
@@ -730,20 +693,7 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
end
end
-- vorbis comment
local comments = {}
local keys = {}
for k in src.tags do
if type(k) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
for _, k in keys do
local v = src.tags[k]
if type(v) == "string" then
table.insert(comments, (TAG_NAMES[k] or string.upper(k)) .. "=" .. v)
end
end
local comments = VorbisComment.fields(src.tags)
local vendor = opts.vendor
local vcLen = 4 + #vendor + 4
for _, c in comments do
@@ -803,7 +753,7 @@ function Encode.encode(src: Source, opts: Options): (buffer?, string?)
local mbuf = buffer.create(bs * ch * mbytes)
local scale = POW[bps]
local maxv, minv = scale - 1, -scale
local X = table.create(ch)
local X: { { number } } = table.create(ch) :: any
for c = 1, ch do
X[c] = table.create(bs, 0)
end
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- audio/flac/Frame: FLAC frames: header parsing (CRC-8), the sync search, subframes (constant, verbatim, fixed, LPC, wasted bits),
-- codecs/audio/Flac/Frame: FLAC frames: header parsing (CRC-8), the sync search, subframes (constant, verbatim, fixed, LPC, wasted bits),
-- residuals (Rice / Rice2 partitions, escapes), stereo decorrelation and the CRC-16 check.
--
-- The input buffer must have at least PAD zero bytes after the data end (`len`): the bit reader reads 32-bit
@@ -41,6 +41,15 @@ local function crc16(b: buffer, from: number, to: number): number
end
Frame.crc16 = crc16
local function crc8(b: buffer, from: number, to: number): number
local c = 0
for i = from, to - 1 do
c = CRC8[bxor(c, readu8(b, i)) + 1]
end
return c
end
Frame.crc8 = crc8
local POW2 = table.create(64, 0)
for i = 0, 63 do
POW2[i + 1] = 2 ^ i
@@ -147,11 +156,7 @@ function Frame.header(b: buffer, pos: number, len: number, si: any): Header?
return nil
end
-- CRC-8 over the header
local c = 0
for i = pos, p - 1 do
c = CRC8[bxor(c, readu8(b, i)) + 1]
end
if c ~= readu8(b, p) then
if crc8(b, pos, p) ~= readu8(b, p) then
return nil
end
return {
+11
View File
@@ -0,0 +1,11 @@
--!strict
-- codecs/audio/Flac: FLAC frames without the container: frame header parsing, subframe decoding (constant, verbatim,
-- fixed, LPC, Rice residuals, stereo decorrelation) with CRC-8 / CRC-16 (Frame), and the frame encoder (Encode).
-- Absorbed from flac-luau 7083d0d (same author); the encoder is new. Native FLAC / Ogg FLAC streams, metadata and
-- seeking are audio/flac.
local Flac = {
Frame = require("@formats/codecs/audio/Flac/Frame"),
Encode = require("@formats/codecs/audio/Flac/Encode"),
}
return Flac
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Mdct/Fft: mixed-radix complex FFT of any size (radix 4, 2, 3, 5 butterflies, a generic odd-radix pass for
-- codecs/audio/Mdct/Fft: mixed-radix complex FFT of any size (radix 4, 2, 3, 5 butterflies, a generic odd-radix pass for
-- other primes), self-sorting Stockham passes ping-ponging between the data and a scratch array (the FFTPACK /
-- pocketfft pass structure, written from the textbook decimation-in-frequency derivation; no third-party code).
-- Data are separate real / imaginary arrays, 1-based. Never throws.
@@ -1,8 +1,8 @@
--!strict
--!native
--!optimize 2
-- codecs/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
-- complex FFT (codecs/Mdct/Fft, mixed radix: AAC 2048 / 256, Vorbis 64 .. 8192, CELT 1920 / 240 / ...), plus the
-- codecs/audio/Mdct: the MDCT / IMDCT of any window length N divisible by 4 (N / 2 coefficients), through an N / 4-point
-- complex FFT (codecs/audio/Mdct/Fft, mixed radix: AAC 2048 / 256, Vorbis 64 .. 8192, CELT 1920 / 240 / ...), plus the
-- DCT-IV, a plain FFT and the sine / KBD / Vorbis windows. Shared by AAC, Vorbis and Opus (decoders and encoders).
-- Written from the textbook definitions (MDCT = DCT-IV of the folded input; DCT-IV through a half-size complex FFT
-- with pre / post twiddles); no third-party code.
@@ -15,7 +15,7 @@
-- are Luau arrays; `xi` / `yi` are the 1-based index of element 0, coefficient arrays may be strided (CELT
-- interleaves its short blocks).
--
-- local Mdct = require("@formats/codecs/Mdct")
-- local Mdct = require("@formats/codecs/audio/Mdct")
-- local plan = Mdct.new(2048) -- nil when N is not a multiple of 4
-- Mdct.forward(plan, x, 1, X, 1) -- 2048 samples -> 1024 coefficients
-- Mdct.inverse(plan, X, 1, 1, y, 1, 2 / 2048) -- 1024 coefficients -> 2048 samples
@@ -23,7 +23,7 @@
--
-- Never throws: bad sizes return nil from new(); the transforms trust the plan and the array ranges (the caller
-- sizes them).
local Fft = require("@formats/codecs/Mdct/Fft")
local Fft = require("@formats/codecs/audio/Mdct/Fft")
local cos, sin, pi, sqrt = math.cos, math.sin, math.pi, math.sqrt
@@ -1,14 +1,14 @@
--!strict
--!native
--!optimize 2
-- audio/mp3/Analysis: the MPEG audio polyphase analysis filterbank (ISO/IEC 11172-3 section C.1.3, figure C.4): 32
-- codecs/audio/Mpa/Analysis: the MPEG audio polyphase analysis filterbank (ISO/IEC 11172-3 section C.1.3, figure C.4): 32
-- input samples -> one sample in each of the 32 subbands, with the standard's 512-tap window C = D / 32 (D from
-- audio/mp3/EncTables) and the matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64). Shared by the layer II and layer III
-- codecs/audio/Mpa/EncTables) and the matrixing M[k][i] = cos((2k + 1)(i - 16) pi / 64). Shared by the layer II and layer III
-- encoders. New code from the standard's flow chart. Never throws.
--
-- local st = Analysis.new()
-- Analysis.run(st, samples, start, out, outStart) -- samples[start .. start + 31] -> out[outStart .. outStart + 31]
local E = require("@formats/audio/mp3/EncTables")
local E = require("@formats/codecs/audio/Mpa/EncTables")
local Analysis = {}
@@ -1,12 +1,12 @@
--!strict
--!native
--!optimize 2
-- audio/mp3/Core: a line-by-line port of minimp3's mp3dec_decode_frame (https://github.com/lieff/minimp3,
-- codecs/audio/Mpa/Core: a line-by-line port of minimp3's mp3dec_decode_frame (https://github.com/lieff/minimp3,
-- CC0) for layers I, II and III, using its scalar (non-SIMD) code paths and float output.
-- State that must survive between frames (MDCT overlap, polyphase history, bit reservoir) lives in a per-stream
-- state from Core.newState(); everything else is module scratch, so decoding is synchronous and allocation free.
-- All buffer accesses stay in bounds by construction (padded scratch, bounded loops): native code must not throw.
local T = require("@formats/audio/mp3/Tables")
local T = require("@formats/codecs/audio/Mpa/Tables")
local band, bor, lshift, rshift, arshift, bswap = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.arshift, bit32.byteswap
local ru8, wu8, ru32, ri16 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.readi16
@@ -561,7 +561,8 @@ local function intensityStereo(h1: number, h3: number, gr: number)
kr = 1
end
end
kl, kr = f32(kl * s), f32(kr * s)
kl = f32(kl * s)
kr = f32(kr * s)
for k = left * 4, (left + n - 1) * 4, 4 do
local v = rf(GRBUF, k)
wf(GRBUF, k + 2304, v * kr)
@@ -1183,8 +1184,14 @@ local function synth(xl: number, dstl: number, nch: number, lins: number)
a3 += z3 * w0 - y3 * w1
vz -= 256
vy += 256
z0, z1, z2, z3 = rf(SYN, vz), rf(SYN, vz + 4), rf(SYN, vz + 8), rf(SYN, vz + 12)
y0, y1, y2, y3 = rf(SYN, vy), rf(SYN, vy + 4), rf(SYN, vy + 8), rf(SYN, vy + 12)
z0 = rf(SYN, vz)
z1 = rf(SYN, vz + 4)
z2 = rf(SYN, vz + 8)
z3 = rf(SYN, vz + 12)
y0 = rf(SYN, vy)
y1 = rf(SYN, vy + 4)
y2 = rf(SYN, vy + 8)
y3 = rf(SYN, vy + 12)
b0 += z0 * w3 + y0 * w2
b1 += z1 * w3 + y1 * w2
b2 += z2 * w3 + y2 * w2
@@ -1212,8 +1219,10 @@ local function synth(xl: number, dstl: number, nch: number, lins: number)
a2 += z2 * w0 - y2 * w1
vz -= 256
vy += 256
z0, z2 = rf(SYN, vz), rf(SYN, vz + 8)
y0, y2 = rf(SYN, vy), rf(SYN, vy + 8)
z0 = rf(SYN, vz)
z2 = rf(SYN, vz + 8)
y0 = rf(SYN, vy)
y2 = rf(SYN, vy + 8)
b0 += z0 * w3 + y0 * w2
b2 += z2 * w3 + y2 * w2
a0 += y0 * w3 - z0 * w2
@@ -1,5 +1,5 @@
--!strict
-- audio/mp3/EncTables: tables for the MPEG audio encoders, from PDMP3 (public domain / unlicense, by Krister
-- codecs/audio/Mpa/EncTables: tables for the MPEG audio encoders, from PDMP3 (public domain / unlicense, by Krister
-- Lagerstrom and contributors: licenses/PDMP3-UNLICENSE.txt), which transcribes ISO/IEC 11172-3: the synthesis window D
-- (the analysis window is C = D / 32) and the layer III Huffman code trees (the encoders derive codeword tables from
-- them). Trees use the standard's decoder layout: an entry with a high byte is a node (high byte: left offset, low
@@ -1,15 +1,16 @@
--!strict
--!native
--!optimize 2
-- audio/mp3/Encode2: an MPEG audio layer II (MP2) encoder: constant bit rate, MPEG-1 (32 / 44.1 / 48 kHz) and MPEG-2
-- codecs/audio/Mpa/Encode2: an MPEG audio layer II (MP2) encoder: constant bit rate, MPEG-1 (32 / 44.1 / 48 kHz) and MPEG-2
-- low sampling frequencies (16 / 22.05 / 24 kHz), mono or stereo. New code written from ISO/IEC 11172-3 (2.4.2.3,
-- C.1.5.2): the polyphase analysis (audio/mp3/Analysis), one scalefactor per 12-sample part (scfsi 0: all three are
-- C.1.5.2): the polyphase analysis (codecs/audio/Mpa/Analysis), one scalefactor per 12-sample part (scfsi 0: all three are
-- sent), the standard bit allocation tables (in minimp3's compact form, CC0: licenses/minimp3-CC0.txt, as the decoder
-- in this folder reads them), a greedy allocation that always gives the next step to the band with the most noise
-- (signal level minus the quantizer's SNR; no psychoacoustic model), uniform midtread quantization and grouping of
-- 3 / 5 / 9-level samples. Never throws.
local T = require("@formats/audio/mp3/Tables")
local Analysis = require("@formats/audio/mp3/Analysis")
local Bits = require("@formats/core/Bits")
local T = require("@formats/codecs/audio/Mpa/Tables")
local Analysis = require("@formats/codecs/audio/Mpa/Analysis")
local Encode2 = {}
@@ -87,24 +88,8 @@ local BITRATES_V1 = { 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
local BITRATES_V2 = { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }
Encode2.BITRATES = { [1] = BITRATES_V1, [2] = BITRATES_V2 }
type W = { buf: buffer, pos: number, acc: number, cnt: number }
local function put(w: W, v: number, n: number)
if n == 0 then
return
end
local acc = w.acc * POW[n + 1] + v
local cnt = w.cnt + n
local b, p = w.buf, w.pos
while cnt >= 8 do
cnt -= 8
local m = POW[cnt + 1]
local byte = floor(acc / m)
writeu8(b, p, byte)
p += 1
acc -= byte * m
end
w.acc, w.cnt, w.pos = acc, cnt, p
end
type W = Bits.RawWriter
local put = Bits.msbPut
export type Source = {
sampleRate: number,
@@ -375,7 +360,9 @@ function Encode2.encode(src: Source, opts: Options): (buffer?, string?)
local q = floor((x * inv + 1) * L / 2)
return if q < 0 then 0 elseif q > L - 1 then L - 1 else q
end
q0, q1, q2 = quant(sb[o + 1]), quant(sb[o + 2]), quant(sb[o + 3])
q0 = quant(sb[o + 1])
q1 = quant(sb[o + 2])
q2 = quant(sb[o + 3])
end
if ba >= 17 then
put(w, q0 + L * (q1 + L * q2), tripleBits(ba))
@@ -1,16 +1,17 @@
--!strict
--!native
--!optimize 2
-- audio/mp3/Encode3: an MPEG audio layer III encoder in the spirit of shine: constant bit rate, long blocks only,
-- codecs/audio/Mpa/Encode3: an MPEG audio layer III encoder in the spirit of shine: constant bit rate, long blocks only,
-- global-gain rate control (no psychoacoustic model, scalefactors all zero), no bit reservoir (main_data_begin = 0),
-- MPEG-1 (32 / 44.1 / 48 kHz, two granules), MPEG-2 (16 / 22.05 / 24 kHz) and MPEG-2.5 (8 / 11.025 / 12 kHz), mono,
-- stereo or joint (mid / side) stereo. New code written from ISO/IEC 11172-3 / 13818-3 (no shine / LAME code): the
-- analysis filterbank (audio/mp3/Analysis), the 36-point MDCT with the sine window, the alias-reduction butterflies,
-- analysis filterbank (codecs/audio/Mpa/Analysis), the 36-point MDCT with the sine window, the alias-reduction butterflies,
-- the x^(3/4) quantizer, big_values / count1 partitioning with per-region Huffman table choice; the Huffman codes are
-- derived from the standard's decoder trees (audio/mp3/EncTables, from PDMP3, public domain). Never throws.
local E = require("@formats/audio/mp3/EncTables")
local T = require("@formats/audio/mp3/Tables")
local Analysis = require("@formats/audio/mp3/Analysis")
-- derived from the standard's decoder trees (codecs/audio/Mpa/EncTables, from PDMP3, public domain). Never throws.
local Bits = require("@formats/core/Bits")
local E = require("@formats/codecs/audio/Mpa/EncTables")
local T = require("@formats/codecs/audio/Mpa/Tables")
local Analysis = require("@formats/codecs/audio/Mpa/Analysis")
local Encode3 = {}
@@ -87,25 +88,9 @@ for m = 0, 15 do
end
-- ------------------------------------------------------------------------------------------------ bit writer
type W = { buf: buffer, pos: number, acc: number, cnt: number }
type W = Bits.RawWriter
local function put(w: W, v: number, n: number)
if n == 0 then
return
end
local acc = w.acc * POW[n + 1] + v
local cnt = w.cnt + n
local b, p = w.buf, w.pos
while cnt >= 8 do
cnt -= 8
local m = POW[cnt + 1]
local byte = floor(acc / m)
writeu8(b, p, byte)
p += 1
acc -= byte * m
end
w.acc, w.cnt, w.pos = acc, cnt, p
end
local put = Bits.msbPut
Encode3.put = put
-- ------------------------------------------------------------------------------------------------ constants
@@ -1,10 +1,10 @@
--!strict
--!native
--!optimize 2
-- audio/mp3/Header: MPEG audio frame headers (minimp3's hdr_* macros and functions), frame sync (mp3d_find_frame /
-- codecs/audio/Mpa/Header: MPEG audio frame headers (minimp3's hdr_* macros and functions), frame sync (mp3d_find_frame /
-- mp3d_match_frame). Every function reads 4 header bytes at a byte offset of a buffer; callers keep offset + 4
-- inside the buffer. Never throws.
local T = require("@formats/audio/mp3/Tables")
local T = require("@formats/codecs/audio/Mpa/Tables")
local band, bxor, rshift = bit32.band, bit32.bxor, bit32.rshift
local ru8 = buffer.readu8
@@ -1,5 +1,5 @@
--!strict
-- audio/mp3/Tables: constant tables of minimp3 (https://github.com/lieff/minimp3, CC0), generated by tools/gen_tables.py.
-- codecs/audio/Mpa/Tables: constant tables of minimp3 (https://github.com/lieff/minimp3, CC0), generated by tools/gen_tables.py.
-- Every list is flattened row-major and 0-based (t[0] is the first element), like the C arrays.
local T = {}
T.halfrate = { [0] = 0,
+13
View File
@@ -0,0 +1,13 @@
--!strict
-- codecs/audio/Mpa: MPEG audio layers I / II / III (ISO/IEC 11172-3, 13818-3, MPEG-2.5) without the file around it:
-- frame headers (Header), the decoder core (Core: a port of minimp3 by lieff, CC0: licenses/minimp3-CC0.txt,
-- absorbed from mp3-luau c755bbf) with its tables, and the layer III / layer II encoders (Encode3, Encode2: shine-style
-- CBR, new) with their analysis tables. ID3 tags, Xing / LAME gapless info, the frame index and seeking are audio/mp3.
local Mpa = {
Header = require("@formats/codecs/audio/Mpa/Header"),
Core = require("@formats/codecs/audio/Mpa/Core"),
Encode3 = require("@formats/codecs/audio/Mpa/Encode3"),
Encode2 = require("@formats/codecs/audio/Mpa/Encode2"),
}
return Mpa
@@ -1,15 +1,15 @@
--!strict
--!native
--!optimize 2
-- audio/opus/Celt: CELT decoder (RFC 6716 section 4.3), a port of the libopus float decoder: celt/celt_decoder.c, bands.c, vq.c,
-- codecs/audio/Opus/Celt: CELT decoder (RFC 6716 section 4.3), a port of the libopus float decoder: celt/celt_decoder.c, bands.c, vq.c,
-- cwrs.c, rate.c, quant_bands.c, laplace.c, celt.c (comb filter). Only the standard 48 kHz / 960-sample mode is
-- needed by Opus. Packet loss concealment is the noise-based variant only (no pitch PLC).
--
-- 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/audio/opus/RangeDecoder")
local Mdct = require("@formats/audio/opus/Mdct")
local T = require("@formats/audio/opus/CeltTables")
local RD = require("@formats/codecs/entropy/RangeCoder/Decoder")
local Mdct = require("@formats/codecs/audio/Opus/Mdct")
local T = require("@formats/codecs/audio/Opus/CeltTables")
local Celt = {}
@@ -1,15 +1,15 @@
--!strict
--!native
--!optimize 2
-- audio/opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms frames (LM 3), full band, constant
-- codecs/audio/Opus/CeltEncoder: a fixed-frame CELT encoder (RFC 6716 section 5.3): 20 ms frames (LM 3), full band, constant
-- 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 codecs/audio/Opus/Celt's decoder step for step; the analysis is simplified. The MDCT is codecs/audio/Mdct.
-- Never throws.
local RE = require("@formats/audio/opus/RangeEncoder")
local T = require("@formats/audio/opus/CeltTables")
local Mdct = require("@formats/codecs/Mdct")
local RE = require("@formats/codecs/entropy/RangeCoder/Encoder")
local T = require("@formats/codecs/audio/Opus/CeltTables")
local Mdct = require("@formats/codecs/audio/Mdct")
local CeltEncoder = {}
@@ -74,7 +74,7 @@ for i = 0, OVERLAP - 1 do
WINDOW[i + 1] = math.sin(0.5 * math.pi * s * s)
end
local PLAN = Mdct.new(2 * N) :: Mdct.Plan
-- forward scale matching the decoder's backward MDCT (calibrated against audio/opus/Mdct: tests/audio/opus_encode)
-- forward scale matching the decoder's backward MDCT (calibrated against codecs/audio/Opus/Mdct: tests/audio/opus_encode)
local MDCT_SCALE = 2 / N
-- PVQ codebook sizes U(n, k), flat: U[n * UK + k + 1]
@@ -1,5 +1,5 @@
--!strict
-- audio/opus/CeltTables: Generated from libopus celt/static_modes_float.h and celt/quant_bands.c (BSD, see licenses/). 1-based arrays.
-- codecs/audio/Opus/CeltTables: Generated from libopus celt/static_modes_float.h and celt/quant_bands.c (BSD, see licenses/). 1-based arrays.
return {
logN400 = {
0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36,
@@ -1,13 +1,13 @@
--!strict
--!native
--!optimize 2
-- audio/opus/Decoder: The Opus decoder proper (libopus src/opus_decoder.c and opus_multistream_decoder.c): per-frame mode switching
-- codecs/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/audio/opus/RangeDecoder")
local Packet = require("@formats/audio/opus/Packet")
local Celt = require("@formats/audio/opus/Celt")
local Silk = require("@formats/audio/opus/Silk")
local RD = require("@formats/codecs/entropy/RangeCoder/Decoder")
local Packet = require("@formats/codecs/audio/Opus/Packet")
local Celt = require("@formats/codecs/audio/Opus/Celt")
local Silk = require("@formats/codecs/audio/Opus/Silk")
local Decoder = {}
@@ -1,9 +1,13 @@
--!strict
--!native
--!optimize 2
-- audio/opus/Mdct: CELT inverse MDCT (libopus celt/mdct.c clt_mdct_backward) over a mixed-radix complex FFT (a port of the
-- codecs/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/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.
local Mdct = {}
local sin, cos, pi = math.sin, math.cos, math.pi
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- audio/opus/Packet: Opus packet framing (RFC 6716 section 3): the TOC byte and frame packing codes 0-3, with padding.
-- codecs/audio/Opus/Packet: Opus packet framing (RFC 6716 section 3): the TOC byte and frame packing codes 0-3, with padding.
local Packet = {}
local readu8 = buffer.readu8
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- audio/opus/Silk: SILK decoder: a bit-exact port of the libopus fixed-point SILK decoder (silk/dec_API.c and what it calls:
-- codecs/audio/Opus/Silk: SILK decoder: a bit-exact port of the libopus fixed-point SILK decoder (silk/dec_API.c and what it calls:
-- decode_frame, decode_indices, decode_pulses, shell_coder, code_signs, decode_parameters, gain_quant, NLSF_*,
-- LPC_fit, LPC_inv_pred_gain, decode_core, stereo_*, CNG, PLC, resampler_private_up2_HQ / IIR_FIR). BSD, see
-- licenses/.
@@ -14,8 +14,8 @@
--
-- 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/audio/opus/RangeDecoder")
local T = require("@formats/audio/opus/SilkTables")
local RD = require("@formats/codecs/entropy/RangeCoder/Decoder")
local T = require("@formats/codecs/audio/Opus/SilkTables")
local icdf = RD.icdf
local bitLogp = RD.bitLogp
@@ -1,6 +1,6 @@
--!strict
--!optimize 2
-- audio/opus/SilkTables: SILK decoder tables (generated from libopus silk/tables_*.c, pitch_est_tables.c, resampler_rom.c; BSD, see
-- codecs/audio/Opus/SilkTables: SILK decoder tables (generated from libopus silk/tables_*.c, pitch_est_tables.c, resampler_rom.c; BSD, see
-- licenses/). Multi-dimensional C arrays are flattened row-major; every array is 1-based.
local T = {}
T.LTP_per_index_iCDF = {
+15
View File
@@ -0,0 +1,15 @@
--!strict
-- codecs/audio/Opus: the Opus codec (RFC 6716) without its container: TOC / packet framing (Packet), the SILK and CELT
-- decoders and the multistream / hybrid decoder that drives them (Decoder), the CELT encoder (CeltEncoder) and the
-- CELT inverse MDCT (Mdct, a fused libopus port: see its header for why it is not codecs/audio/Mdct). A port of the
-- libopus 1.6 decoder (BSD: licenses/libopus-BSD.txt), absorbed from opus-luau dd2b4e5; the encoder is new. Ogg Opus
-- (OpusHead, OpusTags, granules, seeking) is audio/opus.
local Opus = {
Packet = require("@formats/codecs/audio/Opus/Packet"),
Decoder = require("@formats/codecs/audio/Opus/Decoder"),
Celt = require("@formats/codecs/audio/Opus/Celt"),
Silk = require("@formats/codecs/audio/Opus/Silk"),
CeltEncoder = require("@formats/codecs/audio/Opus/CeltEncoder"),
}
return Opus
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/Pcm). Integers map to
-- codecs/audio/Pcm/Convert: raw sample formats <-> interleaved f32 (the hot loops of codecs/audio/Pcm). Integers map to
-- v / 2^(bits-1) (as ffmpeg does); encoding rounds to nearest and clips. G.711 A-law / mu-law per ITU-T G.711 (the
-- classic Sun g711.c algorithm, written from the spec).
--
@@ -1,5 +1,5 @@
--!strict
-- codecs/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
-- codecs/audio/Pcm: PCM plumbing shared by audio formats: raw sample formats, streaming Decoders, encoder input sources.
-- An encoder accepts a Types.Audio (fully decoded) or a Types.Decoder (streamed); Pcm.source turns either into one
-- pull interface, so encoders stream in blocks without caring which they got. Uncompressed containers (aiff, au,
-- voc, ...) get their Decoder from Pcm.rawDecoder (over a sample region of the file) or Pcm.audioDecoder.
@@ -10,7 +10,7 @@
-- local dec = Pcm.rawDecoder(buf, offset, frames, channels, rate, "s16be", tags?) -- a Types.Decoder
-- local dec = Pcm.audioDecoder(audio) -- a Types.Decoder over a decoded Audio
-- local raw = Pcm.encode(src, "s24le", writer) -- every frame of src appended to a core/Bytes Writer
-- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/Pcm/Convert)
-- Pcm.Convert.decode / encode / SIZE / BITS -- the raw sample loops (codecs/audio/Pcm/Convert)
-- local s16 = Pcm.toInt(x, 16) -- round, clip to [-32768, 32767]
-- local x = Pcm.fromInt(s16, 16) -- s / 32768
--
@@ -19,11 +19,25 @@
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
-- Channel order. Decoders return WAVE (WAVEFORMATEXTENSIBLE) order: FL FR C LFE BL BR (SL SR) ..., as FLAC, WAV and
-- AAC store it. Vorbis and Opus (mapping family 1) store the Vorbis order (FL C FR ... LFE last); WAVE_FROM_VORBIS[n][i]
-- is the Vorbis-order channel (1-based) that WAVE-order channel i holds, for n = 1 .. 8 channels.
Pcm.WAVE_FROM_VORBIS = {
{ 1 },
{ 1, 2 },
{ 1, 3, 2 }, -- L C R -> L R C
{ 1, 2, 3, 4 }, -- FL FR RL RR
{ 1, 3, 2, 4, 5 }, -- FL C FR RL RR -> FL FR C RL RR
{ 1, 3, 2, 6, 4, 5 }, -- FL C FR RL RR LFE -> FL FR C LFE RL RR
{ 1, 3, 2, 7, 6, 4, 5 }, -- FL C FR SL SR RC LFE -> FL FR C LFE RC SL SR
{ 1, 3, 2, 8, 6, 7, 4, 5 }, -- FL C FR SL SR RL RR LFE -> FL FR C LFE RL RR SL SR
}
export type Source = {
sampleRate: number,
channels: number,
@@ -103,6 +117,16 @@ function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?)
local total = 0
local limit = maxFrames or 2 ^ 31
local tmp: buffer? = nil
-- a known length: one read straight into the result (decoders write into a big enough out buffer: no copy)
if src.frames > 0 and src.frames <= limit then
local b, n = src:read(src.frames, data)
if n > 0 then
if b ~= data then
buffer.copy(data, 0, b, 0, math.min(n, cap) * ch * 4)
end
total = math.min(n, cap)
end
end
while true do
local b, n = src:read(16384, tmp)
if n <= 0 then
@@ -136,6 +160,26 @@ function Pcm.collect(src: Source, maxFrames: number?): (Types.Audio?, Err.Err?)
return a, nil
end
-- drain(dec, source?, maxFrames?) -> Types.Audio | nil, Err: a format's decode() through its open(): every frame of
-- the Decoder (dec.frames is only a hint: short or long streams keep what decodes), dec.tags, meta.source = source
-- (default dec.source). A decoder that recorded a failure in dec.error (an Err) fails the drain.
function Pcm.drain(dec: any, source: { [string]: any }?, maxFrames: number?): (Types.Audio?, Err.Err?)
local src, err = Pcm.source(dec)
if not src then
return nil, err
end
local a, cerr = Pcm.collect(src, maxFrames)
if not a then
return nil, cerr
end
if Err.is(dec.error) then
return nil, dec.error
end
a.tags = dec.tags or {}
a.meta.source = source or dec.source
return a, nil
end
-- ------------------------------------------------------------------------------------------------ decoders
-- rawDecoder(buf, offset, frames, channels, sampleRate, fmt, tags?) -> Types.Decoder | nil, Err.ARG: a streaming
-- decoder over frames * channels samples of fmt at buf[offset] (the caller has checked the range is inside buf)
@@ -211,6 +255,22 @@ function Pcm.encode(src: Source, fmt: string, w: Bytes.Writer): (number?, Err.Er
end
-- ------------------------------------------------------------------------------------------------ conversions
-- reorder(buf, offset, frames, channels, map): in place, frame by frame, channel i of the result = channel map[i]
-- (1-based) of the input; for converting between channel orders (Pcm.WAVE_FROM_VORBIS)
function Pcm.reorder(buf: buffer, offset: number, frames: number, channels: number, map: { number })
local tmp = table.create(channels, 0)
local readf32, writef32 = buffer.readf32, buffer.writef32
for f = 0, frames - 1 do
local p = offset + f * channels * 4
for c = 1, channels do
tmp[c] = readf32(buf, p + (map[c] - 1) * 4)
end
for c = 1, channels do
writef32(buf, p + (c - 1) * 4, tmp[c])
end
end
end
-- toInt(x, bits) -> the nearest bits-wide signed integer to x * 2^(bits-1), clipped (NaN -> 0)
function Pcm.toInt(x: number, bits: number): number
local s = 2 ^ (bits - 1)
+377
View File
@@ -0,0 +1,377 @@
--!strict
--!native
--!optimize 2
-- 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).
--
-- The filter is a polyphase table: exact phases when to / gcd(from, to) <= 4096 (44100 <-> 48000: 160 phases),
-- else 4096 phases with linear interpolation between them. Each phase is normalised to unit DC gain. The cutoff is a
-- fraction (opts.cutoff, default 0.97) of the lower Nyquist frequency; quality picks the taps per side at the cutoff:
--
-- quality zero crossings per side Kaiser beta stop band
-- "low" 8 6 ~ -60 dB
-- "medium" 16 (default) 8 ~ -80 dB
-- "high" 32 10 ~ -100 dB
--
-- Output frame j sits at input time j * from / to (no delay: the filter is centred, the input is zero outside its
-- range); a stream of n input frames gives floor(n * to / from + 0.5) output frames.
--
-- local out, frames = Resample.buffer(samples, frames, channels, 44100, 48000, { quality = "high" })
-- 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/audio/Pcm Source at the new rate
--
-- Never throws: bad arguments return nil, message (the api turns them into Err.ARG).
local Resample = {}
export type Options = {
quality: ("low" | "medium" | "high")?, -- default "medium"
cutoff: number?, -- pass band edge as a fraction of the lower Nyquist frequency, 0.5 .. 1 (default 0.97)
}
export type Resampler = {
from: number,
to: number,
channels: number,
-- process(src, frames, out?) -> interleaved f32 buffer, output frames (out is reused when big enough)
process: (self: Resampler, src: buffer, frames: number, out: buffer?) -> (buffer, number),
-- flush(out?) -> the remaining output frames; the resampler is finished afterwards
flush: (self: Resampler, out: buffer?) -> (buffer, number),
}
local QUALITY = { low = { 8, 6 }, medium = { 16, 8 }, high = { 32, 10 } }
local MAX_EXACT = 4096
local INTERP_PHASES = 4096
local floor, sin, pi, sqrt, max, min = math.floor, math.sin, math.pi, math.sqrt, math.max, math.min
local readf32, writef32 = buffer.readf32, buffer.writef32
local function besselI0(x: number): number
local sum, term = 1, 1
for k = 1, 80 do
term *= (x / (2 * k)) ^ 2
sum += term
if term < sum * 1e-16 then
break
end
end
return sum
end
local function gcd(a: number, b: number): number
while b ~= 0 do
a, b = b, a % b
end
return a
end
type Filter = {
taps: number, -- per phase
half: number, -- taps on the left of the centre (taps = 2 * half)
phases: number,
exact: boolean,
h: { number }, -- phase p, tap k: h[p * taps + k + 1]
}
-- filter(ratio, phases, exact, opts) -> the polyphase table. Phase p is the kernel for an output at fraction
-- p / phases past an input sample; tap k multiplies input (floor(t) - half + 1 + k).
local function makeFilter(ratio: number, phases: number, exact: boolean, zc: number, beta: number, cut: number): Filter
local cutoff = cut * min(1, ratio)
local width = zc / cutoff -- in input samples, each side
local half = math.ceil(width)
local taps = 2 * half
local i0b = besselI0(beta)
local n = if exact then phases else phases + 1
local h = table.create(n * taps, 0)
for p = 0, n - 1 do
local frac = p / phases
local sum = 0
local base = p * taps
for k = 0, taps - 1 do
local d = (k - half + 1) - frac -- input position minus output position
local r = d / width
local v = 0
if r > -1 and r < 1 then
local x = d * cutoff
local s = if x == 0 then 1 else sin(pi * x) / (pi * x)
v = s * besselI0(beta * sqrt(1 - r * r)) / i0b
end
h[base + k + 1] = v
sum += v
end
if sum ~= 0 then
for k = 1, taps do
h[base + k] /= sum
end
end
end
return { taps = taps, half = half, phases = phases, exact = exact, h = h }
end
-- the stream state: the input history as an interleaved Lua array; hist[1] is frame `base` (absolute)
type State = {
from: number,
to: number,
channels: number,
f: Filter,
step: number, -- M = from / g: the input advance per output frame, in units of 1 / L
L: number, -- to / g
hist: { number },
histFrames: number,
base: number, -- the absolute input frame of hist[1]
inFrames: number, -- absolute input frames received
outPos: number, -- next output frame (absolute)
done: boolean,
process: any,
flush: any,
}
-- run(st, lastInput) -> buffer, frames: every output frame whose taps end at or before lastInput (absolute, exclusive)
local function run(st: State, limitOut: number, out: buffer?): (buffer, number)
local f = st.f
local taps, half, h = f.taps, f.half, f.h
local ch = st.channels
local hist, base, histFrames = st.hist, st.base, st.histFrames
local L, M = st.L, st.step
local j0 = st.outPos
-- outputs j with floor(j * M / L) - half + taps <= available frames (zero beyond the end after flush)
local avail = base + histFrames
local jmax = limitOut
if not st.done then
-- the last tap must be buffered: floor(j * M / L) + half <= avail - 1, i.e. j * M < (avail - half) * L
local lim = floor(((avail - half) * L - 1) / M)
if lim + 1 < jmax then
jmax = lim + 1
end
end
local n = jmax - j0
if n <= 0 then
return out or buffer.create(0), 0
end
local bytes = n * ch * 4
local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes)
local exact = f.exact
local phases = f.phases
local o = 0
for j = j0, jmax - 1 do
local num = j * M
local ip = num // L -- floor(t)
local first = ip - half + 1 -- absolute input frame of tap 0
local rel = first - base -- frame index in hist
local kLo = if rel < 0 then -rel else 0
local kHi = taps - 1
if rel + kHi >= histFrames then
kHi = histFrames - 1 - rel
end
if exact then
local hb = (num - ip * L) * taps + 1 -- phase * taps + 1
for c = 0, ch - 1 do
local acc = 0
local hi = (rel + kLo) * ch + c + 1
for k = kLo, kHi do
acc += hist[hi] * h[hb + k]
hi += ch
end
writef32(b, o, acc)
o += 4
end
else
local fp = (num - ip * L) / L * phases
local p = floor(fp)
local a = fp - p
local hb = p * taps + 1
local hb2 = hb + taps
for c = 0, ch - 1 do
local acc, acc2 = 0, 0
local hi = (rel + kLo) * ch + c + 1
for k = kLo, kHi do
local x = hist[hi]
acc += x * h[hb + k]
acc2 += x * h[hb2 + k]
hi += ch
end
writef32(b, o, acc + (acc2 - acc) * a)
o += 4
end
end
end
st.outPos = jmax
-- drop history no future output needs (keep from the next output's first tap)
local keepFrom = (jmax * M) // L - half + 1
local drop = keepFrom - base
if drop > 0 then
if drop >= histFrames then
st.hist = {}
st.histFrames = 0
st.base = base + histFrames
else
local nh: { number } = table.create((histFrames - drop) * ch) :: any
table.move(hist, drop * ch + 1, histFrames * ch, 1, nh)
st.hist = nh
st.histFrames = histFrames - drop
st.base = base + drop
end
end
return b, n
end
local function process(self: State, src: buffer, frames: number, out: buffer?): (buffer, number)
if self.done or type(src) ~= "buffer" or type(frames) ~= "number" or frames <= 0 then
return out or buffer.create(0), 0
end
local ch = self.channels
frames = min(floor(frames), buffer.len(src) // (ch * 4))
local hist = self.hist
local p = self.histFrames * ch
for i = 0, frames * ch - 1 do
hist[p + i + 1] = readf32(src, i * 4)
end
self.histFrames += frames
self.inFrames += frames
return run(self, math.huge, out)
end
local function flush(self: State, out: buffer?): (buffer, number)
if self.done then
return out or buffer.create(0), 0
end
self.done = true
local total = floor(self.inFrames * self.to / self.from + 0.5)
return run(self, total, out)
end
-- new(from, to, channels, opts?) -> Resampler | nil, message
function Resample.new(from: number, to: number, channels: number, opts: Options?): (Resampler?, string?)
if type(from) ~= "number" or type(to) ~= "number" or from ~= from or to ~= to or from <= 0 or to <= 0 or from > 2 ^ 24 or to > 2 ^ 24 then
return nil, "bad sample rates"
end
if type(channels) ~= "number" or channels < 1 or channels > 256 or channels ~= floor(channels) then
return nil, "bad channel count"
end
local q: { number }? = QUALITY[(opts and opts.quality) or "medium"]
if not q then
return nil, "quality must be low, medium or high"
end
local cut = (opts and opts.cutoff) or 0.97
if type(cut) ~= "number" or not (cut >= 0.5 and cut <= 1) then
return nil, "cutoff must be 0.5 .. 1"
end
-- positions are exact integers: output j sits at input j * M / L (non-integer rates: to 1 / 1000 Hz)
local scale = if from ~= floor(from) or to ~= floor(to) then 1000 else 1
local fi: number = floor(from * scale + 0.5)
local ti: number = floor(to * scale + 0.5)
local g: number = gcd(fi, ti)
local L: number, M: number = ti // g, fi // g
local exact = L <= MAX_EXACT
local phases = if exact then L else INTERP_PHASES
local st: State = {
from = from,
to = to,
channels = channels,
-- the same rate: a pass-through (tap 0 is the input frame itself)
f = if L == 1 and M == 1 then { taps = 2, half = 1, phases = 1, exact = true, h = { 1, 0 } } else makeFilter(to / from, phases, exact, q[1], q[2], cut),
step = M,
L = L,
hist = {},
histFrames = 0,
base = 0,
inFrames = 0,
outPos = 0,
done = false,
process = process,
flush = flush,
}
return st :: any, nil
end
-- buffer(src, frames, channels, from, to, opts?) -> interleaved f32 buffer, frames | nil, message
function Resample.buffer(src: buffer, frames: number, channels: number, from: number, to: number, opts: Options?): (buffer?, number | string)
local rs, err = Resample.new(from, to, channels, opts)
if not rs then
return nil, err :: string
end
if type(src) ~= "buffer" or type(frames) ~= "number" or frames < 0 or buffer.len(src) < frames * channels * 4 then
return nil, "the buffer is shorter than frames * channels * 4"
end
local total = floor(frames * to / from + 0.5)
local out = buffer.create(total * channels * 4)
local got = 0
local chunk = 65536
local tmp: buffer? = nil
local pos = 0
while pos < frames do
local n = min(chunk, frames - pos)
local part = buffer.create(n * channels * 4)
buffer.copy(part, 0, src, pos * channels * 4, n * channels * 4)
local b, m = rs:process(part, n, tmp)
tmp = b
if m > 0 then
buffer.copy(out, got * channels * 4, b, 0, m * channels * 4)
got += m
end
pos += n
end
local b, m = rs:flush(tmp)
if m > 0 then
buffer.copy(out, got * channels * 4, b, 0, m * channels * 4)
got += m
end
return out, got
end
-- 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
return nil, "needs a source"
end
local rs, err = Resample.new(src.sampleRate, to, src.channels, opts)
if not rs then
return nil, err
end
local ch = src.channels
local pending = buffer.create(0) -- produced but not yet returned
local pendingFrames, pendingPos = 0, 0
local ended = false
local out = {
sampleRate = to,
channels = ch,
frames = if src.frames > 0 then floor(src.frames * to / src.sampleRate + 0.5) else 0,
tags = src.tags,
err = nil :: any,
}
local inTmp: buffer? = nil
function out.read(self: any, n: number, dst: buffer?): (buffer, number)
n = floor(n)
while pendingFrames - pendingPos <= 0 and not ended do
local b: buffer, m: number = (src :: any):read(math.max(1024, floor(n * src.sampleRate / to) + 64), inTmp)
inTmp = b
local r: buffer, k: number
if m <= 0 then
ended = true
self.err = src.err
r, k = rs:flush()
else
r, k = rs:process(b, m)
end
if k > 0 then
pending, pendingFrames, pendingPos = r, k, 0
end
end
local k = min(n, pendingFrames - pendingPos)
if k <= 0 then
return dst or buffer.create(0), 0
end
local bytes = k * ch * 4
local b = if dst and buffer.len(dst) >= bytes then dst else buffer.create(bytes)
buffer.copy(b, 0, pending, pendingPos * ch * 4, bytes)
pendingPos += k
return b, k
end
return out, nil
end
return Resample
@@ -1,11 +1,11 @@
--!strict
-- codecs/SoundFont/Fallback: the built-in General MIDI set used when no SoundFont is given. A generated SoundFont
-- codecs/audio/SoundFont/Fallback: the built-in General MIDI set used when no SoundFont is given. A generated SoundFont
-- (the same shape Parse returns, so the same synth plays it): single-cycle sine / triangle / square / saw waves and a
-- looped noise sample, one preset per GM family of 8 programs (piano, chromatic percussion, organ, guitar, bass,
-- strings, ensemble, brass, reed, pipe, lead, pad, synth fx, ethnic, percussive, sound fx) with family envelopes,
-- filters and vibrato, plus a drum kit on bank 128 (pitch-swept sine kicks and toms, filtered noise snares, hats with
-- an exclusive class, cymbals). Written for this library (no third-party code).
local Parse = require("@formats/codecs/SoundFont/Parse")
local Parse = require("@formats/codecs/audio/SoundFont/Parse")
local Fallback = {}
@@ -1,5 +1,5 @@
--!strict
-- codecs/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader. The INFO list, the sdta samples (smpl 16-bit, + sm24
-- codecs/audio/SoundFont/Parse: SoundFont 2.0x (sfbk RIFF) reader. The INFO list, the sdta samples (smpl 16-bit, + sm24
-- when present) as one f32 buffer, and the pdta "hydra" (phdr pbag pmod pgen inst ibag imod igen shdr), flattened
-- into playable regions per preset: the instrument global zone, the preset global zone and the preset zone's
-- generators merged the way TinySoundFont (tsf.h v0.9, MIT, (c) Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt)
@@ -296,7 +296,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?)
if layout and not hydra[sid] then
local rs = RECSIZE[sid]
local n = sub:remaining() // rs
local recs: { { number } } = table.create(n)
local recs = table.create(n) :: { { number } }
for i = 1, n do
local rec = {}
for _, w in layout do
@@ -487,7 +487,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?)
for _, p in presets do
(p :: any)._order = nil
end
local headers: { { [string]: any } } = table.create(nShdr)
local headers = table.create(nShdr) :: { { [string]: any } }
for i = 1, nShdr do
local sh = shdr[i]
headers[i] = {
@@ -503,7 +503,7 @@ function Parse.parse(r: Bytes.Reader, opts: Options?): (SoundFont?, Err.Err?)
type = sh[10],
}
end
local instruments: { { name: string, zones: number } } = table.create(nInst)
local instruments = table.create(nInst) :: { { name: string, zones: number } }
for i = 1, nInst do
instruments[i] = { name = instNames[i], zones = math.max(0, (inst[i + 1][2] or 0) - inst[i][2]) }
end
@@ -1,6 +1,6 @@
--!strict
--!native
-- codecs/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. A port of TinySoundFont (tsf.h v0.9,
-- codecs/audio/SoundFont/Synth: a SoundFont 2 sample synthesizer with MIDI channels. A port of TinySoundFont (tsf.h v0.9,
-- MIT, (c) 2017-2025 Bernhard Schelling, based on SFZero (c) 2012 Steve Folta; licenses/TinySoundFont-LICENSE.txt):
-- voices with the DAHDSR volume envelope (exponential decay / release), the modulation envelope to pitch and filter
-- cutoff, the modulation and vibrato LFOs (triangle) to pitch / filter / volume, a resonant biquad low-pass, linear
@@ -1,11 +1,11 @@
--!strict
-- codecs/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by
-- codecs/audio/SoundFont: SoundFont 2 banks and the sample synth that plays MIDI through them. A codec (layer 1) shared by
-- music/sf2 (the file format) and music/midi (rendering). The synth is a port of TinySoundFont (tsf.h v0.9, MIT,
-- (c) 2017-2025 Bernhard Schelling; licenses/TinySoundFont-LICENSE.txt); see Parse / Synth for what is covered.
-- Without a bank, fallback() is a generated General MIDI set of simple waveforms (sine / triangle / square / saw /
-- noise) with a drum kit.
--
-- local SoundFont = require("@formats/codecs/SoundFont")
-- local SoundFont = require("@formats/codecs/audio/SoundFont")
-- local sf, err = SoundFont.parse(buf) -- buffer | string | core/Bytes Reader -> SoundFont | nil, Err
-- local sf = SoundFont.fallback() -- the built-in waveform set
-- local s = SoundFont.synth(sf, 44100, { gain = 0.5 }) -- a synth State; SoundFont.Synth.midi(s, 0x90, 60, 100)
@@ -14,9 +14,9 @@
-- Never throws: bad data returns nil, Err.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Parse = require("@formats/codecs/SoundFont/Parse")
local Synth = require("@formats/codecs/SoundFont/Synth")
local Fallback = require("@formats/codecs/SoundFont/Fallback")
local Parse = require("@formats/codecs/audio/SoundFont/Parse")
local Synth = require("@formats/codecs/audio/SoundFont/Synth")
local Fallback = require("@formats/codecs/audio/SoundFont/Fallback")
local SoundFont = {}
+141
View File
@@ -0,0 +1,141 @@
--!strict
-- codecs/audio/Stream: the streaming Decoder (Types.Decoder: read / seek / position) over a packetised codec, the part
-- every packet-based audio format repeated: decode packets in order into a pending float block, return frames in
-- read()-sized pieces, drop the encoder priming at the start and the padding at the end (gapless), and seek by
-- finding the packet holding the target (with codec pre-roll) and dropping up to it. AAC (ADTS), CAF and M4A use it;
-- formats with their own seeking (Opus granule bisection, FLAC, MP3, Vorbis) keep their streams. New in formats-luau
-- (the loop the three formats carried).
--
-- local dec, err = Stream.packets(dec, { -- dec: the Decoder table with its fields (sampleRate, channels,
-- count = n, -- frames, duration, bitrate, tags, ...); read / seek / position
-- start = function(i) return ... end, -- are added. start(i): packet i's first frame (absolute, before
-- decode = function(i) return n, err end,-- trimming); decode(i) -> frames | nil, Err, the samples in pcm()
-- pcm = function() return floats end, -- (interleaved, 1-based) until the next decode
-- reset = function() end, -- forget codec state (before a seek)
-- skip = priming, stop = lastFrame, -- output = absolute frames [skip, stop)
-- preroll = 1, -- packets decoded before the one holding a seek target (AAC: 1)
-- })
--
-- A decode failure ends the stream and is kept in dec.error (Pcm.drain reports it); a failing first packet is
-- returned by packets() as the open error. Never throws.
local Err = require("@formats/core/Err")
local Stream = {}
export type Spec = {
count: number,
start: (i: number) -> number,
decode: (i: number) -> (number?, Err.Err?),
pcm: () -> { number },
reset: () -> (),
skip: number?, -- default 0
stop: number?, -- default start(count + 1)
preroll: number?, -- default 0
cumulative: boolean?, -- frames after a packet = frames before + its output (default: start(i) + its output)
}
-- packets(dec, spec) -> dec (with read / seek / position) | nil, Err (the first packet failed)
function Stream.packets(dec: any, spec: Spec): (any, Err.Err?)
local sr, ch = dec.sampleRate, dec.channels
local count = spec.count
local skip = spec.skip or 0
local stopAt = spec.stop or spec.start(count + 1)
local frames = math.max(0, stopAt - skip)
local preroll = spec.preroll or 0
local decodeP, pcmOf, startOf = spec.decode, spec.pcm, spec.start
local nextPacket = 1
local decoded = 0 -- absolute frame after the packets decoded so far
local pendPos, pendN = 0, 0
local dropUntil = skip
local pos = 0
local failed: Err.Err? = nil
dec.error = nil
local function fill(): boolean
while true do
if nextPacket > count or decoded >= stopAt then
return false
end
local i = nextPacket
nextPacket += 1
local first = if spec.cumulative then decoded else startOf(i)
local n, e = decodeP(i)
if not n then
failed = e or Err.new(Err.CORRUPT, "packet " .. i .. " failed")
dec.error = failed
return false
end
decoded = first + n
local a = math.max(first, dropUntil)
local b = math.min(decoded, stopAt)
if b > a then
pendPos, pendN = a - first, b - first
return true
end
end
end
function dec.read(_self: any, n: number, out: buffer?): (buffer, number)
local want = math.max(0, math.floor(n))
local need = want * ch * 4
local ob = if out and buffer.len(out) >= need then out else buffer.create(need)
local got = 0
local writef32 = buffer.writef32
while got < want do
if pendPos >= pendN then
if failed or not fill() then
break
end
end
local take = math.min(want - got, pendN - pendPos)
local src = pcmOf()
local q = got * ch * 4
local s = pendPos * ch
for k = 1, take * ch do
writef32(ob, q, src[s + k])
q += 4
end
pendPos += take
got += take
end
pos += got
return ob, got
end
function dec.seek(_self: any, seconds: number)
local sec = if type(seconds) == "number" and seconds == seconds then seconds else 0
local target = math.clamp(math.floor(sec * sr + 0.5), 0, frames) + skip -- absolute frame
-- the last packet starting at or before the target, minus the codec's pre-roll
local lo, hi, found = 1, count, 1
while lo <= hi do
local mid = (lo + hi) // 2
if startOf(mid) <= target then
found = mid
lo = mid + 1
else
hi = mid - 1
end
end
found = math.max(1, found - preroll)
spec.reset()
nextPacket = found
decoded = if count > 0 then startOf(found) else 0
dropUntil = target
pendPos, pendN = 0, 0
failed = nil
dec.error = nil
pos = target - skip
end
function dec.position(_self: any): number
return pos / sr
end
-- prime: surface a broken first packet as an open error
if count > 0 and frames > 0 and not fill() and failed then
return nil, failed
end
return dec, nil
end
return Stream
@@ -1,10 +1,10 @@
--!strict
--!native
-- codecs/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample
-- codecs/audio/Tracker/Mixer: mixes the player's active voices into an interleaved stereo f32 buffer. Per voice: sample
-- loops (forward, ping-pong, IT sustain loops while the key is held), linear or no interpolation, the IT two-pole
-- resonant filter, and a short gain ramp per tick against clicks. Written for this library (no third-party code).
--
-- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/Tracker)
-- Never throws: sample indexes are clamped to the sample, every loop is bounded, and the caller (codecs/audio/Tracker)
-- validates the sample buffers' sizes.
local floor, ceil, min = math.floor, math.ceil, math.min
local readf32, writef32 = buffer.readf32, buffer.writef32
@@ -1,6 +1,6 @@
--!strict
--!native
-- codecs/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned,
-- codecs/audio/Tracker/Pcm: sample data conversions shared by the tracker formats. Raw 8 / 16-bit PCM (signed or unsigned,
-- plain or delta coded as in XM / IT 2.15, interleaved or planar stereo) to the engine's f32 samples, and back.
--
-- Never throws: reads past the source are refused up front (decode returns nil).
@@ -1,15 +1,15 @@
--!strict
--!native
-- codecs/Tracker/Player: the sequencer of the tracker engine. One player for MOD, S3M, XM and IT: rows, orders,
-- codecs/audio/Tracker/Player: the sequencer of the tracker engine. One player for MOD, S3M, XM and IT: rows, orders,
-- speed / tempo, every effect of the four formats (interpreted per format family: ProTracker / FastTracker 2 numeric
-- effects, ScreamTracker 3 / Impulse Tracker letter effects), instruments with volume / panning / pitch envelopes,
-- fadeout and auto-vibrato, IT new note actions (background voices), duplicate checks and resonant filters, and song
-- end / loop detection. Written from the format documents (ProTracker 2.3 docs, the XM spec and FT2 behaviour notes,
-- ST3 TECH.DOC, ITTECH.TXT); no third-party code. Mixing is codecs/Tracker/Mixer.
-- ST3 TECH.DOC, ITTECH.TXT); no third-party code. Mixing is codecs/audio/Tracker/Mixer.
--
-- Never throws: the module is validated by codecs/Tracker before a player is made, and every table lookup here is
-- Never throws: the module is validated by codecs/audio/Tracker before a player is made, and every table lookup here is
-- guarded.
local Tables = require("@formats/codecs/Tracker/Tables")
local Tables = require("@formats/codecs/audio/Tracker/Tables")
local wave64, autoWave = Tables.wave64, Tables.autoWave
local AMIGA = Tables.AMIGA
@@ -322,7 +322,7 @@ local function advanceRow(st: any)
end
-- ------------------------------------------------------------------------------------------------ pitch
-- the period of a note for a sample (see codecs/Tracker for the two period spaces)
-- the period of a note for a sample (see codecs/audio/Tracker for the two period spaces)
local function notePeriod(st: any, note: number, smp: any, ft: number?): (number, number)
local base, ref, tr
if st.fmt == MOD or st.fmt == XM then
@@ -1,6 +1,6 @@
--!strict
--!native
-- codecs/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the
-- codecs/audio/Tracker/Tables: lookup tables of the tracker engine. Waveforms for vibrato / tremolo / panbrello and the
-- auto-vibrato, the ProTracker period table (finetune 0, used to map MOD periods to notes and back) and the IT / S3M
-- volume-column tone-portamento and retrigger tables. All values are from the public format documents (ProTracker
-- 2.3 effect docs, FT2 / XM spec, ST3 TECH.DOC, ITTECH.TXT).
@@ -1,10 +1,10 @@
--!strict
-- codecs/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
-- codecs/audio/Tracker: the shared tracker engine behind music/mod, music/s3m, music/xm and music/it. The four loaders read
-- their files into one Module structure (below); render(module, opts) plays any of them through the standard audio
-- Decoder (Types.Decoder: stereo f32). Written for this library from the format documents (ProTracker 2.3, the XM
-- spec + FT2 behaviour, ST3 TECH.DOC, ITTECH.TXT); libxmp / OpenMPT were used only as reference players for tests.
--
-- local Tracker = require("@formats/codecs/Tracker")
-- local Tracker = require("@formats/codecs/audio/Tracker")
-- local dec, err = Tracker.render(module, { sampleRate = 44100 }) -- a Types.Decoder
-- local seconds = Tracker.duration(module) -- one pass, song loops detected
--
@@ -48,10 +48,10 @@
-- (S2x), random volume / pan variation, OPL (AdLib) instruments, MOD Amiga low-pass filter emulation.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Player = require("@formats/codecs/Tracker/Player")
local Mixer = require("@formats/codecs/Tracker/Mixer")
local Pcm = require("@formats/codecs/Tracker/Pcm")
local Tables = require("@formats/codecs/Tracker/Tables")
local Player = require("@formats/codecs/audio/Tracker/Player")
local Mixer = require("@formats/codecs/audio/Tracker/Mixer")
local Pcm = require("@formats/codecs/audio/Tracker/Pcm")
local Tables = require("@formats/codecs/audio/Tracker/Tables")
local Tracker = {}
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- audio/vorbis/Codebook: the Vorbis LSB-first packet bit reader and codebooks (Vorbis I spec sections 2 and 3):
-- codecs/audio/Vorbis/Codebook: the Vorbis LSB-first packet bit reader and codebooks (Vorbis I spec sections 2 and 3):
-- reading a codebook from the setup header (ordered / sparse length lists, lookup types 1 and 2, float32_unpack),
-- the codeword assignment, and Huffman / VQ decoding. Ported from stb_vorbis 1.22 (public domain / MIT; see
-- licenses/stb_vorbis-LICENSE.txt): compute_codewords' lowest-free-leaf assignment, lookup1_values; the decode side
@@ -1,8 +1,8 @@
--!strict
--!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.
-- codecs/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/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
@@ -13,10 +13,10 @@
-- Packet.reset(st) -- forget the overlap (after a seek / a gap)
-- local bs = Packet.blocksize(st, buf, offset, size) -- the packet's block size (0 = not audio), header bits only
-- Never throws: a damaged packet decodes as far as its bits go (the spec's end-of-packet rule) or returns -1.
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 Codebook = require("@formats/codecs/audio/Vorbis/Codebook")
local Setup = require("@formats/codecs/audio/Vorbis/Setup")
local Tables = require("@formats/codecs/audio/Vorbis/Tables")
local Mdct = require("@formats/codecs/audio/Mdct")
local Packet = {}
@@ -1,11 +1,11 @@
--!strict
--!native
-- audio/vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2): identification (channels, rate,
-- codecs/audio/Vorbis/Setup: the three Vorbis header packets (Vorbis I spec section 4.2): identification (channels, rate,
-- bitrates, blocksizes), comment (vendor + user comments -> tags) and setup (codebooks, floors, residues, mappings,
-- modes). Ported from stb_vorbis 1.22 start_decoder (public domain / MIT; see licenses/stb_vorbis-LICENSE.txt).
-- Floor 0 is rejected as unsupported, as stb_vorbis does (no encoder has produced it since 2000).
-- Never throws: every parser returns nil, message on bad data.
local Codebook = require("@formats/audio/vorbis/Codebook")
local Codebook = require("@formats/codecs/audio/Vorbis/Codebook")
local Setup = {}
@@ -1,5 +1,5 @@
--!strict
-- audio/vorbis/Tables: the floor 1 inverse dB table (Vorbis I specification, section 10.1, as in stb_vorbis 1.22,
-- codecs/audio/Vorbis/Tables: the floor 1 inverse dB table (Vorbis I specification, section 10.1, as in stb_vorbis 1.22,
-- public domain / MIT, licenses/stb_vorbis-LICENSE.txt). 256 values, index = floor value (1-based here).
return table.freeze({
1.0649863e-07, 1.1341951e-07, 1.2079015e-07, 1.2863978e-07, 1.3699951e-07, 1.4590251e-07, 1.5538408e-07, 1.6548181e-07,
+13
View File
@@ -0,0 +1,13 @@
--!strict
-- codecs/audio/Vorbis: the Vorbis I decoder without its container: identification / comment / setup headers (Setup),
-- codebooks (Codebook), audio packets to PCM (Packet: floors 0 / 1, residues 0 / 1 / 2, coupling, the IMDCT through
-- codecs/audio/Mdct) and the shared tables. A Luau port of stb_vorbis 1.22 (public domain / MIT,
-- licenses/stb_vorbis-LICENSE.txt). Ogg Vorbis (pages, granules, seeking) and the encoder are audio/vorbis.
local Vorbis = {
Setup = require("@formats/codecs/audio/Vorbis/Setup"),
Codebook = require("@formats/codecs/audio/Vorbis/Codebook"),
Packet = require("@formats/codecs/audio/Vorbis/Packet"),
Tables = require("@formats/codecs/audio/Vorbis/Tables"),
}
return Vorbis
@@ -0,0 +1,62 @@
--!strict
-- 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
-- "; " in tags; the raw fields stay available (decoders put them in meta.source.comments). Shared so the three
-- formats read and write tags the same way. Never throws.
--
-- local tags, raw = VorbisComment.tags({ "TITLE=x", "TRACKNUMBER=3" }) -- { title = "x", track = "3" }, raw list
-- local fields = VorbisComment.fields(tags) -- sorted { "TITLE=x", "TRACKNUMBER=3" }
local VorbisComment = {}
export type Field = { key: string, value: string } -- key as written (upper-cased), value
local TO_TAG: { [string]: string } = { tracknumber = "track", discnumber = "disc", description = "comment" }
local TO_FIELD: { [string]: string } = { track = "TRACKNUMBER", disc = "DISCNUMBER" }
-- tagKey(fieldName) -> the Types.Tags key
function VorbisComment.tagKey(name: string): string
local k = string.lower(name)
return TO_TAG[k] or k
end
-- fieldName(tagKey) -> the Vorbis comment field name
function VorbisComment.fieldName(key: string): string
return TO_FIELD[key] or string.upper(key)
end
-- tags(list of "KEY=value") -> Types.Tags, { Field } (entries without "=" are skipped)
function VorbisComment.tags(comments: { string }): ({ [string]: string }, { Field })
local tags: { [string]: string } = {}
local raw: { Field } = {}
for _, s in comments do
local eq = string.find(s, "=", 1, true)
if eq then
local name, v = string.sub(s, 1, eq - 1), string.sub(s, eq + 1)
table.insert(raw, { key = string.upper(name), value = v })
local k = VorbisComment.tagKey(name)
local old = tags[k]
tags[k] = if old then old .. "; " .. v else v
end
end
return tags, raw
end
-- fields(tags) -> "KEY=value" strings in key order (string keys and values only)
function VorbisComment.fields(tags: { [any]: any }): { string }
local keys = {}
for k, v in tags do
if type(k) == "string" and type(v) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
local out: { string } = table.create(#keys) :: any
for i, k in keys do
out[i] = VorbisComment.fieldName(k) .. "=" .. tags[k]
end
return out
end
return VorbisComment
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Brotli/Decode: a Brotli (RFC 7932) decoder over a whole in-memory stream. Written from the RFC, with the
-- codecs/compress/Brotli/Decode: a Brotli (RFC 7932) decoder over a whole in-memory stream. Written from the RFC, with the
-- reference decoder (google/brotli c/dec/decode.c, MIT) as the authority on edge cases (simple prefix code alphabet
-- widths, repeat codes, padding checks, the large-window extension). Supports every meta-block kind (compressed,
-- uncompressed, metadata), block types / counts, the four literal context modes, context maps with RLE and inverse
@@ -1,5 +1,5 @@
--!strict
-- codecs/Brotli/Static: GENERATED by tools/brotli_static.py from the brotli C sources (MIT, Google; see
-- codecs/compress/Brotli/Static: GENERATED by tools/brotli_static.py from the brotli C sources (MIT, Google; see
-- licenses/brotli-LICENSE.txt) - do not edit. The RFC 7932 static dictionary (122784 bytes, deflated, base64),
-- the context lookup table (Appendix B, 4 modes x 512) and the 121 word transforms (Appendix B).
return {
@@ -1,21 +1,23 @@
--!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 })
--
-- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / LIMIT / UNSUPPORTED / ARG).
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 Decode = require("@formats/codecs/Brotli/Decode")
local StaticData = require("@formats/codecs/Brotli/Static")
local Base64 = require("@formats/core/Base64")
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 = {}
@@ -25,37 +27,9 @@ export type Options = {
}
-- ------------------------------------------------------------------------------------------------ static data
local B64 = {}
do
local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
for i = 1, 64 do
B64[string.byte(alphabet, i)] = i - 1
end
end
-- the tables are base64 text (trusted, generated by tools/brotli_static.py)
local function unbase64(s: string): buffer
local n = #s
local pad = 0
if string.sub(s, -2) == "==" then
pad = 2
elseif string.sub(s, -1) == "=" then
pad = 1
end
local out = buffer.create(n // 4 * 3 - pad)
local o = 0
for i = 1, n, 4 do
local a, b, c, d = string.byte(s, i, i + 3)
local v = B64[a] * 262144 + B64[b] * 4096 + (B64[c] or 0) * 64 + (B64[d] or 0)
buffer.writeu8(out, o, v // 65536)
if o + 1 < buffer.len(out) then
buffer.writeu8(out, o + 1, (v // 256) % 256)
end
if o + 2 < buffer.len(out) then
buffer.writeu8(out, o + 2, v % 256)
end
o += 3
end
return out
return Base64.decode(s) or buffer.create(0)
end
local static: Decode.Static? = nil
@@ -90,30 +64,14 @@ function Brotli.dictionary(): buffer?
end
-- ------------------------------------------------------------------------------------------------ decompress
local function toBuffer(b: any): buffer?
if type(b) == "string" then
return buffer.fromstring(b)
end
return if type(b) == "buffer" then b else nil
end
-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. consumedEnd: the input offset just past
-- the stream (trailing bytes are ignored).
function Brotli.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
local b = toBuffer(buf)
local b, o, l, aerr = Bytes.span("Brotli.decompress", buf, offset, length)
if not b then
return nil, Err.new(Err.ARG, "Brotli.decompress: expected a buffer or a string, got " .. typeof(buf))
return nil, aerr
end
local n = buffer.len(b)
local o = offset or 0
if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Brotli.decompress: bad offset " .. tostring(offset))
end
local l = length or (n - o)
if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Brotli.decompress: bad length " .. tostring(length))
end
l = math.min(l, n - o)
local maxBytes = if opts and opts.maxBytes then opts.maxBytes else 2 ^ 30
if type(maxBytes) ~= "number" or maxBytes < 0 then
return nil, Err.new(Err.ARG, "Brotli.decompress: bad maxBytes")
@@ -128,16 +86,9 @@ function Brotli.decompress(buf: buffer | string, offset: number?, length: number
end
local out, size, consumed = Decode.decompress(b, o, l, maxBytes, S, large)
if not out then
local msg = tostring(size)
local code = Err.CORRUPT
if string.find(msg, "truncated", 1, true) then
code = Err.TRUNCATED
elseif string.sub(msg, 1, 6) == "limit:" then
code = Err.LIMIT
elseif string.sub(msg, 1, 12) == "unsupported:" then
code = Err.UNSUPPORTED
end
return nil, Err.new(code, "brotli: " .. msg, o)
local e = Err.from(size, o)
e.message = "brotli: " .. e.message
return nil, e
end
local res = out
if buffer.len(out) ~= size then
@@ -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
@@ -11,25 +11,15 @@
--
-- Never throws: every buffer access is in range by construction; failures return nil, message, kind
-- ("truncated" | "corrupt" | "checksum" | "limit" | "unsupported").
local Crc32 = require("@formats/core/Crc32")
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32
local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len
local Decode = {}
-- CRC-32/BZIP2 table (polynomial 0x04C11DB7, not reflected)
local CT = table.create(256, 0)
for i = 0, 255 do
local c = lshift(i, 24)
for _ = 1, 8 do
if band(c, 0x80000000) ~= 0 then
c = bxor(lshift(c, 1), 0x04C11DB7)
else
c = lshift(c, 1)
end
end
CT[i + 1] = c
end
-- CRC-32/BZIP2 table (polynomial 0x04C11DB7, not reflected: core/Crc32)
local CT = Crc32.MSB_TABLE
Decode.crcTable = CT
local MASK = table.create(33, 0)
@@ -1,16 +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 Decode = require("@formats/codecs/Bzip2/Decode")
local Bytes = require("@formats/core/Bytes")
local Decode = require("@formats/codecs/compress/Bzip2/Decode")
local Bzip2 = {}
@@ -18,41 +19,19 @@ export type Options = {
maxBytes: number?, -- refuse output larger than this (default 2^30)
}
local KINDS = {
truncated = Err.TRUNCATED,
corrupt = Err.CORRUPT,
checksum = Err.CHECKSUM,
limit = Err.LIMIT,
unsupported = Err.UNSUPPORTED,
}
-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err
function Bzip2.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
local b: buffer
if type(buf) == "string" then
b = buffer.fromstring(buf)
elseif type(buf) == "buffer" then
b = buf
else
return nil, Err.new(Err.ARG, "Bzip2.decompress: expected a buffer or a string, got " .. typeof(buf))
local b, o, l, aerr = Bytes.span("Bzip2.decompress", buf, offset, length)
if not b then
return nil, aerr
end
local n = buffer.len(b)
local o = offset or 0
if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Bzip2.decompress: bad offset " .. tostring(offset))
end
local l = length or (n - o)
if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Bzip2.decompress: bad length " .. tostring(length))
end
l = math.min(l, n - o)
local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30
if type(maxBytes) ~= "number" or maxBytes < 0 then
return nil, Err.new(Err.ARG, "Bzip2.decompress: bad maxBytes")
end
local out, nOut, consumed = Decode.decode(b, o, o + l, maxBytes)
if not out then
return nil, Err.new(KINDS[consumed] or Err.CORRUPT, "bzip2: " .. tostring(nOut), o)
return nil, Err.from("bzip2: " .. tostring(nOut), o, consumed)
end
local res = out
if buffer.len(out) ~= nOut then
@@ -1,12 +1,12 @@
--!strict
--!native
--!optimize 2
-- codecs/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth
-- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (core/Huffman
-- codecs/compress/Deflate/Compress: a DEFLATE (RFC 1951) compressor. LZ77 over a 32 KB window with hash chains (chain depth
-- and lazy matching by level), then per block the cheapest of stored / fixed-Huffman / dynamic-Huffman (codecs/entropy/Huffman
-- length-limited codes). Level 0 = stored blocks only.
--
-- raw(buf, off, len, level) -> buffer. Never throws (the caller validated the arguments).
local Huffman = require("@formats/core/Huffman")
local Huffman = require("@formats/codecs/entropy/Huffman")
local readu8, writeu8, writeu16 = buffer.readu8, buffer.writeu8, buffer.writeu16
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
@@ -1,17 +1,17 @@
--!strict
--!native
--!optimize 2
-- codecs/Deflate/Inflate: raw DEFLATE (RFC 1951) decoder: stored, fixed-Huffman and dynamic-Huffman blocks.
-- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author); the table builder moved to core/Huffman, whose
-- codecs/compress/Deflate/Inflate: raw DEFLATE (RFC 1951) decoder: stored, fixed-Huffman and dynamic-Huffman blocks.
-- Absorbed from deflate-luau src/Deflate/Inflate.luau (same author); the table builder moved to codecs/entropy/Huffman, whose
-- entries are symbol * 32 + length (5 length bits instead of 4).
--
-- Bits are read LSB first into a 32-bit bit buffer (refilled 4 bytes at a time with one readu32 while the input
-- lasts). Huffman codes decode through a core/Huffman LSB table indexed by the next LITBITS / DISTBITS bits; a longer
-- lasts). Huffman codes decode through a codecs/entropy/Huffman LSB table indexed by the next LITBITS / DISTBITS bits; a longer
-- code's primary slot links to a subtable, so a symbol is one or two table reads.
--
-- Nothing in this module throws on any input: every buffer read and write is bounds-checked, and corrupt data
-- returns nil, message. (Native code must never throw: it crashes Roblox Studio.)
local Huffman = require("@formats/core/Huffman")
local Huffman = require("@formats/codecs/entropy/Huffman")
local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift
local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
@@ -38,7 +38,7 @@ local CLCAP = Huffman.capacity(19, CLBITS, 7)
-- fixed Huffman tables
local FLIT, FDIST = bcreate(LITCAP * 4), bcreate(DISTCAP * 4)
local FLITS, FDISTS
local FLITS: number, FDISTS: number
do
local l = bcreate(288)
bfill(l, 0, 8, 144)
@@ -69,7 +69,7 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex
local op = 0
local pos = start
local bitbuf, bitcnt, over = 0, 0, 0
local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4)
local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) :: buffer
local clt = bcreate(CLCAP * 4)
local lens = bcreate(320)
local final = 0
@@ -132,13 +132,13 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex
pos += n
continue
end
local lsub, dsub
local lsub: number, dsub: number
if btype == 1 then
lt, dt = FLIT, FDIST
lsub, dsub = FLITS, FDISTS
elseif btype == 2 then
if lt == FLIT then
lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4)
lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) :: buffer
end
local hlit = band(bitbuf, 31) + 257
local hdist = band(rshift(bitbuf, 5), 31) + 1
@@ -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
@@ -12,53 +12,18 @@
--
-- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG).
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 = {}
Deflate.version = "1.1.0"
local function toBuffer(b: any): buffer?
if type(b) == "string" then
return buffer.fromstring(b)
end
if type(b) ~= "buffer" then
return nil
end
return b
end
-- (offset, length) clamped to the buffer; nil for non-numbers / negative / fractional / out-of-range offsets
local function range(b: buffer, off: number?, len: number?): (number?, number)
local n = buffer.len(b)
local o = off or 0
if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then
return nil, 0
end
local l = len or (n - o)
if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then
return nil, 0
end
if o + l > n then
l = n - o
end
return o, l
end
local function args(what: string, buf: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?)
local b = toBuffer(buf)
if not b then
return nil, 0, 0, Err.new(Err.ARG, what .. ": expected a buffer or a string, got " .. typeof(buf))
end
local o, l = range(b, offset, length)
if not o then
return nil, 0, 0, Err.new(Err.ARG, what .. ": bad offset / length " .. tostring(offset) .. ", " .. tostring(length))
end
return b, o, l, nil
end
local toBuffer = Bytes.toBuffer
local args = Bytes.span
local function shrink(out: buffer, n: number): buffer
if buffer.len(out) == n then
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), the xz check type 4. The 64-bit
-- codecs/compress/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), the xz check type 4. The 64-bit
-- value is kept as two u32 halves (hi, lo). Written from the xz file format specification. Never throws.
local band, bxor, rshift, lshift, bor = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift, bit32.bor
local readu8 = buffer.readu8
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by raw LZMA (.lzma, 7z) and LZMA2 (xz, 7z).
-- codecs/compress/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by raw LZMA (.lzma, 7z) and LZMA2 (xz, 7z).
-- Written from the LZMA specification and its reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain); the
-- structure (probability model layout, state transitions, distance / length decoding) follows that document.
--
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Lzma/Filters: the branch-call-jump (BCJ) and delta decoding filters of xz and 7z, run in place over a whole
-- codecs/compress/Lzma/Filters: the branch-call-jump (BCJ) and delta decoding filters of xz and 7z, run in place over a whole
-- decoded buffer range. Written from the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin,
-- public domain): x86, ARM, ARM-Thumb, PowerPC, SPARC, ARM64 and delta. Not supported: IA-64, RISC-V.
-- Never throws: every access is inside [o, o + n).
@@ -1,10 +1,10 @@
--!strict
-- codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
-- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
-- archive/xz, archive/7z (and anything else holding LZMA data) build on it. Decode only.
-- Written from the LZMA specification (LzmaSpec.cpp, Igor Pavlov, public domain) and the xz file format specification
-- 1.2 (Lasse Collin / Igor Pavlov, public domain); the BCJ filters follow xz-embedded (public domain).
--
-- local Lzma = require("@formats/codecs/Lzma")
-- local Lzma = require("@formats/codecs/compress/Lzma")
-- local out, e = Lzma.lzma(buf, off, len, props, unpackSize?, opts?) -- raw LZMA; props = 5-byte buffer / string
-- -- or { lc, lp, pb, dictSize }
-- local out, e = Lzma.lzma2(buf, off, len, dictSize?, unpackSize?, opts?) -- raw LZMA2 chunks
@@ -17,10 +17,11 @@
-- none / CRC-32 / CRC-64 are verified, SHA-256 is skipped (not verified). xz filters: LZMA2, delta, x86, PowerPC,
-- ARM, ARM-Thumb, SPARC, ARM64; IA-64 and RISC-V are Err.UNSUPPORTED. Never throws.
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
@@ -33,43 +34,8 @@ export type Options = {
}
export type Props = { lc: number, lp: number, pb: number, dictSize: number? }
local function toBuffer(b: any): buffer?
if type(b) == "string" then
return buffer.fromstring(b)
end
if type(b) ~= "buffer" then
return nil
end
return b
end
local function range(b: buffer, off: number?, len: number?): (number?, number)
local n = buffer.len(b)
local o = off or 0
if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then
return nil, 0
end
local l = len or (n - o)
if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then
return nil, 0
end
if o + l > n then
l = n - o
end
return o, l
end
local function args(what: string, buf: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?)
local b = toBuffer(buf)
if not b then
return nil, 0, 0, Err.new(Err.ARG, what .. ": expected a buffer or a string, got " .. typeof(buf))
end
local o, l = range(b, offset, length)
if not o then
return nil, 0, 0, Err.new(Err.ARG, what .. ": bad offset / length " .. tostring(offset) .. ", " .. tostring(length))
end
return b, o, l, nil
end
local toBuffer = Bytes.toBuffer
local args = Bytes.span
local function maxOf(opts: Options?): number
local m = opts and opts.maxBytes
@@ -319,7 +285,7 @@ function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?):
return nil, Err.new(Err.CORRUPT, "bad delta filter properties")
end
Filters.delta(b, o, n, readu8(pb :: buffer, 0) + 1)
return true
return true, nil
end
local f = BCJ[id]
if not f then
@@ -332,7 +298,7 @@ function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?):
return nil, Err.new(Err.CORRUPT, "bad BCJ filter properties")
end
f(b, o, n, start)
return true
return true, nil
end
-- ------------------------------------------------------------------------------------------------ xz
@@ -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).
+95
View File
@@ -0,0 +1,95 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF
-- ByteRun1, ...): a header byte n < 128 copies n + 1 literal bytes, n > 128 repeats the next byte 257 - n times,
-- 128 is a no-op. Decode and encode; moved here from image/tiff (TIFF and PSD both carried a decoder). Never throws.
--
-- local written, srcEnd, clean = PackBits.decode(src, p, limit, dst, d, n) -- up to n bytes into dst at d
-- local packed = PackBits.encode(src, offset, length) -- a buffer (one row at a time)
local PackBits = {}
local readu8, writeu8 = buffer.readu8, buffer.writeu8
-- decode(src, p, limit, dst, d, n) -> bytes written (<= n), the source offset after the codes used, clean (false when
-- the source ran out before n bytes or a run overflowed n: lenient callers keep what was written, strict ones fail)
function PackBits.decode(src: buffer, p: number, limit: number, dst: buffer, d: number, n: number): (number, number, boolean)
local o, lim = d, d + n
local clean = true
while o < lim do
if p >= limit then
clean = false
break
end
local h = readu8(src, p)
p += 1
if h < 128 then
local want = h + 1
local cnt = math.min(want, limit - p, lim - o)
if cnt < want then
clean = false
end
if cnt > 0 then
buffer.copy(dst, o, src, p, cnt)
o += cnt
end
p += want
if p > limit then
p = limit
break
end
elseif h > 128 then
if p >= limit then
clean = false
break
end
local want = 257 - h
local cnt = math.min(want, lim - o)
if cnt < want then
clean = false
end
buffer.fill(dst, o, readu8(src, p), cnt)
p += 1
o += cnt
end
end
return o - d, p, clean
end
-- encode(src, offset, length) -> buffer: runs of 3+ equal bytes as repeats, the rest as literals (at most 128 each)
function PackBits.encode(src: buffer, off: number, len: number): buffer
local out = buffer.create(len + (len + 127) // 128 + 8)
local o = 0
local p, e = off, off + len
while p < e do
local run = 1
local v = readu8(src, p)
while p + run < e and run < 128 and readu8(src, p + run) == v do
run += 1
end
if run >= 3 then
writeu8(out, o, 257 - run)
writeu8(out, o + 1, v)
o += 2
p += run
else
local s = p
local n = 0
while p < e and n < 128 do
if p + 2 < e and readu8(src, p) == readu8(src, p + 1) and readu8(src, p) == readu8(src, p + 2) then
break
end
p += 1
n += 1
end
writeu8(out, o, n - 1)
buffer.copy(out, o + 1, src, s, n)
o += n + 1
end
end
local r = buffer.create(o)
buffer.copy(r, 0, out, 0, o)
return r
end
return PackBits
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no code copied from the
-- codecs/compress/Zstd/Decode: Zstandard frame decoder (RFC 8878), written from the specification (no code copied from the
-- BSD reference implementation). Frames (any number, concatenated), skippable frames, raw / RLE / compressed blocks,
-- Huffman literals (1 or 4 streams, new or repeated table), FSE sequence tables (predefined / RLE / compressed /
-- repeat), repeat offsets, the XXH64 content checksum. Not supported: dictionaries (a non-zero dictionary ID).
@@ -11,7 +11,7 @@
-- byte (o - n) / 8, bits before the stream start read as zeros.
--
-- Nothing here throws on any input: every read is bounds-checked; failures return nil, code, message, offset.
local Xxh64 = require("@formats/codecs/Zstd/Xxh64")
local Xxh64 = require("@formats/codecs/compress/Zstd/Xxh64")
local band, lshift, rshift = bit32.band, bit32.lshift, bit32.rshift
local readu8, readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32
@@ -1,7 +1,7 @@
--!strict
--!native
--!optimize 2
-- codecs/Zstd/Xxh64: XXH64 (seed 0) of a buffer range, computed on 32-bit halves held in doubles (Luau and LuaJIT have
-- codecs/compress/Zstd/Xxh64: XXH64 (seed 0) of a buffer range, computed on 32-bit halves held in doubles (Luau and LuaJIT have
-- no 64-bit integers). 64 x 64 -> 64 products split the low operand into 16-bit limbs so every partial product is
-- exact below 2^53. From the xxHash specification (Yann Collet, BSD-2); no code copied. zstd stores the low 32 bits
-- of the hash as the frame content checksum. Never throws (the caller passes an in-range buffer slice).
@@ -122,7 +122,7 @@ function Xxh64.hash(b: buffer, offset: number, length: number): (number, number)
hh, hl = add(hh, hl, math.floor(length / T32) % T32, length % T32)
while p + 8 <= e do
local kh, kl = round(0, 0, readu32(b, p + 4), readu32(b, p))
hh, hl = bxor(hh, kh), bxor(hl, kl)
hh, hl = bxor(hh, kh), bxor(hl, kl) :: number
hh, hl = rotl(hh, hl, 27)
hh, hl = mul(hh, hl, P1H, P1L)
hh, hl = add(hh, hl, P4H, P4L)
@@ -130,7 +130,7 @@ function Xxh64.hash(b: buffer, offset: number, length: number): (number, number)
end
if p + 4 <= e then
local kh, kl = mul(0, readu32(b, p), P1H, P1L)
hh, hl = bxor(hh, kh), bxor(hl, kl)
hh, hl = bxor(hh, kh), bxor(hl, kl) :: number
hh, hl = rotl(hh, hl, 23)
hh, hl = mul(hh, hl, P2H, P2L)
hh, hl = add(hh, hl, P3H, P3L)
@@ -138,7 +138,7 @@ function Xxh64.hash(b: buffer, offset: number, length: number): (number, number)
end
while p < e do
local kh, kl = mul(0, readu8(b, p), P5H, P5L)
hh, hl = bxor(hh, kh), bxor(hl, kl)
hh, hl = bxor(hh, kh), bxor(hl, kl) :: number
hh, hl = rotl(hh, hl, 11)
hh, hl = mul(hh, hl, P1H, P1L)
p += 1
@@ -146,7 +146,7 @@ function Xxh64.hash(b: buffer, offset: number, length: number): (number, number)
-- avalanche
hl = bxor(hl, rshift(hh, 1)) -- h ^= h >> 33
hh, hl = mul(hh, hl, P2H, P2L)
hh, hl = bxor(hh, rshift(hh, 29)), bxor(hl, bor(rshift(hl, 29), lshift(hh, 3))) -- h ^= h >> 29
hh, hl = bxor(hh, rshift(hh, 29)), bxor(hl, bor(rshift(hl, 29), lshift(hh, 3))) :: number -- h ^= h >> 29
hh, hl = mul(hh, hl, P3H, P3L)
hl = bxor(hl, hh) -- h ^= h >> 32
return hh, hl
@@ -1,17 +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 Decode = require("@formats/codecs/Zstd/Decode")
local Bytes = require("@formats/core/Bytes")
local Decode = require("@formats/codecs/compress/Zstd/Decode")
local Zstd = {}
@@ -20,14 +21,6 @@ export type Options = {
verify: boolean?, -- check the content checksum when a frame has one (default true)
}
local CODES: { [string]: string } = {
TRUNCATED = Err.TRUNCATED,
CORRUPT = Err.CORRUPT,
CHECKSUM = Err.CHECKSUM,
UNSUPPORTED = Err.UNSUPPORTED,
LIMIT = Err.LIMIT,
}
-- magic numbers: a zstd frame, and skippable frames (0x184D2A50 .. 0x184D2A5F)
Zstd.MAGIC = "\40\181\47\253"
@@ -44,24 +37,10 @@ end
-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err. Every frame in the range is decoded
-- and the outputs concatenated; data after the last frame that is not a frame is an error (as zstd -d does).
function Zstd.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
local b: buffer
if type(buf) == "string" then
b = buffer.fromstring(buf)
elseif type(buf) == "buffer" then
b = buf
else
return nil, Err.new(Err.ARG, "Zstd.decompress: expected a buffer or a string, got " .. typeof(buf))
local b, o, l, aerr = Bytes.span("Zstd.decompress", buf, offset, length)
if not b then
return nil, aerr
end
local n = buffer.len(b)
local o = offset or 0
if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Zstd.decompress: bad offset " .. tostring(offset))
end
local l = length or (n - o)
if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Zstd.decompress: bad length " .. tostring(length))
end
l = math.min(l, n - o)
local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30
if type(maxBytes) ~= "number" or maxBytes < 0 then
return nil, Err.new(Err.ARG, "Zstd.decompress: bad maxBytes " .. tostring(maxBytes))
@@ -69,7 +48,7 @@ function Zstd.decompress(buf: buffer | string, offset: number?, length: number?,
local verify = not (opts and opts.verify == false)
local out, len, consumed, at = Decode.decompress(b, o, o + l, maxBytes, verify)
if not out then
return nil, Err.new(CODES[len] or Err.CORRUPT, tostring(consumed), at)
return nil, Err.from(consumed, at, len)
end
if buffer.len(out) ~= len then
local r = buffer.create(len)
Loaded 100 of 369 files, more files were not shown because too many files have changed in this diff. Show more